three.js 796 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. * @author bhouston / http://exocortex.com
  5. */
  6. var THREE = { REVISION: '65dev' };
  7. self.console = self.console || {
  8. info: function () {},
  9. log: function () {},
  10. debug: function () {},
  11. warn: function () {},
  12. error: function () {}
  13. };
  14. String.prototype.trim = String.prototype.trim || function () {
  15. return this.replace( /^\s+|\s+$/g, '' );
  16. };
  17. // based on https://github.com/documentcloud/underscore/blob/bf657be243a075b5e72acc8a83e6f12a564d8f55/underscore.js#L767
  18. THREE.extend = function ( obj, source ) {
  19. // ECMAScript5 compatibility based on: http://www.nczonline.net/blog/2012/12/11/are-your-mixins-ecmascript-5-compatible/
  20. if ( Object.keys ) {
  21. var keys = Object.keys( source );
  22. for (var i = 0, il = keys.length; i < il; i++) {
  23. var prop = keys[i];
  24. Object.defineProperty( obj, prop, Object.getOwnPropertyDescriptor( source, prop ) );
  25. }
  26. } else {
  27. var safeHasOwnProperty = {}.hasOwnProperty;
  28. for ( var prop in source ) {
  29. if ( safeHasOwnProperty.call( source, prop ) ) {
  30. obj[prop] = source[prop];
  31. }
  32. }
  33. }
  34. return obj;
  35. };
  36. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  37. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  38. // requestAnimationFrame polyfill by Erik Möller
  39. // fixes from Paul Irish and Tino Zijdel
  40. // using 'self' instead of 'window' for compatibility with both NodeJS and IE10.
  41. ( function () {
  42. var lastTime = 0;
  43. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  44. for ( var x = 0; x < vendors.length && !self.requestAnimationFrame; ++ x ) {
  45. self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ];
  46. self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  47. }
  48. if ( self.requestAnimationFrame === undefined && self['setTimeout'] !== undefined ) {
  49. self.requestAnimationFrame = function ( callback ) {
  50. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  51. var id = self.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  52. lastTime = currTime + timeToCall;
  53. return id;
  54. };
  55. }
  56. if( self.cancelAnimationFrame === undefined && self['clearTimeout'] !== undefined ) {
  57. self.cancelAnimationFrame = function ( id ) { self.clearTimeout( id ) };
  58. }
  59. }() );
  60. // GL STATE CONSTANTS
  61. THREE.CullFaceNone = 0;
  62. THREE.CullFaceBack = 1;
  63. THREE.CullFaceFront = 2;
  64. THREE.CullFaceFrontBack = 3;
  65. THREE.FrontFaceDirectionCW = 0;
  66. THREE.FrontFaceDirectionCCW = 1;
  67. // SHADOWING TYPES
  68. THREE.BasicShadowMap = 0;
  69. THREE.PCFShadowMap = 1;
  70. THREE.PCFSoftShadowMap = 2;
  71. // MATERIAL CONSTANTS
  72. // side
  73. THREE.FrontSide = 0;
  74. THREE.BackSide = 1;
  75. THREE.DoubleSide = 2;
  76. // shading
  77. THREE.NoShading = 0;
  78. THREE.FlatShading = 1;
  79. THREE.SmoothShading = 2;
  80. // colors
  81. THREE.NoColors = 0;
  82. THREE.FaceColors = 1;
  83. THREE.VertexColors = 2;
  84. // blending modes
  85. THREE.NoBlending = 0;
  86. THREE.NormalBlending = 1;
  87. THREE.AdditiveBlending = 2;
  88. THREE.SubtractiveBlending = 3;
  89. THREE.MultiplyBlending = 4;
  90. THREE.CustomBlending = 5;
  91. // custom blending equations
  92. // (numbers start from 100 not to clash with other
  93. // mappings to OpenGL constants defined in Texture.js)
  94. THREE.AddEquation = 100;
  95. THREE.SubtractEquation = 101;
  96. THREE.ReverseSubtractEquation = 102;
  97. // custom blending destination factors
  98. THREE.ZeroFactor = 200;
  99. THREE.OneFactor = 201;
  100. THREE.SrcColorFactor = 202;
  101. THREE.OneMinusSrcColorFactor = 203;
  102. THREE.SrcAlphaFactor = 204;
  103. THREE.OneMinusSrcAlphaFactor = 205;
  104. THREE.DstAlphaFactor = 206;
  105. THREE.OneMinusDstAlphaFactor = 207;
  106. // custom blending source factors
  107. //THREE.ZeroFactor = 200;
  108. //THREE.OneFactor = 201;
  109. //THREE.SrcAlphaFactor = 204;
  110. //THREE.OneMinusSrcAlphaFactor = 205;
  111. //THREE.DstAlphaFactor = 206;
  112. //THREE.OneMinusDstAlphaFactor = 207;
  113. THREE.DstColorFactor = 208;
  114. THREE.OneMinusDstColorFactor = 209;
  115. THREE.SrcAlphaSaturateFactor = 210;
  116. // TEXTURE CONSTANTS
  117. THREE.MultiplyOperation = 0;
  118. THREE.MixOperation = 1;
  119. THREE.AddOperation = 2;
  120. // Mapping modes
  121. THREE.UVMapping = function () {};
  122. THREE.CubeReflectionMapping = function () {};
  123. THREE.CubeRefractionMapping = function () {};
  124. THREE.SphericalReflectionMapping = function () {};
  125. THREE.SphericalRefractionMapping = function () {};
  126. // Wrapping modes
  127. THREE.RepeatWrapping = 1000;
  128. THREE.ClampToEdgeWrapping = 1001;
  129. THREE.MirroredRepeatWrapping = 1002;
  130. // Filters
  131. THREE.NearestFilter = 1003;
  132. THREE.NearestMipMapNearestFilter = 1004;
  133. THREE.NearestMipMapLinearFilter = 1005;
  134. THREE.LinearFilter = 1006;
  135. THREE.LinearMipMapNearestFilter = 1007;
  136. THREE.LinearMipMapLinearFilter = 1008;
  137. // Data types
  138. THREE.UnsignedByteType = 1009;
  139. THREE.ByteType = 1010;
  140. THREE.ShortType = 1011;
  141. THREE.UnsignedShortType = 1012;
  142. THREE.IntType = 1013;
  143. THREE.UnsignedIntType = 1014;
  144. THREE.FloatType = 1015;
  145. // Pixel types
  146. //THREE.UnsignedByteType = 1009;
  147. THREE.UnsignedShort4444Type = 1016;
  148. THREE.UnsignedShort5551Type = 1017;
  149. THREE.UnsignedShort565Type = 1018;
  150. // Pixel formats
  151. THREE.AlphaFormat = 1019;
  152. THREE.RGBFormat = 1020;
  153. THREE.RGBAFormat = 1021;
  154. THREE.LuminanceFormat = 1022;
  155. THREE.LuminanceAlphaFormat = 1023;
  156. // Compressed texture formats
  157. THREE.RGB_S3TC_DXT1_Format = 2001;
  158. THREE.RGBA_S3TC_DXT1_Format = 2002;
  159. THREE.RGBA_S3TC_DXT3_Format = 2003;
  160. THREE.RGBA_S3TC_DXT5_Format = 2004;
  161. /*
  162. // Potential future PVRTC compressed texture formats
  163. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  164. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  165. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  166. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  167. */
  168. /**
  169. * @author mrdoob / http://mrdoob.com/
  170. */
  171. THREE.Color = function ( value ) {
  172. if ( value !== undefined ) this.set( value );
  173. return this;
  174. };
  175. THREE.Color.prototype = {
  176. constructor: THREE.Color,
  177. r: 1, g: 1, b: 1,
  178. set: function ( value ) {
  179. if ( value instanceof THREE.Color ) {
  180. this.copy( value );
  181. } else if ( typeof value === 'number' ) {
  182. this.setHex( value );
  183. } else if ( typeof value === 'string' ) {
  184. this.setStyle( value );
  185. }
  186. return this;
  187. },
  188. setHex: function ( hex ) {
  189. hex = Math.floor( hex );
  190. this.r = ( hex >> 16 & 255 ) / 255;
  191. this.g = ( hex >> 8 & 255 ) / 255;
  192. this.b = ( hex & 255 ) / 255;
  193. return this;
  194. },
  195. setRGB: function ( r, g, b ) {
  196. this.r = r;
  197. this.g = g;
  198. this.b = b;
  199. return this;
  200. },
  201. setHSL: function ( h, s, l ) {
  202. // h,s,l ranges are in 0.0 - 1.0
  203. if ( s === 0 ) {
  204. this.r = this.g = this.b = l;
  205. } else {
  206. var hue2rgb = function ( p, q, t ) {
  207. if ( t < 0 ) t += 1;
  208. if ( t > 1 ) t -= 1;
  209. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  210. if ( t < 1 / 2 ) return q;
  211. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  212. return p;
  213. };
  214. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  215. var q = ( 2 * l ) - p;
  216. this.r = hue2rgb( q, p, h + 1 / 3 );
  217. this.g = hue2rgb( q, p, h );
  218. this.b = hue2rgb( q, p, h - 1 / 3 );
  219. }
  220. return this;
  221. },
  222. setStyle: function ( style ) {
  223. // rgb(255,0,0)
  224. if ( /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test( style ) ) {
  225. var color = /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec( style );
  226. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  227. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  228. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  229. return this;
  230. }
  231. // rgb(100%,0%,0%)
  232. if ( /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test( style ) ) {
  233. var color = /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec( style );
  234. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  235. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  236. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  237. return this;
  238. }
  239. // #ff0000
  240. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  241. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  242. this.setHex( parseInt( color[ 1 ], 16 ) );
  243. return this;
  244. }
  245. // #f00
  246. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  247. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  248. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  249. return this;
  250. }
  251. // red
  252. if ( /^(\w+)$/i.test( style ) ) {
  253. this.setHex( THREE.ColorKeywords[ style ] );
  254. return this;
  255. }
  256. },
  257. copy: function ( color ) {
  258. this.r = color.r;
  259. this.g = color.g;
  260. this.b = color.b;
  261. return this;
  262. },
  263. copyGammaToLinear: function ( color ) {
  264. this.r = color.r * color.r;
  265. this.g = color.g * color.g;
  266. this.b = color.b * color.b;
  267. return this;
  268. },
  269. copyLinearToGamma: function ( color ) {
  270. this.r = Math.sqrt( color.r );
  271. this.g = Math.sqrt( color.g );
  272. this.b = Math.sqrt( color.b );
  273. return this;
  274. },
  275. convertGammaToLinear: function () {
  276. var r = this.r, g = this.g, b = this.b;
  277. this.r = r * r;
  278. this.g = g * g;
  279. this.b = b * b;
  280. return this;
  281. },
  282. convertLinearToGamma: function () {
  283. this.r = Math.sqrt( this.r );
  284. this.g = Math.sqrt( this.g );
  285. this.b = Math.sqrt( this.b );
  286. return this;
  287. },
  288. getHex: function () {
  289. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  290. },
  291. getHexString: function () {
  292. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  293. },
  294. getHSL: function ( optionalTarget ) {
  295. // h,s,l ranges are in 0.0 - 1.0
  296. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  297. var r = this.r, g = this.g, b = this.b;
  298. var max = Math.max( r, g, b );
  299. var min = Math.min( r, g, b );
  300. var hue, saturation;
  301. var lightness = ( min + max ) / 2.0;
  302. if ( min === max ) {
  303. hue = 0;
  304. saturation = 0;
  305. } else {
  306. var delta = max - min;
  307. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  308. switch ( max ) {
  309. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  310. case g: hue = ( b - r ) / delta + 2; break;
  311. case b: hue = ( r - g ) / delta + 4; break;
  312. }
  313. hue /= 6;
  314. }
  315. hsl.h = hue;
  316. hsl.s = saturation;
  317. hsl.l = lightness;
  318. return hsl;
  319. },
  320. getStyle: function () {
  321. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  322. },
  323. offsetHSL: function ( h, s, l ) {
  324. var hsl = this.getHSL();
  325. hsl.h += h; hsl.s += s; hsl.l += l;
  326. this.setHSL( hsl.h, hsl.s, hsl.l );
  327. return this;
  328. },
  329. add: function ( color ) {
  330. this.r += color.r;
  331. this.g += color.g;
  332. this.b += color.b;
  333. return this;
  334. },
  335. addColors: function ( color1, color2 ) {
  336. this.r = color1.r + color2.r;
  337. this.g = color1.g + color2.g;
  338. this.b = color1.b + color2.b;
  339. return this;
  340. },
  341. addScalar: function ( s ) {
  342. this.r += s;
  343. this.g += s;
  344. this.b += s;
  345. return this;
  346. },
  347. multiply: function ( color ) {
  348. this.r *= color.r;
  349. this.g *= color.g;
  350. this.b *= color.b;
  351. return this;
  352. },
  353. multiplyScalar: function ( s ) {
  354. this.r *= s;
  355. this.g *= s;
  356. this.b *= s;
  357. return this;
  358. },
  359. lerp: function ( color, alpha ) {
  360. this.r += ( color.r - this.r ) * alpha;
  361. this.g += ( color.g - this.g ) * alpha;
  362. this.b += ( color.b - this.b ) * alpha;
  363. return this;
  364. },
  365. equals: function ( c ) {
  366. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  367. },
  368. fromArray: function ( array ) {
  369. this.r = array[ 0 ];
  370. this.g = array[ 1 ];
  371. this.b = array[ 2 ];
  372. return this;
  373. },
  374. toArray: function () {
  375. return [ this.r, this.g, this.b ];
  376. },
  377. clone: function () {
  378. return new THREE.Color().setRGB( this.r, this.g, this.b );
  379. }
  380. };
  381. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  382. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  383. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  384. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  385. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  386. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  387. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  388. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  389. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  390. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  391. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  392. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  393. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  394. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  395. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  396. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  397. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  398. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  399. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  400. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  401. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  402. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  403. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  404. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  405. /**
  406. * @author mikael emtinger / http://gomo.se/
  407. * @author alteredq / http://alteredqualia.com/
  408. * @author WestLangley / http://github.com/WestLangley
  409. * @author bhouston / http://exocortex.com
  410. */
  411. THREE.Quaternion = function ( x, y, z, w ) {
  412. this._x = x || 0;
  413. this._y = y || 0;
  414. this._z = z || 0;
  415. this._w = ( w !== undefined ) ? w : 1;
  416. };
  417. THREE.Quaternion.prototype = {
  418. constructor: THREE.Quaternion,
  419. _x: 0,_y: 0, _z: 0, _w: 0,
  420. _euler: undefined,
  421. _updateEuler: function ( callback ) {
  422. if ( this._euler !== undefined ) {
  423. this._euler.setFromQuaternion( this, undefined, false );
  424. }
  425. },
  426. get x () {
  427. return this._x;
  428. },
  429. set x ( value ) {
  430. this._x = value;
  431. this._updateEuler();
  432. },
  433. get y () {
  434. return this._y;
  435. },
  436. set y ( value ) {
  437. this._y = value;
  438. this._updateEuler();
  439. },
  440. get z () {
  441. return this._z;
  442. },
  443. set z ( value ) {
  444. this._z = value;
  445. this._updateEuler();
  446. },
  447. get w () {
  448. return this._w;
  449. },
  450. set w ( value ) {
  451. this._w = value;
  452. this._updateEuler();
  453. },
  454. set: function ( x, y, z, w ) {
  455. this._x = x;
  456. this._y = y;
  457. this._z = z;
  458. this._w = w;
  459. this._updateEuler();
  460. return this;
  461. },
  462. copy: function ( quaternion ) {
  463. this._x = quaternion._x;
  464. this._y = quaternion._y;
  465. this._z = quaternion._z;
  466. this._w = quaternion._w;
  467. this._updateEuler();
  468. return this;
  469. },
  470. setFromEuler: function ( euler, update ) {
  471. if ( euler instanceof THREE.Euler === false ) {
  472. throw new Error( 'ERROR: Quaternion\'s .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  473. }
  474. // http://www.mathworks.com/matlabcentral/fileexchange/
  475. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  476. // content/SpinCalc.m
  477. var c1 = Math.cos( euler._x / 2 );
  478. var c2 = Math.cos( euler._y / 2 );
  479. var c3 = Math.cos( euler._z / 2 );
  480. var s1 = Math.sin( euler._x / 2 );
  481. var s2 = Math.sin( euler._y / 2 );
  482. var s3 = Math.sin( euler._z / 2 );
  483. if ( euler.order === 'XYZ' ) {
  484. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  485. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  486. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  487. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  488. } else if ( euler.order === 'YXZ' ) {
  489. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  490. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  491. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  492. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  493. } else if ( euler.order === 'ZXY' ) {
  494. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  495. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  496. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  497. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  498. } else if ( euler.order === 'ZYX' ) {
  499. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  500. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  501. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  502. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  503. } else if ( euler.order === 'YZX' ) {
  504. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  505. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  506. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  507. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  508. } else if ( euler.order === 'XZY' ) {
  509. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  510. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  511. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  512. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  513. }
  514. if ( update !== false ) this._updateEuler();
  515. return this;
  516. },
  517. setFromAxisAngle: function ( axis, angle ) {
  518. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  519. // axis have to be normalized
  520. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  521. this._x = axis.x * s;
  522. this._y = axis.y * s;
  523. this._z = axis.z * s;
  524. this._w = Math.cos( halfAngle );
  525. this._updateEuler();
  526. return this;
  527. },
  528. setFromRotationMatrix: function ( m ) {
  529. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  530. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  531. var te = m.elements,
  532. m11 = te[0], m12 = te[4], m13 = te[8],
  533. m21 = te[1], m22 = te[5], m23 = te[9],
  534. m31 = te[2], m32 = te[6], m33 = te[10],
  535. trace = m11 + m22 + m33,
  536. s;
  537. if ( trace > 0 ) {
  538. s = 0.5 / Math.sqrt( trace + 1.0 );
  539. this._w = 0.25 / s;
  540. this._x = ( m32 - m23 ) * s;
  541. this._y = ( m13 - m31 ) * s;
  542. this._z = ( m21 - m12 ) * s;
  543. } else if ( m11 > m22 && m11 > m33 ) {
  544. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  545. this._w = (m32 - m23 ) / s;
  546. this._x = 0.25 * s;
  547. this._y = (m12 + m21 ) / s;
  548. this._z = (m13 + m31 ) / s;
  549. } else if ( m22 > m33 ) {
  550. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  551. this._w = (m13 - m31 ) / s;
  552. this._x = (m12 + m21 ) / s;
  553. this._y = 0.25 * s;
  554. this._z = (m23 + m32 ) / s;
  555. } else {
  556. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  557. this._w = ( m21 - m12 ) / s;
  558. this._x = ( m13 + m31 ) / s;
  559. this._y = ( m23 + m32 ) / s;
  560. this._z = 0.25 * s;
  561. }
  562. this._updateEuler();
  563. return this;
  564. },
  565. inverse: function () {
  566. this.conjugate().normalize();
  567. return this;
  568. },
  569. conjugate: function () {
  570. this._x *= -1;
  571. this._y *= -1;
  572. this._z *= -1;
  573. this._updateEuler();
  574. return this;
  575. },
  576. lengthSq: function () {
  577. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  578. },
  579. length: function () {
  580. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  581. },
  582. normalize: function () {
  583. var l = this.length();
  584. if ( l === 0 ) {
  585. this._x = 0;
  586. this._y = 0;
  587. this._z = 0;
  588. this._w = 1;
  589. } else {
  590. l = 1 / l;
  591. this._x = this._x * l;
  592. this._y = this._y * l;
  593. this._z = this._z * l;
  594. this._w = this._w * l;
  595. }
  596. return this;
  597. },
  598. multiply: function ( q, p ) {
  599. if ( p !== undefined ) {
  600. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  601. return this.multiplyQuaternions( q, p );
  602. }
  603. return this.multiplyQuaternions( this, q );
  604. },
  605. multiplyQuaternions: function ( a, b ) {
  606. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  607. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  608. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  609. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  610. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  611. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  612. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  613. this._updateEuler();
  614. return this;
  615. },
  616. multiplyVector3: function ( vector ) {
  617. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  618. return vector.applyQuaternion( this );
  619. },
  620. slerp: function ( qb, t ) {
  621. var x = this._x, y = this._y, z = this._z, w = this._w;
  622. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  623. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  624. if ( cosHalfTheta < 0 ) {
  625. this._w = -qb._w;
  626. this._x = -qb._x;
  627. this._y = -qb._y;
  628. this._z = -qb._z;
  629. cosHalfTheta = -cosHalfTheta;
  630. } else {
  631. this.copy( qb );
  632. }
  633. if ( cosHalfTheta >= 1.0 ) {
  634. this._w = w;
  635. this._x = x;
  636. this._y = y;
  637. this._z = z;
  638. return this;
  639. }
  640. var halfTheta = Math.acos( cosHalfTheta );
  641. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  642. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  643. this._w = 0.5 * ( w + this._w );
  644. this._x = 0.5 * ( x + this._x );
  645. this._y = 0.5 * ( y + this._y );
  646. this._z = 0.5 * ( z + this._z );
  647. return this;
  648. }
  649. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  650. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  651. this._w = ( w * ratioA + this._w * ratioB );
  652. this._x = ( x * ratioA + this._x * ratioB );
  653. this._y = ( y * ratioA + this._y * ratioB );
  654. this._z = ( z * ratioA + this._z * ratioB );
  655. this._updateEuler();
  656. return this;
  657. },
  658. equals: function ( quaternion ) {
  659. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  660. },
  661. fromArray: function ( array ) {
  662. this._x = array[ 0 ];
  663. this._y = array[ 1 ];
  664. this._z = array[ 2 ];
  665. this._w = array[ 3 ];
  666. this._updateEuler();
  667. return this;
  668. },
  669. toArray: function () {
  670. return [ this._x, this._y, this._z, this._w ];
  671. },
  672. clone: function () {
  673. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  674. }
  675. };
  676. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  677. return qm.copy( qa ).slerp( qb, t );
  678. }
  679. /**
  680. * @author mrdoob / http://mrdoob.com/
  681. * @author philogb / http://blog.thejit.org/
  682. * @author egraether / http://egraether.com/
  683. * @author zz85 / http://www.lab4games.net/zz85/blog
  684. */
  685. THREE.Vector2 = function ( x, y ) {
  686. this.x = x || 0;
  687. this.y = y || 0;
  688. };
  689. THREE.Vector2.prototype = {
  690. constructor: THREE.Vector2,
  691. set: function ( x, y ) {
  692. this.x = x;
  693. this.y = y;
  694. return this;
  695. },
  696. setX: function ( x ) {
  697. this.x = x;
  698. return this;
  699. },
  700. setY: function ( y ) {
  701. this.y = y;
  702. return this;
  703. },
  704. setComponent: function ( index, value ) {
  705. switch ( index ) {
  706. case 0: this.x = value; break;
  707. case 1: this.y = value; break;
  708. default: throw new Error( "index is out of range: " + index );
  709. }
  710. },
  711. getComponent: function ( index ) {
  712. switch ( index ) {
  713. case 0: return this.x;
  714. case 1: return this.y;
  715. default: throw new Error( "index is out of range: " + index );
  716. }
  717. },
  718. copy: function ( v ) {
  719. this.x = v.x;
  720. this.y = v.y;
  721. return this;
  722. },
  723. add: function ( v, w ) {
  724. if ( w !== undefined ) {
  725. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  726. return this.addVectors( v, w );
  727. }
  728. this.x += v.x;
  729. this.y += v.y;
  730. return this;
  731. },
  732. addVectors: function ( a, b ) {
  733. this.x = a.x + b.x;
  734. this.y = a.y + b.y;
  735. return this;
  736. },
  737. addScalar: function ( s ) {
  738. this.x += s;
  739. this.y += s;
  740. return this;
  741. },
  742. sub: function ( v, w ) {
  743. if ( w !== undefined ) {
  744. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  745. return this.subVectors( v, w );
  746. }
  747. this.x -= v.x;
  748. this.y -= v.y;
  749. return this;
  750. },
  751. subVectors: function ( a, b ) {
  752. this.x = a.x - b.x;
  753. this.y = a.y - b.y;
  754. return this;
  755. },
  756. multiplyScalar: function ( s ) {
  757. this.x *= s;
  758. this.y *= s;
  759. return this;
  760. },
  761. divideScalar: function ( scalar ) {
  762. if ( scalar !== 0 ) {
  763. var invScalar = 1 / scalar;
  764. this.x *= invScalar;
  765. this.y *= invScalar;
  766. } else {
  767. this.x = 0;
  768. this.y = 0;
  769. }
  770. return this;
  771. },
  772. min: function ( v ) {
  773. if ( this.x > v.x ) {
  774. this.x = v.x;
  775. }
  776. if ( this.y > v.y ) {
  777. this.y = v.y;
  778. }
  779. return this;
  780. },
  781. max: function ( v ) {
  782. if ( this.x < v.x ) {
  783. this.x = v.x;
  784. }
  785. if ( this.y < v.y ) {
  786. this.y = v.y;
  787. }
  788. return this;
  789. },
  790. clamp: function ( min, max ) {
  791. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  792. if ( this.x < min.x ) {
  793. this.x = min.x;
  794. } else if ( this.x > max.x ) {
  795. this.x = max.x;
  796. }
  797. if ( this.y < min.y ) {
  798. this.y = min.y;
  799. } else if ( this.y > max.y ) {
  800. this.y = max.y;
  801. }
  802. return this;
  803. },
  804. negate: function() {
  805. return this.multiplyScalar( - 1 );
  806. },
  807. dot: function ( v ) {
  808. return this.x * v.x + this.y * v.y;
  809. },
  810. lengthSq: function () {
  811. return this.x * this.x + this.y * this.y;
  812. },
  813. length: function () {
  814. return Math.sqrt( this.x * this.x + this.y * this.y );
  815. },
  816. normalize: function () {
  817. return this.divideScalar( this.length() );
  818. },
  819. distanceTo: function ( v ) {
  820. return Math.sqrt( this.distanceToSquared( v ) );
  821. },
  822. distanceToSquared: function ( v ) {
  823. var dx = this.x - v.x, dy = this.y - v.y;
  824. return dx * dx + dy * dy;
  825. },
  826. setLength: function ( l ) {
  827. var oldLength = this.length();
  828. if ( oldLength !== 0 && l !== oldLength ) {
  829. this.multiplyScalar( l / oldLength );
  830. }
  831. return this;
  832. },
  833. lerp: function ( v, alpha ) {
  834. this.x += ( v.x - this.x ) * alpha;
  835. this.y += ( v.y - this.y ) * alpha;
  836. return this;
  837. },
  838. equals: function( v ) {
  839. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  840. },
  841. fromArray: function ( array ) {
  842. this.x = array[ 0 ];
  843. this.y = array[ 1 ];
  844. return this;
  845. },
  846. toArray: function () {
  847. return [ this.x, this.y ];
  848. },
  849. clone: function () {
  850. return new THREE.Vector2( this.x, this.y );
  851. }
  852. };
  853. /**
  854. * @author mrdoob / http://mrdoob.com/
  855. * @author *kile / http://kile.stravaganza.org/
  856. * @author philogb / http://blog.thejit.org/
  857. * @author mikael emtinger / http://gomo.se/
  858. * @author egraether / http://egraether.com/
  859. * @author WestLangley / http://github.com/WestLangley
  860. */
  861. THREE.Vector3 = function ( x, y, z ) {
  862. this.x = x || 0;
  863. this.y = y || 0;
  864. this.z = z || 0;
  865. };
  866. THREE.Vector3.prototype = {
  867. constructor: THREE.Vector3,
  868. set: function ( x, y, z ) {
  869. this.x = x;
  870. this.y = y;
  871. this.z = z;
  872. return this;
  873. },
  874. setX: function ( x ) {
  875. this.x = x;
  876. return this;
  877. },
  878. setY: function ( y ) {
  879. this.y = y;
  880. return this;
  881. },
  882. setZ: function ( z ) {
  883. this.z = z;
  884. return this;
  885. },
  886. setComponent: function ( index, value ) {
  887. switch ( index ) {
  888. case 0: this.x = value; break;
  889. case 1: this.y = value; break;
  890. case 2: this.z = value; break;
  891. default: throw new Error( "index is out of range: " + index );
  892. }
  893. },
  894. getComponent: function ( index ) {
  895. switch ( index ) {
  896. case 0: return this.x;
  897. case 1: return this.y;
  898. case 2: return this.z;
  899. default: throw new Error( "index is out of range: " + index );
  900. }
  901. },
  902. copy: function ( v ) {
  903. this.x = v.x;
  904. this.y = v.y;
  905. this.z = v.z;
  906. return this;
  907. },
  908. add: function ( v, w ) {
  909. if ( w !== undefined ) {
  910. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  911. return this.addVectors( v, w );
  912. }
  913. this.x += v.x;
  914. this.y += v.y;
  915. this.z += v.z;
  916. return this;
  917. },
  918. addScalar: function ( s ) {
  919. this.x += s;
  920. this.y += s;
  921. this.z += s;
  922. return this;
  923. },
  924. addVectors: function ( a, b ) {
  925. this.x = a.x + b.x;
  926. this.y = a.y + b.y;
  927. this.z = a.z + b.z;
  928. return this;
  929. },
  930. sub: function ( v, w ) {
  931. if ( w !== undefined ) {
  932. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  933. return this.subVectors( v, w );
  934. }
  935. this.x -= v.x;
  936. this.y -= v.y;
  937. this.z -= v.z;
  938. return this;
  939. },
  940. subVectors: function ( a, b ) {
  941. this.x = a.x - b.x;
  942. this.y = a.y - b.y;
  943. this.z = a.z - b.z;
  944. return this;
  945. },
  946. multiply: function ( v, w ) {
  947. if ( w !== undefined ) {
  948. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  949. return this.multiplyVectors( v, w );
  950. }
  951. this.x *= v.x;
  952. this.y *= v.y;
  953. this.z *= v.z;
  954. return this;
  955. },
  956. multiplyScalar: function ( scalar ) {
  957. this.x *= scalar;
  958. this.y *= scalar;
  959. this.z *= scalar;
  960. return this;
  961. },
  962. multiplyVectors: function ( a, b ) {
  963. this.x = a.x * b.x;
  964. this.y = a.y * b.y;
  965. this.z = a.z * b.z;
  966. return this;
  967. },
  968. applyMatrix3: function ( m ) {
  969. var x = this.x;
  970. var y = this.y;
  971. var z = this.z;
  972. var e = m.elements;
  973. this.x = e[0] * x + e[3] * y + e[6] * z;
  974. this.y = e[1] * x + e[4] * y + e[7] * z;
  975. this.z = e[2] * x + e[5] * y + e[8] * z;
  976. return this;
  977. },
  978. applyMatrix4: function ( m ) {
  979. // input: THREE.Matrix4 affine matrix
  980. var x = this.x, y = this.y, z = this.z;
  981. var e = m.elements;
  982. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  983. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  984. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  985. return this;
  986. },
  987. applyProjection: function ( m ) {
  988. // input: THREE.Matrix4 projection matrix
  989. var x = this.x, y = this.y, z = this.z;
  990. var e = m.elements;
  991. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  992. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  993. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  994. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  995. return this;
  996. },
  997. applyQuaternion: function ( q ) {
  998. var x = this.x;
  999. var y = this.y;
  1000. var z = this.z;
  1001. var qx = q.x;
  1002. var qy = q.y;
  1003. var qz = q.z;
  1004. var qw = q.w;
  1005. // calculate quat * vector
  1006. var ix = qw * x + qy * z - qz * y;
  1007. var iy = qw * y + qz * x - qx * z;
  1008. var iz = qw * z + qx * y - qy * x;
  1009. var iw = -qx * x - qy * y - qz * z;
  1010. // calculate result * inverse quat
  1011. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1012. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1013. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1014. return this;
  1015. },
  1016. transformDirection: function ( m ) {
  1017. // input: THREE.Matrix4 affine matrix
  1018. // vector interpreted as a direction
  1019. var x = this.x, y = this.y, z = this.z;
  1020. var e = m.elements;
  1021. this.x = e[0] * x + e[4] * y + e[8] * z;
  1022. this.y = e[1] * x + e[5] * y + e[9] * z;
  1023. this.z = e[2] * x + e[6] * y + e[10] * z;
  1024. this.normalize();
  1025. return this;
  1026. },
  1027. divide: function ( v ) {
  1028. this.x /= v.x;
  1029. this.y /= v.y;
  1030. this.z /= v.z;
  1031. return this;
  1032. },
  1033. divideScalar: function ( scalar ) {
  1034. if ( scalar !== 0 ) {
  1035. var invScalar = 1 / scalar;
  1036. this.x *= invScalar;
  1037. this.y *= invScalar;
  1038. this.z *= invScalar;
  1039. } else {
  1040. this.x = 0;
  1041. this.y = 0;
  1042. this.z = 0;
  1043. }
  1044. return this;
  1045. },
  1046. min: function ( v ) {
  1047. if ( this.x > v.x ) {
  1048. this.x = v.x;
  1049. }
  1050. if ( this.y > v.y ) {
  1051. this.y = v.y;
  1052. }
  1053. if ( this.z > v.z ) {
  1054. this.z = v.z;
  1055. }
  1056. return this;
  1057. },
  1058. max: function ( v ) {
  1059. if ( this.x < v.x ) {
  1060. this.x = v.x;
  1061. }
  1062. if ( this.y < v.y ) {
  1063. this.y = v.y;
  1064. }
  1065. if ( this.z < v.z ) {
  1066. this.z = v.z;
  1067. }
  1068. return this;
  1069. },
  1070. clamp: function ( min, max ) {
  1071. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1072. if ( this.x < min.x ) {
  1073. this.x = min.x;
  1074. } else if ( this.x > max.x ) {
  1075. this.x = max.x;
  1076. }
  1077. if ( this.y < min.y ) {
  1078. this.y = min.y;
  1079. } else if ( this.y > max.y ) {
  1080. this.y = max.y;
  1081. }
  1082. if ( this.z < min.z ) {
  1083. this.z = min.z;
  1084. } else if ( this.z > max.z ) {
  1085. this.z = max.z;
  1086. }
  1087. return this;
  1088. },
  1089. negate: function () {
  1090. return this.multiplyScalar( - 1 );
  1091. },
  1092. dot: function ( v ) {
  1093. return this.x * v.x + this.y * v.y + this.z * v.z;
  1094. },
  1095. lengthSq: function () {
  1096. return this.x * this.x + this.y * this.y + this.z * this.z;
  1097. },
  1098. length: function () {
  1099. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1100. },
  1101. lengthManhattan: function () {
  1102. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1103. },
  1104. normalize: function () {
  1105. return this.divideScalar( this.length() );
  1106. },
  1107. setLength: function ( l ) {
  1108. var oldLength = this.length();
  1109. if ( oldLength !== 0 && l !== oldLength ) {
  1110. this.multiplyScalar( l / oldLength );
  1111. }
  1112. return this;
  1113. },
  1114. lerp: function ( v, alpha ) {
  1115. this.x += ( v.x - this.x ) * alpha;
  1116. this.y += ( v.y - this.y ) * alpha;
  1117. this.z += ( v.z - this.z ) * alpha;
  1118. return this;
  1119. },
  1120. cross: function ( v, w ) {
  1121. if ( w !== undefined ) {
  1122. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1123. return this.crossVectors( v, w );
  1124. }
  1125. var x = this.x, y = this.y, z = this.z;
  1126. this.x = y * v.z - z * v.y;
  1127. this.y = z * v.x - x * v.z;
  1128. this.z = x * v.y - y * v.x;
  1129. return this;
  1130. },
  1131. crossVectors: function ( a, b ) {
  1132. var ax = a.x, ay = a.y, az = a.z;
  1133. var bx = b.x, by = b.y, bz = b.z;
  1134. this.x = ay * bz - az * by;
  1135. this.y = az * bx - ax * bz;
  1136. this.z = ax * by - ay * bx;
  1137. return this;
  1138. },
  1139. angleTo: function ( v ) {
  1140. var theta = this.dot( v ) / ( this.length() * v.length() );
  1141. // clamp, to handle numerical problems
  1142. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1143. },
  1144. distanceTo: function ( v ) {
  1145. return Math.sqrt( this.distanceToSquared( v ) );
  1146. },
  1147. distanceToSquared: function ( v ) {
  1148. var dx = this.x - v.x;
  1149. var dy = this.y - v.y;
  1150. var dz = this.z - v.z;
  1151. return dx * dx + dy * dy + dz * dz;
  1152. },
  1153. setEulerFromRotationMatrix: function ( m, order ) {
  1154. console.error( "REMOVED: Vector3\'s setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code.");
  1155. },
  1156. setEulerFromQuaternion: function ( q, order ) {
  1157. console.error( "REMOVED: Vector3\'s setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code.");
  1158. },
  1159. getPositionFromMatrix: function ( m ) {
  1160. console.warn( "DEPRECATED: Vector3\'s .getPositionFromMatrix() has been renamed to .setFromMatrixPosition(). Please update your code." );
  1161. return this.setFromMatrixPosition( m );
  1162. },
  1163. getScaleFromMatrix: function ( m ) {
  1164. console.warn( "DEPRECATED: Vector3\'s .getScaleFromMatrix() has been renamed to .setFromMatrixScale(). Please update your code." );
  1165. return this.setFromMatrixScale( m );
  1166. },
  1167. getColumnFromMatrix: function ( index, matrix ) {
  1168. console.warn( "DEPRECATED: Vector3\'s .getColumnFromMatrix() has been renamed to .setFromMatrixColumn(). Please update your code." );
  1169. return this.setFromMatrixColumn( index, matrix );
  1170. },
  1171. setFromMatrixPosition: function ( m ) {
  1172. this.x = m.elements[ 12 ];
  1173. this.y = m.elements[ 13 ];
  1174. this.z = m.elements[ 14 ];
  1175. return this;
  1176. },
  1177. setFromMatrixScale: function ( m ) {
  1178. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1179. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1180. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1181. this.x = sx;
  1182. this.y = sy;
  1183. this.z = sz;
  1184. return this;
  1185. },
  1186. setFromMatrixColumn: function ( index, matrix ) {
  1187. var offset = index * 4;
  1188. var me = matrix.elements;
  1189. this.x = me[ offset ];
  1190. this.y = me[ offset + 1 ];
  1191. this.z = me[ offset + 2 ];
  1192. return this;
  1193. },
  1194. equals: function ( v ) {
  1195. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1196. },
  1197. fromArray: function ( array ) {
  1198. this.x = array[ 0 ];
  1199. this.y = array[ 1 ];
  1200. this.z = array[ 2 ];
  1201. return this;
  1202. },
  1203. toArray: function () {
  1204. return [ this.x, this.y, this.z ];
  1205. },
  1206. clone: function () {
  1207. return new THREE.Vector3( this.x, this.y, this.z );
  1208. }
  1209. };
  1210. THREE.extend( THREE.Vector3.prototype, {
  1211. applyEuler: function () {
  1212. var quaternion = new THREE.Quaternion();
  1213. return function ( euler ) {
  1214. if ( euler instanceof THREE.Euler === false ) {
  1215. console.error( 'ERROR: Vector3\'s .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  1216. }
  1217. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1218. return this;
  1219. };
  1220. }(),
  1221. applyAxisAngle: function () {
  1222. var quaternion = new THREE.Quaternion();
  1223. return function ( axis, angle ) {
  1224. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1225. return this;
  1226. };
  1227. }(),
  1228. projectOnVector: function () {
  1229. var v1 = new THREE.Vector3();
  1230. return function ( vector ) {
  1231. v1.copy( vector ).normalize();
  1232. var d = this.dot( v1 );
  1233. return this.copy( v1 ).multiplyScalar( d );
  1234. };
  1235. }(),
  1236. projectOnPlane: function () {
  1237. var v1 = new THREE.Vector3();
  1238. return function ( planeNormal ) {
  1239. v1.copy( this ).projectOnVector( planeNormal );
  1240. return this.sub( v1 );
  1241. }
  1242. }(),
  1243. reflect: function () {
  1244. var v1 = new THREE.Vector3();
  1245. return function ( vector ) {
  1246. v1.copy( this ).projectOnVector( vector ).multiplyScalar( 2 );
  1247. return this.subVectors( v1, this );
  1248. }
  1249. }()
  1250. } );
  1251. /**
  1252. * @author supereggbert / http://www.paulbrunt.co.uk/
  1253. * @author philogb / http://blog.thejit.org/
  1254. * @author mikael emtinger / http://gomo.se/
  1255. * @author egraether / http://egraether.com/
  1256. * @author WestLangley / http://github.com/WestLangley
  1257. */
  1258. THREE.Vector4 = function ( x, y, z, w ) {
  1259. this.x = x || 0;
  1260. this.y = y || 0;
  1261. this.z = z || 0;
  1262. this.w = ( w !== undefined ) ? w : 1;
  1263. };
  1264. THREE.Vector4.prototype = {
  1265. constructor: THREE.Vector4,
  1266. set: function ( x, y, z, w ) {
  1267. this.x = x;
  1268. this.y = y;
  1269. this.z = z;
  1270. this.w = w;
  1271. return this;
  1272. },
  1273. setX: function ( x ) {
  1274. this.x = x;
  1275. return this;
  1276. },
  1277. setY: function ( y ) {
  1278. this.y = y;
  1279. return this;
  1280. },
  1281. setZ: function ( z ) {
  1282. this.z = z;
  1283. return this;
  1284. },
  1285. setW: function ( w ) {
  1286. this.w = w;
  1287. return this;
  1288. },
  1289. setComponent: function ( index, value ) {
  1290. switch ( index ) {
  1291. case 0: this.x = value; break;
  1292. case 1: this.y = value; break;
  1293. case 2: this.z = value; break;
  1294. case 3: this.w = value; break;
  1295. default: throw new Error( "index is out of range: " + index );
  1296. }
  1297. },
  1298. getComponent: function ( index ) {
  1299. switch ( index ) {
  1300. case 0: return this.x;
  1301. case 1: return this.y;
  1302. case 2: return this.z;
  1303. case 3: return this.w;
  1304. default: throw new Error( "index is out of range: " + index );
  1305. }
  1306. },
  1307. copy: function ( v ) {
  1308. this.x = v.x;
  1309. this.y = v.y;
  1310. this.z = v.z;
  1311. this.w = ( v.w !== undefined ) ? v.w : 1;
  1312. return this;
  1313. },
  1314. add: function ( v, w ) {
  1315. if ( w !== undefined ) {
  1316. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1317. return this.addVectors( v, w );
  1318. }
  1319. this.x += v.x;
  1320. this.y += v.y;
  1321. this.z += v.z;
  1322. this.w += v.w;
  1323. return this;
  1324. },
  1325. addScalar: function ( s ) {
  1326. this.x += s;
  1327. this.y += s;
  1328. this.z += s;
  1329. this.w += s;
  1330. return this;
  1331. },
  1332. addVectors: function ( a, b ) {
  1333. this.x = a.x + b.x;
  1334. this.y = a.y + b.y;
  1335. this.z = a.z + b.z;
  1336. this.w = a.w + b.w;
  1337. return this;
  1338. },
  1339. sub: function ( v, w ) {
  1340. if ( w !== undefined ) {
  1341. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1342. return this.subVectors( v, w );
  1343. }
  1344. this.x -= v.x;
  1345. this.y -= v.y;
  1346. this.z -= v.z;
  1347. this.w -= v.w;
  1348. return this;
  1349. },
  1350. subVectors: function ( a, b ) {
  1351. this.x = a.x - b.x;
  1352. this.y = a.y - b.y;
  1353. this.z = a.z - b.z;
  1354. this.w = a.w - b.w;
  1355. return this;
  1356. },
  1357. multiplyScalar: function ( scalar ) {
  1358. this.x *= scalar;
  1359. this.y *= scalar;
  1360. this.z *= scalar;
  1361. this.w *= scalar;
  1362. return this;
  1363. },
  1364. applyMatrix4: function ( m ) {
  1365. var x = this.x;
  1366. var y = this.y;
  1367. var z = this.z;
  1368. var w = this.w;
  1369. var e = m.elements;
  1370. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1371. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1372. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1373. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1374. return this;
  1375. },
  1376. divideScalar: function ( scalar ) {
  1377. if ( scalar !== 0 ) {
  1378. var invScalar = 1 / scalar;
  1379. this.x *= invScalar;
  1380. this.y *= invScalar;
  1381. this.z *= invScalar;
  1382. this.w *= invScalar;
  1383. } else {
  1384. this.x = 0;
  1385. this.y = 0;
  1386. this.z = 0;
  1387. this.w = 1;
  1388. }
  1389. return this;
  1390. },
  1391. setAxisAngleFromQuaternion: function ( q ) {
  1392. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1393. // q is assumed to be normalized
  1394. this.w = 2 * Math.acos( q.w );
  1395. var s = Math.sqrt( 1 - q.w * q.w );
  1396. if ( s < 0.0001 ) {
  1397. this.x = 1;
  1398. this.y = 0;
  1399. this.z = 0;
  1400. } else {
  1401. this.x = q.x / s;
  1402. this.y = q.y / s;
  1403. this.z = q.z / s;
  1404. }
  1405. return this;
  1406. },
  1407. setAxisAngleFromRotationMatrix: function ( m ) {
  1408. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1409. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1410. var angle, x, y, z, // variables for result
  1411. epsilon = 0.01, // margin to allow for rounding errors
  1412. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1413. te = m.elements,
  1414. m11 = te[0], m12 = te[4], m13 = te[8],
  1415. m21 = te[1], m22 = te[5], m23 = te[9],
  1416. m31 = te[2], m32 = te[6], m33 = te[10];
  1417. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1418. && ( Math.abs( m13 - m31 ) < epsilon )
  1419. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1420. // singularity found
  1421. // first check for identity matrix which must have +1 for all terms
  1422. // in leading diagonal and zero in other terms
  1423. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1424. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1425. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1426. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1427. // this singularity is identity matrix so angle = 0
  1428. this.set( 1, 0, 0, 0 );
  1429. return this; // zero angle, arbitrary axis
  1430. }
  1431. // otherwise this singularity is angle = 180
  1432. angle = Math.PI;
  1433. var xx = ( m11 + 1 ) / 2;
  1434. var yy = ( m22 + 1 ) / 2;
  1435. var zz = ( m33 + 1 ) / 2;
  1436. var xy = ( m12 + m21 ) / 4;
  1437. var xz = ( m13 + m31 ) / 4;
  1438. var yz = ( m23 + m32 ) / 4;
  1439. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1440. if ( xx < epsilon ) {
  1441. x = 0;
  1442. y = 0.707106781;
  1443. z = 0.707106781;
  1444. } else {
  1445. x = Math.sqrt( xx );
  1446. y = xy / x;
  1447. z = xz / x;
  1448. }
  1449. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1450. if ( yy < epsilon ) {
  1451. x = 0.707106781;
  1452. y = 0;
  1453. z = 0.707106781;
  1454. } else {
  1455. y = Math.sqrt( yy );
  1456. x = xy / y;
  1457. z = yz / y;
  1458. }
  1459. } else { // m33 is the largest diagonal term so base result on this
  1460. if ( zz < epsilon ) {
  1461. x = 0.707106781;
  1462. y = 0.707106781;
  1463. z = 0;
  1464. } else {
  1465. z = Math.sqrt( zz );
  1466. x = xz / z;
  1467. y = yz / z;
  1468. }
  1469. }
  1470. this.set( x, y, z, angle );
  1471. return this; // return 180 deg rotation
  1472. }
  1473. // as we have reached here there are no singularities so we can handle normally
  1474. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1475. + ( m13 - m31 ) * ( m13 - m31 )
  1476. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1477. if ( Math.abs( s ) < 0.001 ) s = 1;
  1478. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1479. // caught by singularity test above, but I've left it in just in case
  1480. this.x = ( m32 - m23 ) / s;
  1481. this.y = ( m13 - m31 ) / s;
  1482. this.z = ( m21 - m12 ) / s;
  1483. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1484. return this;
  1485. },
  1486. min: function ( v ) {
  1487. if ( this.x > v.x ) {
  1488. this.x = v.x;
  1489. }
  1490. if ( this.y > v.y ) {
  1491. this.y = v.y;
  1492. }
  1493. if ( this.z > v.z ) {
  1494. this.z = v.z;
  1495. }
  1496. if ( this.w > v.w ) {
  1497. this.w = v.w;
  1498. }
  1499. return this;
  1500. },
  1501. max: function ( v ) {
  1502. if ( this.x < v.x ) {
  1503. this.x = v.x;
  1504. }
  1505. if ( this.y < v.y ) {
  1506. this.y = v.y;
  1507. }
  1508. if ( this.z < v.z ) {
  1509. this.z = v.z;
  1510. }
  1511. if ( this.w < v.w ) {
  1512. this.w = v.w;
  1513. }
  1514. return this;
  1515. },
  1516. clamp: function ( min, max ) {
  1517. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1518. if ( this.x < min.x ) {
  1519. this.x = min.x;
  1520. } else if ( this.x > max.x ) {
  1521. this.x = max.x;
  1522. }
  1523. if ( this.y < min.y ) {
  1524. this.y = min.y;
  1525. } else if ( this.y > max.y ) {
  1526. this.y = max.y;
  1527. }
  1528. if ( this.z < min.z ) {
  1529. this.z = min.z;
  1530. } else if ( this.z > max.z ) {
  1531. this.z = max.z;
  1532. }
  1533. if ( this.w < min.w ) {
  1534. this.w = min.w;
  1535. } else if ( this.w > max.w ) {
  1536. this.w = max.w;
  1537. }
  1538. return this;
  1539. },
  1540. negate: function() {
  1541. return this.multiplyScalar( -1 );
  1542. },
  1543. dot: function ( v ) {
  1544. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1545. },
  1546. lengthSq: function () {
  1547. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1548. },
  1549. length: function () {
  1550. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1551. },
  1552. lengthManhattan: function () {
  1553. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1554. },
  1555. normalize: function () {
  1556. return this.divideScalar( this.length() );
  1557. },
  1558. setLength: function ( l ) {
  1559. var oldLength = this.length();
  1560. if ( oldLength !== 0 && l !== oldLength ) {
  1561. this.multiplyScalar( l / oldLength );
  1562. }
  1563. return this;
  1564. },
  1565. lerp: function ( v, alpha ) {
  1566. this.x += ( v.x - this.x ) * alpha;
  1567. this.y += ( v.y - this.y ) * alpha;
  1568. this.z += ( v.z - this.z ) * alpha;
  1569. this.w += ( v.w - this.w ) * alpha;
  1570. return this;
  1571. },
  1572. equals: function ( v ) {
  1573. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1574. },
  1575. fromArray: function ( array ) {
  1576. this.x = array[ 0 ];
  1577. this.y = array[ 1 ];
  1578. this.z = array[ 2 ];
  1579. this.w = array[ 3 ];
  1580. return this;
  1581. },
  1582. toArray: function () {
  1583. return [ this.x, this.y, this.z, this.w ];
  1584. },
  1585. clone: function () {
  1586. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1587. }
  1588. };
  1589. /**
  1590. * @author mrdoob / http://mrdoob.com/
  1591. * @author WestLangley / http://github.com/WestLangley
  1592. * @author bhouston / http://exocortex.com
  1593. */
  1594. THREE.Euler = function ( x, y, z, order ) {
  1595. this._x = x || 0;
  1596. this._y = y || 0;
  1597. this._z = z || 0;
  1598. this._order = order || THREE.Euler.DefaultOrder;
  1599. };
  1600. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1601. THREE.Euler.DefaultOrder = 'XYZ';
  1602. THREE.Euler.prototype = {
  1603. constructor: THREE.Euler,
  1604. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1605. _quaternion: undefined,
  1606. _updateQuaternion: function () {
  1607. if ( this._quaternion !== undefined ) {
  1608. this._quaternion.setFromEuler( this, false );
  1609. }
  1610. },
  1611. get x () {
  1612. return this._x;
  1613. },
  1614. set x ( value ) {
  1615. this._x = value;
  1616. this._updateQuaternion();
  1617. },
  1618. get y () {
  1619. return this._y;
  1620. },
  1621. set y ( value ) {
  1622. this._y = value;
  1623. this._updateQuaternion();
  1624. },
  1625. get z () {
  1626. return this._z;
  1627. },
  1628. set z ( value ) {
  1629. this._z = value;
  1630. this._updateQuaternion();
  1631. },
  1632. get order () {
  1633. return this._order;
  1634. },
  1635. set order ( value ) {
  1636. this._order = value;
  1637. this._updateQuaternion();
  1638. },
  1639. set: function ( x, y, z, order ) {
  1640. this._x = x;
  1641. this._y = y;
  1642. this._z = z;
  1643. this._order = order || this._order;
  1644. this._updateQuaternion();
  1645. return this;
  1646. },
  1647. copy: function ( euler ) {
  1648. this._x = euler._x;
  1649. this._y = euler._y;
  1650. this._z = euler._z;
  1651. this._order = euler._order;
  1652. this._updateQuaternion();
  1653. return this;
  1654. },
  1655. setFromRotationMatrix: function ( m, order ) {
  1656. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1657. // clamp, to handle numerical problems
  1658. function clamp( x ) {
  1659. return Math.min( Math.max( x, -1 ), 1 );
  1660. }
  1661. var te = m.elements;
  1662. var m11 = te[0], m12 = te[4], m13 = te[8];
  1663. var m21 = te[1], m22 = te[5], m23 = te[9];
  1664. var m31 = te[2], m32 = te[6], m33 = te[10];
  1665. order = order || this._order;
  1666. if ( order === 'XYZ' ) {
  1667. this._y = Math.asin( clamp( m13 ) );
  1668. if ( Math.abs( m13 ) < 0.99999 ) {
  1669. this._x = Math.atan2( - m23, m33 );
  1670. this._z = Math.atan2( - m12, m11 );
  1671. } else {
  1672. this._x = Math.atan2( m32, m22 );
  1673. this._z = 0;
  1674. }
  1675. } else if ( order === 'YXZ' ) {
  1676. this._x = Math.asin( - clamp( m23 ) );
  1677. if ( Math.abs( m23 ) < 0.99999 ) {
  1678. this._y = Math.atan2( m13, m33 );
  1679. this._z = Math.atan2( m21, m22 );
  1680. } else {
  1681. this._y = Math.atan2( - m31, m11 );
  1682. this._z = 0;
  1683. }
  1684. } else if ( order === 'ZXY' ) {
  1685. this._x = Math.asin( clamp( m32 ) );
  1686. if ( Math.abs( m32 ) < 0.99999 ) {
  1687. this._y = Math.atan2( - m31, m33 );
  1688. this._z = Math.atan2( - m12, m22 );
  1689. } else {
  1690. this._y = 0;
  1691. this._z = Math.atan2( m21, m11 );
  1692. }
  1693. } else if ( order === 'ZYX' ) {
  1694. this._y = Math.asin( - clamp( m31 ) );
  1695. if ( Math.abs( m31 ) < 0.99999 ) {
  1696. this._x = Math.atan2( m32, m33 );
  1697. this._z = Math.atan2( m21, m11 );
  1698. } else {
  1699. this._x = 0;
  1700. this._z = Math.atan2( - m12, m22 );
  1701. }
  1702. } else if ( order === 'YZX' ) {
  1703. this._z = Math.asin( clamp( m21 ) );
  1704. if ( Math.abs( m21 ) < 0.99999 ) {
  1705. this._x = Math.atan2( - m23, m22 );
  1706. this._y = Math.atan2( - m31, m11 );
  1707. } else {
  1708. this._x = 0;
  1709. this._y = Math.atan2( m13, m33 );
  1710. }
  1711. } else if ( order === 'XZY' ) {
  1712. this._z = Math.asin( - clamp( m12 ) );
  1713. if ( Math.abs( m12 ) < 0.99999 ) {
  1714. this._x = Math.atan2( m32, m22 );
  1715. this._y = Math.atan2( m13, m11 );
  1716. } else {
  1717. this._x = Math.atan2( - m23, m33 );
  1718. this._y = 0;
  1719. }
  1720. } else {
  1721. console.warn( 'WARNING: Euler.setFromRotationMatrix() given unsupported order: ' + order )
  1722. }
  1723. this._order = order;
  1724. this._updateQuaternion();
  1725. return this;
  1726. },
  1727. setFromQuaternion: function ( q, order, update ) {
  1728. // q is assumed to be normalized
  1729. // clamp, to handle numerical problems
  1730. function clamp( x ) {
  1731. return Math.min( Math.max( x, -1 ), 1 );
  1732. }
  1733. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1734. var sqx = q.x * q.x;
  1735. var sqy = q.y * q.y;
  1736. var sqz = q.z * q.z;
  1737. var sqw = q.w * q.w;
  1738. order = order || this._order;
  1739. if ( order === 'XYZ' ) {
  1740. this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1741. this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1742. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1743. } else if ( order === 'YXZ' ) {
  1744. this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1745. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1746. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1747. } else if ( order === 'ZXY' ) {
  1748. this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1749. this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1750. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1751. } else if ( order === 'ZYX' ) {
  1752. this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1753. this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1754. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1755. } else if ( order === 'YZX' ) {
  1756. this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1757. this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1758. this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1759. } else if ( order === 'XZY' ) {
  1760. this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1761. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1762. this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1763. } else {
  1764. console.warn( 'WARNING: Euler.setFromQuaternion() given unsupported order: ' + order )
  1765. }
  1766. this._order = order;
  1767. if ( update !== false ) this._updateQuaternion();
  1768. return this;
  1769. },
  1770. reorder: function () {
  1771. // WARNING: this discards revolution information -bhouston
  1772. var q = new THREE.Quaternion();
  1773. return function ( newOrder ) {
  1774. q.setFromEuler( this );
  1775. this.setFromQuaternion( q, newOrder );
  1776. };
  1777. }(),
  1778. fromArray: function ( array ) {
  1779. this._x = array[ 0 ];
  1780. this._y = array[ 1 ];
  1781. this._z = array[ 2 ];
  1782. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1783. this._updateQuaternion();
  1784. return this;
  1785. },
  1786. toArray: function () {
  1787. return [ this._x, this._y, this._z, this._order ];
  1788. },
  1789. equals: function ( euler ) {
  1790. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1791. },
  1792. clone: function () {
  1793. return new THREE.Euler( this._x, this._y, this._z, this._order );
  1794. }
  1795. };
  1796. /**
  1797. * @author bhouston / http://exocortex.com
  1798. */
  1799. THREE.Line3 = function ( start, end ) {
  1800. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1801. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1802. };
  1803. THREE.Line3.prototype = {
  1804. constructor: THREE.Line3,
  1805. set: function ( start, end ) {
  1806. this.start.copy( start );
  1807. this.end.copy( end );
  1808. return this;
  1809. },
  1810. copy: function ( line ) {
  1811. this.start.copy( line.start );
  1812. this.end.copy( line.end );
  1813. return this;
  1814. },
  1815. center: function ( optionalTarget ) {
  1816. var result = optionalTarget || new THREE.Vector3();
  1817. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1818. },
  1819. delta: function ( optionalTarget ) {
  1820. var result = optionalTarget || new THREE.Vector3();
  1821. return result.subVectors( this.end, this.start );
  1822. },
  1823. distanceSq: function () {
  1824. return this.start.distanceToSquared( this.end );
  1825. },
  1826. distance: function () {
  1827. return this.start.distanceTo( this.end );
  1828. },
  1829. at: function ( t, optionalTarget ) {
  1830. var result = optionalTarget || new THREE.Vector3();
  1831. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1832. },
  1833. closestPointToPointParameter: function() {
  1834. var startP = new THREE.Vector3();
  1835. var startEnd = new THREE.Vector3();
  1836. return function ( point, clampToLine ) {
  1837. startP.subVectors( point, this.start );
  1838. startEnd.subVectors( this.end, this.start );
  1839. var startEnd2 = startEnd.dot( startEnd );
  1840. var startEnd_startP = startEnd.dot( startP );
  1841. var t = startEnd_startP / startEnd2;
  1842. if ( clampToLine ) {
  1843. t = THREE.Math.clamp( t, 0, 1 );
  1844. }
  1845. return t;
  1846. };
  1847. }(),
  1848. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1849. var t = this.closestPointToPointParameter( point, clampToLine );
  1850. var result = optionalTarget || new THREE.Vector3();
  1851. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1852. },
  1853. applyMatrix4: function ( matrix ) {
  1854. this.start.applyMatrix4( matrix );
  1855. this.end.applyMatrix4( matrix );
  1856. return this;
  1857. },
  1858. equals: function ( line ) {
  1859. return line.start.equals( this.start ) && line.end.equals( this.end );
  1860. },
  1861. clone: function () {
  1862. return new THREE.Line3().copy( this );
  1863. }
  1864. };
  1865. /**
  1866. * @author bhouston / http://exocortex.com
  1867. */
  1868. THREE.Box2 = function ( min, max ) {
  1869. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1870. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1871. };
  1872. THREE.Box2.prototype = {
  1873. constructor: THREE.Box2,
  1874. set: function ( min, max ) {
  1875. this.min.copy( min );
  1876. this.max.copy( max );
  1877. return this;
  1878. },
  1879. setFromPoints: function ( points ) {
  1880. if ( points.length > 0 ) {
  1881. var point = points[ 0 ];
  1882. this.min.copy( point );
  1883. this.max.copy( point );
  1884. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1885. point = points[ i ];
  1886. if ( point.x < this.min.x ) {
  1887. this.min.x = point.x;
  1888. } else if ( point.x > this.max.x ) {
  1889. this.max.x = point.x;
  1890. }
  1891. if ( point.y < this.min.y ) {
  1892. this.min.y = point.y;
  1893. } else if ( point.y > this.max.y ) {
  1894. this.max.y = point.y;
  1895. }
  1896. }
  1897. } else {
  1898. this.makeEmpty();
  1899. }
  1900. return this;
  1901. },
  1902. setFromCenterAndSize: function () {
  1903. var v1 = new THREE.Vector2();
  1904. return function ( center, size ) {
  1905. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1906. this.min.copy( center ).sub( halfSize );
  1907. this.max.copy( center ).add( halfSize );
  1908. return this;
  1909. };
  1910. }(),
  1911. copy: function ( box ) {
  1912. this.min.copy( box.min );
  1913. this.max.copy( box.max );
  1914. return this;
  1915. },
  1916. makeEmpty: function () {
  1917. this.min.x = this.min.y = Infinity;
  1918. this.max.x = this.max.y = -Infinity;
  1919. return this;
  1920. },
  1921. empty: function () {
  1922. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1923. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1924. },
  1925. center: function ( optionalTarget ) {
  1926. var result = optionalTarget || new THREE.Vector2();
  1927. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1928. },
  1929. size: function ( optionalTarget ) {
  1930. var result = optionalTarget || new THREE.Vector2();
  1931. return result.subVectors( this.max, this.min );
  1932. },
  1933. expandByPoint: function ( point ) {
  1934. this.min.min( point );
  1935. this.max.max( point );
  1936. return this;
  1937. },
  1938. expandByVector: function ( vector ) {
  1939. this.min.sub( vector );
  1940. this.max.add( vector );
  1941. return this;
  1942. },
  1943. expandByScalar: function ( scalar ) {
  1944. this.min.addScalar( -scalar );
  1945. this.max.addScalar( scalar );
  1946. return this;
  1947. },
  1948. containsPoint: function ( point ) {
  1949. if ( point.x < this.min.x || point.x > this.max.x ||
  1950. point.y < this.min.y || point.y > this.max.y ) {
  1951. return false;
  1952. }
  1953. return true;
  1954. },
  1955. containsBox: function ( box ) {
  1956. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1957. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1958. return true;
  1959. }
  1960. return false;
  1961. },
  1962. getParameter: function ( point, optionalTarget ) {
  1963. // This can potentially have a divide by zero if the box
  1964. // has a size dimension of 0.
  1965. var result = optionalTarget || new THREE.Vector2();
  1966. return result.set(
  1967. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1968. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1969. );
  1970. },
  1971. isIntersectionBox: function ( box ) {
  1972. // using 6 splitting planes to rule out intersections.
  1973. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1974. box.max.y < this.min.y || box.min.y > this.max.y ) {
  1975. return false;
  1976. }
  1977. return true;
  1978. },
  1979. clampPoint: function ( point, optionalTarget ) {
  1980. var result = optionalTarget || new THREE.Vector2();
  1981. return result.copy( point ).clamp( this.min, this.max );
  1982. },
  1983. distanceToPoint: function () {
  1984. var v1 = new THREE.Vector2();
  1985. return function ( point ) {
  1986. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1987. return clampedPoint.sub( point ).length();
  1988. };
  1989. }(),
  1990. intersect: function ( box ) {
  1991. this.min.max( box.min );
  1992. this.max.min( box.max );
  1993. return this;
  1994. },
  1995. union: function ( box ) {
  1996. this.min.min( box.min );
  1997. this.max.max( box.max );
  1998. return this;
  1999. },
  2000. translate: function ( offset ) {
  2001. this.min.add( offset );
  2002. this.max.add( offset );
  2003. return this;
  2004. },
  2005. equals: function ( box ) {
  2006. return box.min.equals( this.min ) && box.max.equals( this.max );
  2007. },
  2008. clone: function () {
  2009. return new THREE.Box2().copy( this );
  2010. }
  2011. };
  2012. /**
  2013. * @author bhouston / http://exocortex.com
  2014. * @author WestLangley / http://github.com/WestLangley
  2015. */
  2016. THREE.Box3 = function ( min, max ) {
  2017. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2018. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  2019. };
  2020. THREE.Box3.prototype = {
  2021. constructor: THREE.Box3,
  2022. set: function ( min, max ) {
  2023. this.min.copy( min );
  2024. this.max.copy( max );
  2025. return this;
  2026. },
  2027. addPoint: function ( point ) {
  2028. if ( point.x < this.min.x ) {
  2029. this.min.x = point.x;
  2030. } else if ( point.x > this.max.x ) {
  2031. this.max.x = point.x;
  2032. }
  2033. if ( point.y < this.min.y ) {
  2034. this.min.y = point.y;
  2035. } else if ( point.y > this.max.y ) {
  2036. this.max.y = point.y;
  2037. }
  2038. if ( point.z < this.min.z ) {
  2039. this.min.z = point.z;
  2040. } else if ( point.z > this.max.z ) {
  2041. this.max.z = point.z;
  2042. }
  2043. },
  2044. setFromPoints: function ( points ) {
  2045. if ( points.length > 0 ) {
  2046. var point = points[ 0 ];
  2047. this.min.copy( point );
  2048. this.max.copy( point );
  2049. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2050. this.addPoint( points[ i ] )
  2051. }
  2052. } else {
  2053. this.makeEmpty();
  2054. }
  2055. return this;
  2056. },
  2057. setFromCenterAndSize: function() {
  2058. var v1 = new THREE.Vector3();
  2059. return function ( center, size ) {
  2060. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2061. this.min.copy( center ).sub( halfSize );
  2062. this.max.copy( center ).add( halfSize );
  2063. return this;
  2064. };
  2065. }(),
  2066. setFromObject: function() {
  2067. // Computes the world-axis-aligned bounding box of an object (including its children),
  2068. // accounting for both the object's, and childrens', world transforms
  2069. var v1 = new THREE.Vector3();
  2070. return function( object ) {
  2071. var scope = this;
  2072. object.updateMatrixWorld( true );
  2073. this.makeEmpty();
  2074. object.traverse( function ( node ) {
  2075. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2076. var vertices = node.geometry.vertices;
  2077. for ( var i = 0, il = vertices.length; i < il; i++ ) {
  2078. v1.copy( vertices[ i ] );
  2079. v1.applyMatrix4( node.matrixWorld );
  2080. scope.expandByPoint( v1 );
  2081. }
  2082. }
  2083. } );
  2084. return this;
  2085. };
  2086. }(),
  2087. copy: function ( box ) {
  2088. this.min.copy( box.min );
  2089. this.max.copy( box.max );
  2090. return this;
  2091. },
  2092. makeEmpty: function () {
  2093. this.min.x = this.min.y = this.min.z = Infinity;
  2094. this.max.x = this.max.y = this.max.z = -Infinity;
  2095. return this;
  2096. },
  2097. empty: function () {
  2098. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2099. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2100. },
  2101. center: function ( optionalTarget ) {
  2102. var result = optionalTarget || new THREE.Vector3();
  2103. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2104. },
  2105. size: function ( optionalTarget ) {
  2106. var result = optionalTarget || new THREE.Vector3();
  2107. return result.subVectors( this.max, this.min );
  2108. },
  2109. expandByPoint: function ( point ) {
  2110. this.min.min( point );
  2111. this.max.max( point );
  2112. return this;
  2113. },
  2114. expandByVector: function ( vector ) {
  2115. this.min.sub( vector );
  2116. this.max.add( vector );
  2117. return this;
  2118. },
  2119. expandByScalar: function ( scalar ) {
  2120. this.min.addScalar( -scalar );
  2121. this.max.addScalar( scalar );
  2122. return this;
  2123. },
  2124. containsPoint: function ( point ) {
  2125. if ( point.x < this.min.x || point.x > this.max.x ||
  2126. point.y < this.min.y || point.y > this.max.y ||
  2127. point.z < this.min.z || point.z > this.max.z ) {
  2128. return false;
  2129. }
  2130. return true;
  2131. },
  2132. containsBox: function ( box ) {
  2133. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2134. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2135. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2136. return true;
  2137. }
  2138. return false;
  2139. },
  2140. getParameter: function ( point, optionalTarget ) {
  2141. // This can potentially have a divide by zero if the box
  2142. // has a size dimension of 0.
  2143. var result = optionalTarget || new THREE.Vector3();
  2144. return result.set(
  2145. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2146. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2147. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2148. );
  2149. },
  2150. isIntersectionBox: function ( box ) {
  2151. // using 6 splitting planes to rule out intersections.
  2152. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2153. box.max.y < this.min.y || box.min.y > this.max.y ||
  2154. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2155. return false;
  2156. }
  2157. return true;
  2158. },
  2159. clampPoint: function ( point, optionalTarget ) {
  2160. var result = optionalTarget || new THREE.Vector3();
  2161. return result.copy( point ).clamp( this.min, this.max );
  2162. },
  2163. distanceToPoint: function() {
  2164. var v1 = new THREE.Vector3();
  2165. return function ( point ) {
  2166. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2167. return clampedPoint.sub( point ).length();
  2168. };
  2169. }(),
  2170. getBoundingSphere: function() {
  2171. var v1 = new THREE.Vector3();
  2172. return function ( optionalTarget ) {
  2173. var result = optionalTarget || new THREE.Sphere();
  2174. result.center = this.center();
  2175. result.radius = this.size( v1 ).length() * 0.5;
  2176. return result;
  2177. };
  2178. }(),
  2179. intersect: function ( box ) {
  2180. this.min.max( box.min );
  2181. this.max.min( box.max );
  2182. return this;
  2183. },
  2184. union: function ( box ) {
  2185. this.min.min( box.min );
  2186. this.max.max( box.max );
  2187. return this;
  2188. },
  2189. applyMatrix4: function() {
  2190. var points = [
  2191. new THREE.Vector3(),
  2192. new THREE.Vector3(),
  2193. new THREE.Vector3(),
  2194. new THREE.Vector3(),
  2195. new THREE.Vector3(),
  2196. new THREE.Vector3(),
  2197. new THREE.Vector3(),
  2198. new THREE.Vector3()
  2199. ];
  2200. return function ( matrix ) {
  2201. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2202. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2203. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2204. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2205. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2206. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2207. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2208. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2209. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2210. this.makeEmpty();
  2211. this.setFromPoints( points );
  2212. return this;
  2213. };
  2214. }(),
  2215. translate: function ( offset ) {
  2216. this.min.add( offset );
  2217. this.max.add( offset );
  2218. return this;
  2219. },
  2220. equals: function ( box ) {
  2221. return box.min.equals( this.min ) && box.max.equals( this.max );
  2222. },
  2223. clone: function () {
  2224. return new THREE.Box3().copy( this );
  2225. }
  2226. };
  2227. /**
  2228. * @author alteredq / http://alteredqualia.com/
  2229. * @author WestLangley / http://github.com/WestLangley
  2230. * @author bhouston / http://exocortex.com
  2231. */
  2232. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2233. this.elements = new Float32Array(9);
  2234. this.set(
  2235. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2236. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2237. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2238. );
  2239. };
  2240. THREE.Matrix3.prototype = {
  2241. constructor: THREE.Matrix3,
  2242. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2243. var te = this.elements;
  2244. te[0] = n11; te[3] = n12; te[6] = n13;
  2245. te[1] = n21; te[4] = n22; te[7] = n23;
  2246. te[2] = n31; te[5] = n32; te[8] = n33;
  2247. return this;
  2248. },
  2249. identity: function () {
  2250. this.set(
  2251. 1, 0, 0,
  2252. 0, 1, 0,
  2253. 0, 0, 1
  2254. );
  2255. return this;
  2256. },
  2257. copy: function ( m ) {
  2258. var me = m.elements;
  2259. this.set(
  2260. me[0], me[3], me[6],
  2261. me[1], me[4], me[7],
  2262. me[2], me[5], me[8]
  2263. );
  2264. return this;
  2265. },
  2266. multiplyVector3: function ( vector ) {
  2267. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2268. return vector.applyMatrix3( this );
  2269. },
  2270. multiplyVector3Array: function() {
  2271. var v1 = new THREE.Vector3();
  2272. return function ( a ) {
  2273. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2274. v1.x = a[ i ];
  2275. v1.y = a[ i + 1 ];
  2276. v1.z = a[ i + 2 ];
  2277. v1.applyMatrix3(this);
  2278. a[ i ] = v1.x;
  2279. a[ i + 1 ] = v1.y;
  2280. a[ i + 2 ] = v1.z;
  2281. }
  2282. return a;
  2283. };
  2284. }(),
  2285. multiplyScalar: function ( s ) {
  2286. var te = this.elements;
  2287. te[0] *= s; te[3] *= s; te[6] *= s;
  2288. te[1] *= s; te[4] *= s; te[7] *= s;
  2289. te[2] *= s; te[5] *= s; te[8] *= s;
  2290. return this;
  2291. },
  2292. determinant: function () {
  2293. var te = this.elements;
  2294. var a = te[0], b = te[1], c = te[2],
  2295. d = te[3], e = te[4], f = te[5],
  2296. g = te[6], h = te[7], i = te[8];
  2297. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2298. },
  2299. getInverse: function ( matrix, throwOnInvertible ) {
  2300. // input: THREE.Matrix4
  2301. // ( based on http://code.google.com/p/webgl-mjs/ )
  2302. var me = matrix.elements;
  2303. var te = this.elements;
  2304. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2305. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2306. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2307. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2308. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2309. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2310. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2311. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2312. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2313. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2314. // no inverse
  2315. if ( det === 0 ) {
  2316. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2317. if ( throwOnInvertible || false ) {
  2318. throw new Error( msg );
  2319. } else {
  2320. console.warn( msg );
  2321. }
  2322. this.identity();
  2323. return this;
  2324. }
  2325. this.multiplyScalar( 1.0 / det );
  2326. return this;
  2327. },
  2328. transpose: function () {
  2329. var tmp, m = this.elements;
  2330. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2331. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2332. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2333. return this;
  2334. },
  2335. getNormalMatrix: function ( m ) {
  2336. // input: THREE.Matrix4
  2337. this.getInverse( m ).transpose();
  2338. return this;
  2339. },
  2340. transposeIntoArray: function ( r ) {
  2341. var m = this.elements;
  2342. r[ 0 ] = m[ 0 ];
  2343. r[ 1 ] = m[ 3 ];
  2344. r[ 2 ] = m[ 6 ];
  2345. r[ 3 ] = m[ 1 ];
  2346. r[ 4 ] = m[ 4 ];
  2347. r[ 5 ] = m[ 7 ];
  2348. r[ 6 ] = m[ 2 ];
  2349. r[ 7 ] = m[ 5 ];
  2350. r[ 8 ] = m[ 8 ];
  2351. return this;
  2352. },
  2353. clone: function () {
  2354. var te = this.elements;
  2355. return new THREE.Matrix3(
  2356. te[0], te[3], te[6],
  2357. te[1], te[4], te[7],
  2358. te[2], te[5], te[8]
  2359. );
  2360. }
  2361. };
  2362. /**
  2363. * @author mrdoob / http://mrdoob.com/
  2364. * @author supereggbert / http://www.paulbrunt.co.uk/
  2365. * @author philogb / http://blog.thejit.org/
  2366. * @author jordi_ros / http://plattsoft.com
  2367. * @author D1plo1d / http://github.com/D1plo1d
  2368. * @author alteredq / http://alteredqualia.com/
  2369. * @author mikael emtinger / http://gomo.se/
  2370. * @author timknip / http://www.floorplanner.com/
  2371. * @author bhouston / http://exocortex.com
  2372. * @author WestLangley / http://github.com/WestLangley
  2373. */
  2374. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2375. this.elements = new Float32Array( 16 );
  2376. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2377. // we should not support semi specification of Matrix4, it is just weird.
  2378. var te = this.elements;
  2379. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2380. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2381. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2382. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2383. };
  2384. THREE.Matrix4.prototype = {
  2385. constructor: THREE.Matrix4,
  2386. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2387. var te = this.elements;
  2388. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2389. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2390. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2391. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2392. return this;
  2393. },
  2394. identity: function () {
  2395. this.set(
  2396. 1, 0, 0, 0,
  2397. 0, 1, 0, 0,
  2398. 0, 0, 1, 0,
  2399. 0, 0, 0, 1
  2400. );
  2401. return this;
  2402. },
  2403. copy: function ( m ) {
  2404. this.elements.set( m.elements );
  2405. return this;
  2406. },
  2407. extractPosition: function ( m ) {
  2408. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2409. return this.copyPosition( m );
  2410. },
  2411. copyPosition: function ( m ) {
  2412. var te = this.elements;
  2413. var me = m.elements;
  2414. te[12] = me[12];
  2415. te[13] = me[13];
  2416. te[14] = me[14];
  2417. return this;
  2418. },
  2419. extractRotation: function () {
  2420. var v1 = new THREE.Vector3();
  2421. return function ( m ) {
  2422. var te = this.elements;
  2423. var me = m.elements;
  2424. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2425. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2426. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2427. te[0] = me[0] * scaleX;
  2428. te[1] = me[1] * scaleX;
  2429. te[2] = me[2] * scaleX;
  2430. te[4] = me[4] * scaleY;
  2431. te[5] = me[5] * scaleY;
  2432. te[6] = me[6] * scaleY;
  2433. te[8] = me[8] * scaleZ;
  2434. te[9] = me[9] * scaleZ;
  2435. te[10] = me[10] * scaleZ;
  2436. return this;
  2437. };
  2438. }(),
  2439. makeRotationFromEuler: function ( euler ) {
  2440. if ( euler instanceof THREE.Euler === false ) {
  2441. console.error( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  2442. }
  2443. var te = this.elements;
  2444. var x = euler.x, y = euler.y, z = euler.z;
  2445. var a = Math.cos( x ), b = Math.sin( x );
  2446. var c = Math.cos( y ), d = Math.sin( y );
  2447. var e = Math.cos( z ), f = Math.sin( z );
  2448. if ( euler.order === 'XYZ' ) {
  2449. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2450. te[0] = c * e;
  2451. te[4] = - c * f;
  2452. te[8] = d;
  2453. te[1] = af + be * d;
  2454. te[5] = ae - bf * d;
  2455. te[9] = - b * c;
  2456. te[2] = bf - ae * d;
  2457. te[6] = be + af * d;
  2458. te[10] = a * c;
  2459. } else if ( euler.order === 'YXZ' ) {
  2460. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2461. te[0] = ce + df * b;
  2462. te[4] = de * b - cf;
  2463. te[8] = a * d;
  2464. te[1] = a * f;
  2465. te[5] = a * e;
  2466. te[9] = - b;
  2467. te[2] = cf * b - de;
  2468. te[6] = df + ce * b;
  2469. te[10] = a * c;
  2470. } else if ( euler.order === 'ZXY' ) {
  2471. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2472. te[0] = ce - df * b;
  2473. te[4] = - a * f;
  2474. te[8] = de + cf * b;
  2475. te[1] = cf + de * b;
  2476. te[5] = a * e;
  2477. te[9] = df - ce * b;
  2478. te[2] = - a * d;
  2479. te[6] = b;
  2480. te[10] = a * c;
  2481. } else if ( euler.order === 'ZYX' ) {
  2482. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2483. te[0] = c * e;
  2484. te[4] = be * d - af;
  2485. te[8] = ae * d + bf;
  2486. te[1] = c * f;
  2487. te[5] = bf * d + ae;
  2488. te[9] = af * d - be;
  2489. te[2] = - d;
  2490. te[6] = b * c;
  2491. te[10] = a * c;
  2492. } else if ( euler.order === 'YZX' ) {
  2493. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2494. te[0] = c * e;
  2495. te[4] = bd - ac * f;
  2496. te[8] = bc * f + ad;
  2497. te[1] = f;
  2498. te[5] = a * e;
  2499. te[9] = - b * e;
  2500. te[2] = - d * e;
  2501. te[6] = ad * f + bc;
  2502. te[10] = ac - bd * f;
  2503. } else if ( euler.order === 'XZY' ) {
  2504. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2505. te[0] = c * e;
  2506. te[4] = - f;
  2507. te[8] = d * e;
  2508. te[1] = ac * f + bd;
  2509. te[5] = a * e;
  2510. te[9] = ad * f - bc;
  2511. te[2] = bc * f - ad;
  2512. te[6] = b * e;
  2513. te[10] = bd * f + ac;
  2514. }
  2515. // last column
  2516. te[3] = 0;
  2517. te[7] = 0;
  2518. te[11] = 0;
  2519. // bottom row
  2520. te[12] = 0;
  2521. te[13] = 0;
  2522. te[14] = 0;
  2523. te[15] = 1;
  2524. return this;
  2525. },
  2526. setRotationFromQuaternion: function ( q ) {
  2527. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2528. return this.makeRotationFromQuaternion( q );
  2529. },
  2530. makeRotationFromQuaternion: function ( q ) {
  2531. var te = this.elements;
  2532. var x = q.x, y = q.y, z = q.z, w = q.w;
  2533. var x2 = x + x, y2 = y + y, z2 = z + z;
  2534. var xx = x * x2, xy = x * y2, xz = x * z2;
  2535. var yy = y * y2, yz = y * z2, zz = z * z2;
  2536. var wx = w * x2, wy = w * y2, wz = w * z2;
  2537. te[0] = 1 - ( yy + zz );
  2538. te[4] = xy - wz;
  2539. te[8] = xz + wy;
  2540. te[1] = xy + wz;
  2541. te[5] = 1 - ( xx + zz );
  2542. te[9] = yz - wx;
  2543. te[2] = xz - wy;
  2544. te[6] = yz + wx;
  2545. te[10] = 1 - ( xx + yy );
  2546. // last column
  2547. te[3] = 0;
  2548. te[7] = 0;
  2549. te[11] = 0;
  2550. // bottom row
  2551. te[12] = 0;
  2552. te[13] = 0;
  2553. te[14] = 0;
  2554. te[15] = 1;
  2555. return this;
  2556. },
  2557. lookAt: function() {
  2558. var x = new THREE.Vector3();
  2559. var y = new THREE.Vector3();
  2560. var z = new THREE.Vector3();
  2561. return function ( eye, target, up ) {
  2562. var te = this.elements;
  2563. z.subVectors( eye, target ).normalize();
  2564. if ( z.length() === 0 ) {
  2565. z.z = 1;
  2566. }
  2567. x.crossVectors( up, z ).normalize();
  2568. if ( x.length() === 0 ) {
  2569. z.x += 0.0001;
  2570. x.crossVectors( up, z ).normalize();
  2571. }
  2572. y.crossVectors( z, x );
  2573. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2574. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2575. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2576. return this;
  2577. };
  2578. }(),
  2579. multiply: function ( m, n ) {
  2580. if ( n !== undefined ) {
  2581. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2582. return this.multiplyMatrices( m, n );
  2583. }
  2584. return this.multiplyMatrices( this, m );
  2585. },
  2586. multiplyMatrices: function ( a, b ) {
  2587. var ae = a.elements;
  2588. var be = b.elements;
  2589. var te = this.elements;
  2590. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2591. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2592. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2593. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2594. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2595. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2596. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2597. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2598. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2599. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2600. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2601. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2602. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2603. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2604. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2605. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2606. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2607. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2608. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2609. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2610. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2611. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2612. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2613. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2614. return this;
  2615. },
  2616. multiplyToArray: function ( a, b, r ) {
  2617. var te = this.elements;
  2618. this.multiplyMatrices( a, b );
  2619. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2620. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2621. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2622. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2623. return this;
  2624. },
  2625. multiplyScalar: function ( s ) {
  2626. var te = this.elements;
  2627. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2628. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2629. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2630. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2631. return this;
  2632. },
  2633. multiplyVector3: function ( vector ) {
  2634. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2635. return vector.applyProjection( this );
  2636. },
  2637. multiplyVector4: function ( vector ) {
  2638. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2639. return vector.applyMatrix4( this );
  2640. },
  2641. multiplyVector3Array: function() {
  2642. var v1 = new THREE.Vector3();
  2643. return function ( a ) {
  2644. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2645. v1.x = a[ i ];
  2646. v1.y = a[ i + 1 ];
  2647. v1.z = a[ i + 2 ];
  2648. v1.applyProjection( this );
  2649. a[ i ] = v1.x;
  2650. a[ i + 1 ] = v1.y;
  2651. a[ i + 2 ] = v1.z;
  2652. }
  2653. return a;
  2654. };
  2655. }(),
  2656. rotateAxis: function ( v ) {
  2657. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2658. v.transformDirection( this );
  2659. },
  2660. crossVector: function ( vector ) {
  2661. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2662. return vector.applyMatrix4( this );
  2663. },
  2664. determinant: function () {
  2665. var te = this.elements;
  2666. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2667. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2668. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2669. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2670. //TODO: make this more efficient
  2671. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2672. return (
  2673. n41 * (
  2674. +n14 * n23 * n32
  2675. -n13 * n24 * n32
  2676. -n14 * n22 * n33
  2677. +n12 * n24 * n33
  2678. +n13 * n22 * n34
  2679. -n12 * n23 * n34
  2680. ) +
  2681. n42 * (
  2682. +n11 * n23 * n34
  2683. -n11 * n24 * n33
  2684. +n14 * n21 * n33
  2685. -n13 * n21 * n34
  2686. +n13 * n24 * n31
  2687. -n14 * n23 * n31
  2688. ) +
  2689. n43 * (
  2690. +n11 * n24 * n32
  2691. -n11 * n22 * n34
  2692. -n14 * n21 * n32
  2693. +n12 * n21 * n34
  2694. +n14 * n22 * n31
  2695. -n12 * n24 * n31
  2696. ) +
  2697. n44 * (
  2698. -n13 * n22 * n31
  2699. -n11 * n23 * n32
  2700. +n11 * n22 * n33
  2701. +n13 * n21 * n32
  2702. -n12 * n21 * n33
  2703. +n12 * n23 * n31
  2704. )
  2705. );
  2706. },
  2707. transpose: function () {
  2708. var te = this.elements;
  2709. var tmp;
  2710. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2711. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2712. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2713. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2714. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2715. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2716. return this;
  2717. },
  2718. flattenToArray: function ( flat ) {
  2719. var te = this.elements;
  2720. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2721. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2722. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2723. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2724. return flat;
  2725. },
  2726. flattenToArrayOffset: function( flat, offset ) {
  2727. var te = this.elements;
  2728. flat[ offset ] = te[0];
  2729. flat[ offset + 1 ] = te[1];
  2730. flat[ offset + 2 ] = te[2];
  2731. flat[ offset + 3 ] = te[3];
  2732. flat[ offset + 4 ] = te[4];
  2733. flat[ offset + 5 ] = te[5];
  2734. flat[ offset + 6 ] = te[6];
  2735. flat[ offset + 7 ] = te[7];
  2736. flat[ offset + 8 ] = te[8];
  2737. flat[ offset + 9 ] = te[9];
  2738. flat[ offset + 10 ] = te[10];
  2739. flat[ offset + 11 ] = te[11];
  2740. flat[ offset + 12 ] = te[12];
  2741. flat[ offset + 13 ] = te[13];
  2742. flat[ offset + 14 ] = te[14];
  2743. flat[ offset + 15 ] = te[15];
  2744. return flat;
  2745. },
  2746. getPosition: function() {
  2747. var v1 = new THREE.Vector3();
  2748. return function () {
  2749. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  2750. var te = this.elements;
  2751. return v1.set( te[12], te[13], te[14] );
  2752. };
  2753. }(),
  2754. setPosition: function ( v ) {
  2755. var te = this.elements;
  2756. te[12] = v.x;
  2757. te[13] = v.y;
  2758. te[14] = v.z;
  2759. return this;
  2760. },
  2761. getInverse: function ( m, throwOnInvertible ) {
  2762. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2763. var te = this.elements;
  2764. var me = m.elements;
  2765. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2766. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2767. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2768. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2769. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2770. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2771. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2772. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2773. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2774. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2775. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2776. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2777. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2778. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2779. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2780. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2781. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2782. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2783. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2784. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2785. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2786. if ( det == 0 ) {
  2787. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2788. if ( throwOnInvertible || false ) {
  2789. throw new Error( msg );
  2790. } else {
  2791. console.warn( msg );
  2792. }
  2793. this.identity();
  2794. return this;
  2795. }
  2796. this.multiplyScalar( 1 / det );
  2797. return this;
  2798. },
  2799. translate: function ( v ) {
  2800. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2801. },
  2802. rotateX: function ( angle ) {
  2803. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2804. },
  2805. rotateY: function ( angle ) {
  2806. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2807. },
  2808. rotateZ: function ( angle ) {
  2809. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2810. },
  2811. rotateByAxis: function ( axis, angle ) {
  2812. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2813. },
  2814. scale: function ( v ) {
  2815. var te = this.elements;
  2816. var x = v.x, y = v.y, z = v.z;
  2817. te[0] *= x; te[4] *= y; te[8] *= z;
  2818. te[1] *= x; te[5] *= y; te[9] *= z;
  2819. te[2] *= x; te[6] *= y; te[10] *= z;
  2820. te[3] *= x; te[7] *= y; te[11] *= z;
  2821. return this;
  2822. },
  2823. getMaxScaleOnAxis: function () {
  2824. var te = this.elements;
  2825. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2826. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2827. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2828. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2829. },
  2830. makeTranslation: function ( x, y, z ) {
  2831. this.set(
  2832. 1, 0, 0, x,
  2833. 0, 1, 0, y,
  2834. 0, 0, 1, z,
  2835. 0, 0, 0, 1
  2836. );
  2837. return this;
  2838. },
  2839. makeRotationX: function ( theta ) {
  2840. var c = Math.cos( theta ), s = Math.sin( theta );
  2841. this.set(
  2842. 1, 0, 0, 0,
  2843. 0, c, -s, 0,
  2844. 0, s, c, 0,
  2845. 0, 0, 0, 1
  2846. );
  2847. return this;
  2848. },
  2849. makeRotationY: function ( theta ) {
  2850. var c = Math.cos( theta ), s = Math.sin( theta );
  2851. this.set(
  2852. c, 0, s, 0,
  2853. 0, 1, 0, 0,
  2854. -s, 0, c, 0,
  2855. 0, 0, 0, 1
  2856. );
  2857. return this;
  2858. },
  2859. makeRotationZ: function ( theta ) {
  2860. var c = Math.cos( theta ), s = Math.sin( theta );
  2861. this.set(
  2862. c, -s, 0, 0,
  2863. s, c, 0, 0,
  2864. 0, 0, 1, 0,
  2865. 0, 0, 0, 1
  2866. );
  2867. return this;
  2868. },
  2869. makeRotationAxis: function ( axis, angle ) {
  2870. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2871. var c = Math.cos( angle );
  2872. var s = Math.sin( angle );
  2873. var t = 1 - c;
  2874. var x = axis.x, y = axis.y, z = axis.z;
  2875. var tx = t * x, ty = t * y;
  2876. this.set(
  2877. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2878. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2879. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2880. 0, 0, 0, 1
  2881. );
  2882. return this;
  2883. },
  2884. makeScale: function ( x, y, z ) {
  2885. this.set(
  2886. x, 0, 0, 0,
  2887. 0, y, 0, 0,
  2888. 0, 0, z, 0,
  2889. 0, 0, 0, 1
  2890. );
  2891. return this;
  2892. },
  2893. compose: function ( position, quaternion, scale ) {
  2894. this.makeRotationFromQuaternion( quaternion );
  2895. this.scale( scale );
  2896. this.setPosition( position );
  2897. return this;
  2898. },
  2899. decompose: function () {
  2900. var vector = new THREE.Vector3();
  2901. var matrix = new THREE.Matrix4();
  2902. return function ( position, quaternion, scale ) {
  2903. var te = this.elements;
  2904. var sx = vector.set( te[0], te[1], te[2] ).length();
  2905. var sy = vector.set( te[4], te[5], te[6] ).length();
  2906. var sz = vector.set( te[8], te[9], te[10] ).length();
  2907. position.x = te[12];
  2908. position.y = te[13];
  2909. position.z = te[14];
  2910. // scale the rotation part
  2911. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  2912. var invSX = 1 / sx;
  2913. var invSY = 1 / sy;
  2914. var invSZ = 1 / sz;
  2915. matrix.elements[0] *= invSX;
  2916. matrix.elements[1] *= invSX;
  2917. matrix.elements[2] *= invSX;
  2918. matrix.elements[4] *= invSY;
  2919. matrix.elements[5] *= invSY;
  2920. matrix.elements[6] *= invSY;
  2921. matrix.elements[8] *= invSZ;
  2922. matrix.elements[9] *= invSZ;
  2923. matrix.elements[10] *= invSZ;
  2924. quaternion.setFromRotationMatrix( matrix );
  2925. scale.x = sx;
  2926. scale.y = sy;
  2927. scale.z = sz;
  2928. return this;
  2929. };
  2930. }(),
  2931. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2932. var te = this.elements;
  2933. var x = 2 * near / ( right - left );
  2934. var y = 2 * near / ( top - bottom );
  2935. var a = ( right + left ) / ( right - left );
  2936. var b = ( top + bottom ) / ( top - bottom );
  2937. var c = - ( far + near ) / ( far - near );
  2938. var d = - 2 * far * near / ( far - near );
  2939. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2940. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2941. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2942. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2943. return this;
  2944. },
  2945. makePerspective: function ( fov, aspect, near, far ) {
  2946. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2947. var ymin = - ymax;
  2948. var xmin = ymin * aspect;
  2949. var xmax = ymax * aspect;
  2950. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2951. },
  2952. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2953. var te = this.elements;
  2954. var w = right - left;
  2955. var h = top - bottom;
  2956. var p = far - near;
  2957. var x = ( right + left ) / w;
  2958. var y = ( top + bottom ) / h;
  2959. var z = ( far + near ) / p;
  2960. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2961. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2962. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2963. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2964. return this;
  2965. },
  2966. fromArray: function ( array ) {
  2967. this.elements.set( array );
  2968. return this;
  2969. },
  2970. toArray: function () {
  2971. var te = this.elements;
  2972. return [
  2973. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  2974. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  2975. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  2976. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  2977. ];
  2978. },
  2979. clone: function () {
  2980. var te = this.elements;
  2981. return new THREE.Matrix4(
  2982. te[0], te[4], te[8], te[12],
  2983. te[1], te[5], te[9], te[13],
  2984. te[2], te[6], te[10], te[14],
  2985. te[3], te[7], te[11], te[15]
  2986. );
  2987. }
  2988. };
  2989. /**
  2990. * @author bhouston / http://exocortex.com
  2991. */
  2992. THREE.Ray = function ( origin, direction ) {
  2993. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  2994. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  2995. };
  2996. THREE.Ray.prototype = {
  2997. constructor: THREE.Ray,
  2998. set: function ( origin, direction ) {
  2999. this.origin.copy( origin );
  3000. this.direction.copy( direction );
  3001. return this;
  3002. },
  3003. copy: function ( ray ) {
  3004. this.origin.copy( ray.origin );
  3005. this.direction.copy( ray.direction );
  3006. return this;
  3007. },
  3008. at: function ( t, optionalTarget ) {
  3009. var result = optionalTarget || new THREE.Vector3();
  3010. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3011. },
  3012. recast: function () {
  3013. var v1 = new THREE.Vector3();
  3014. return function ( t ) {
  3015. this.origin.copy( this.at( t, v1 ) );
  3016. return this;
  3017. };
  3018. }(),
  3019. closestPointToPoint: function ( point, optionalTarget ) {
  3020. var result = optionalTarget || new THREE.Vector3();
  3021. result.subVectors( point, this.origin );
  3022. var directionDistance = result.dot( this.direction );
  3023. if ( directionDistance < 0 ) {
  3024. return result.copy( this.origin );
  3025. }
  3026. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3027. },
  3028. distanceToPoint: function () {
  3029. var v1 = new THREE.Vector3();
  3030. return function ( point ) {
  3031. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3032. // point behind the ray
  3033. if ( directionDistance < 0 ) {
  3034. return this.origin.distanceTo( point );
  3035. }
  3036. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3037. return v1.distanceTo( point );
  3038. };
  3039. }(),
  3040. distanceSqToSegment: function( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3041. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3042. // It returns the min distance between the ray and the segment
  3043. // defined by v0 and v1
  3044. // It can also set two optional targets :
  3045. // - The closest point on the ray
  3046. // - The closest point on the segment
  3047. var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 );
  3048. var segDir = v1.clone().sub( v0 ).normalize();
  3049. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3050. var diff = this.origin.clone().sub( segCenter );
  3051. var a01 = - this.direction.dot( segDir );
  3052. var b0 = diff.dot( this.direction );
  3053. var b1 = - diff.dot( segDir );
  3054. var c = diff.lengthSq();
  3055. var det = Math.abs( 1 - a01 * a01 );
  3056. var s0, s1, sqrDist, extDet;
  3057. if ( det >= 0 ) {
  3058. // The ray and segment are not parallel.
  3059. s0 = a01 * b1 - b0;
  3060. s1 = a01 * b0 - b1;
  3061. extDet = segExtent * det;
  3062. if ( s0 >= 0 ) {
  3063. if ( s1 >= - extDet ) {
  3064. if ( s1 <= extDet ) {
  3065. // region 0
  3066. // Minimum at interior points of ray and segment.
  3067. var invDet = 1 / det;
  3068. s0 *= invDet;
  3069. s1 *= invDet;
  3070. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3071. } else {
  3072. // region 1
  3073. s1 = segExtent;
  3074. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3075. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3076. }
  3077. } else {
  3078. // region 5
  3079. s1 = - segExtent;
  3080. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3081. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3082. }
  3083. } else {
  3084. if ( s1 <= - extDet) {
  3085. // region 4
  3086. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3087. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3088. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3089. } else if ( s1 <= extDet ) {
  3090. // region 3
  3091. s0 = 0;
  3092. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3093. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3094. } else {
  3095. // region 2
  3096. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3097. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3098. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3099. }
  3100. }
  3101. } else {
  3102. // Ray and segment are parallel.
  3103. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3104. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3105. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3106. }
  3107. if ( optionalPointOnRay ) {
  3108. optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) );
  3109. }
  3110. if ( optionalPointOnSegment ) {
  3111. optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) );
  3112. }
  3113. return sqrDist;
  3114. },
  3115. isIntersectionSphere: function ( sphere ) {
  3116. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3117. },
  3118. isIntersectionPlane: function ( plane ) {
  3119. // check if the ray lies on the plane first
  3120. var distToPoint = plane.distanceToPoint( this.origin );
  3121. if ( distToPoint === 0 ) {
  3122. return true;
  3123. }
  3124. var denominator = plane.normal.dot( this.direction );
  3125. if ( denominator * distToPoint < 0 ) {
  3126. return true
  3127. }
  3128. // ray origin is behind the plane (and is pointing behind it)
  3129. return false;
  3130. },
  3131. distanceToPlane: function ( plane ) {
  3132. var denominator = plane.normal.dot( this.direction );
  3133. if ( denominator == 0 ) {
  3134. // line is coplanar, return origin
  3135. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3136. return 0;
  3137. }
  3138. // Null is preferable to undefined since undefined means.... it is undefined
  3139. return null;
  3140. }
  3141. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3142. // Return if the ray never intersects the plane
  3143. return t >= 0 ? t : null;
  3144. },
  3145. intersectPlane: function ( plane, optionalTarget ) {
  3146. var t = this.distanceToPlane( plane );
  3147. if ( t === null ) {
  3148. return null;
  3149. }
  3150. return this.at( t, optionalTarget );
  3151. },
  3152. isIntersectionBox: function () {
  3153. var v = new THREE.Vector3();
  3154. return function ( box ) {
  3155. return this.intersectBox( box, v ) !== null;
  3156. }
  3157. }(),
  3158. intersectBox: function ( box , optionalTarget ) {
  3159. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3160. var tmin,tmax,tymin,tymax,tzmin,tzmax;
  3161. var invdirx = 1/this.direction.x,
  3162. invdiry = 1/this.direction.y,
  3163. invdirz = 1/this.direction.z;
  3164. var origin = this.origin;
  3165. if (invdirx >= 0) {
  3166. tmin = (box.min.x - origin.x) * invdirx;
  3167. tmax = (box.max.x - origin.x) * invdirx;
  3168. } else {
  3169. tmin = (box.max.x - origin.x) * invdirx;
  3170. tmax = (box.min.x - origin.x) * invdirx;
  3171. }
  3172. if (invdiry >= 0) {
  3173. tymin = (box.min.y - origin.y) * invdiry;
  3174. tymax = (box.max.y - origin.y) * invdiry;
  3175. } else {
  3176. tymin = (box.max.y - origin.y) * invdiry;
  3177. tymax = (box.min.y - origin.y) * invdiry;
  3178. }
  3179. if ((tmin > tymax) || (tymin > tmax)) return null;
  3180. // These lines also handle the case where tmin or tmax is NaN
  3181. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3182. if (tymin > tmin || tmin !== tmin ) tmin = tymin;
  3183. if (tymax < tmax || tmax !== tmax ) tmax = tymax;
  3184. if (invdirz >= 0) {
  3185. tzmin = (box.min.z - origin.z) * invdirz;
  3186. tzmax = (box.max.z - origin.z) * invdirz;
  3187. } else {
  3188. tzmin = (box.max.z - origin.z) * invdirz;
  3189. tzmax = (box.min.z - origin.z) * invdirz;
  3190. }
  3191. if ((tmin > tzmax) || (tzmin > tmax)) return null;
  3192. if (tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3193. if (tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3194. //return point closest to the ray (positive side)
  3195. if ( tmax < 0 ) return null;
  3196. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3197. },
  3198. intersectTriangle: function() {
  3199. // Compute the offset origin, edges, and normal.
  3200. var diff = new THREE.Vector3();
  3201. var edge1 = new THREE.Vector3();
  3202. var edge2 = new THREE.Vector3();
  3203. var normal = new THREE.Vector3();
  3204. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3205. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3206. edge1.subVectors( b, a );
  3207. edge2.subVectors( c, a );
  3208. normal.crossVectors( edge1, edge2 );
  3209. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3210. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3211. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3212. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3213. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3214. var DdN = this.direction.dot( normal );
  3215. var sign;
  3216. if ( DdN > 0 ) {
  3217. if ( backfaceCulling ) return null;
  3218. sign = 1;
  3219. } else if ( DdN < 0 ) {
  3220. sign = - 1;
  3221. DdN = - DdN;
  3222. } else {
  3223. return null;
  3224. }
  3225. diff.subVectors( this.origin, a );
  3226. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3227. // b1 < 0, no intersection
  3228. if ( DdQxE2 < 0 ) {
  3229. return null;
  3230. }
  3231. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3232. // b2 < 0, no intersection
  3233. if ( DdE1xQ < 0 ) {
  3234. return null;
  3235. }
  3236. // b1+b2 > 1, no intersection
  3237. if ( DdQxE2 + DdE1xQ > DdN ) {
  3238. return null;
  3239. }
  3240. // Line intersects triangle, check if ray does.
  3241. var QdN = - sign * diff.dot( normal );
  3242. // t < 0, no intersection
  3243. if ( QdN < 0 ) {
  3244. return null;
  3245. }
  3246. // Ray intersects triangle.
  3247. return this.at( QdN / DdN, optionalTarget );
  3248. }
  3249. }(),
  3250. applyMatrix4: function ( matrix4 ) {
  3251. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3252. this.origin.applyMatrix4( matrix4 );
  3253. this.direction.sub( this.origin );
  3254. this.direction.normalize();
  3255. return this;
  3256. },
  3257. equals: function ( ray ) {
  3258. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3259. },
  3260. clone: function () {
  3261. return new THREE.Ray().copy( this );
  3262. }
  3263. };
  3264. /**
  3265. * @author bhouston / http://exocortex.com
  3266. * @author mrdoob / http://mrdoob.com/
  3267. */
  3268. THREE.Sphere = function ( center, radius ) {
  3269. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3270. this.radius = ( radius !== undefined ) ? radius : 0;
  3271. };
  3272. THREE.Sphere.prototype = {
  3273. constructor: THREE.Sphere,
  3274. set: function ( center, radius ) {
  3275. this.center.copy( center );
  3276. this.radius = radius;
  3277. return this;
  3278. },
  3279. setFromPoints: function () {
  3280. var box = new THREE.Box3();
  3281. return function ( points, optionalCenter ) {
  3282. var center = this.center;
  3283. if ( optionalCenter !== undefined ) {
  3284. center.copy( optionalCenter );
  3285. } else {
  3286. box.setFromPoints( points ).center( center );
  3287. }
  3288. var maxRadiusSq = 0;
  3289. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3290. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3291. }
  3292. this.radius = Math.sqrt( maxRadiusSq );
  3293. return this;
  3294. };
  3295. }(),
  3296. copy: function ( sphere ) {
  3297. this.center.copy( sphere.center );
  3298. this.radius = sphere.radius;
  3299. return this;
  3300. },
  3301. empty: function () {
  3302. return ( this.radius <= 0 );
  3303. },
  3304. containsPoint: function ( point ) {
  3305. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3306. },
  3307. distanceToPoint: function ( point ) {
  3308. return ( point.distanceTo( this.center ) - this.radius );
  3309. },
  3310. intersectsSphere: function ( sphere ) {
  3311. var radiusSum = this.radius + sphere.radius;
  3312. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3313. },
  3314. clampPoint: function ( point, optionalTarget ) {
  3315. var deltaLengthSq = this.center.distanceToSquared( point );
  3316. var result = optionalTarget || new THREE.Vector3();
  3317. result.copy( point );
  3318. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3319. result.sub( this.center ).normalize();
  3320. result.multiplyScalar( this.radius ).add( this.center );
  3321. }
  3322. return result;
  3323. },
  3324. getBoundingBox: function ( optionalTarget ) {
  3325. var box = optionalTarget || new THREE.Box3();
  3326. box.set( this.center, this.center );
  3327. box.expandByScalar( this.radius );
  3328. return box;
  3329. },
  3330. applyMatrix4: function ( matrix ) {
  3331. this.center.applyMatrix4( matrix );
  3332. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3333. return this;
  3334. },
  3335. translate: function ( offset ) {
  3336. this.center.add( offset );
  3337. return this;
  3338. },
  3339. equals: function ( sphere ) {
  3340. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3341. },
  3342. clone: function () {
  3343. return new THREE.Sphere().copy( this );
  3344. }
  3345. };
  3346. /**
  3347. * @author mrdoob / http://mrdoob.com/
  3348. * @author alteredq / http://alteredqualia.com/
  3349. * @author bhouston / http://exocortex.com
  3350. */
  3351. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3352. this.planes = [
  3353. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3354. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3355. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3356. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3357. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3358. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3359. ];
  3360. };
  3361. THREE.Frustum.prototype = {
  3362. constructor: THREE.Frustum,
  3363. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3364. var planes = this.planes;
  3365. planes[0].copy( p0 );
  3366. planes[1].copy( p1 );
  3367. planes[2].copy( p2 );
  3368. planes[3].copy( p3 );
  3369. planes[4].copy( p4 );
  3370. planes[5].copy( p5 );
  3371. return this;
  3372. },
  3373. copy: function ( frustum ) {
  3374. var planes = this.planes;
  3375. for( var i = 0; i < 6; i ++ ) {
  3376. planes[i].copy( frustum.planes[i] );
  3377. }
  3378. return this;
  3379. },
  3380. setFromMatrix: function ( m ) {
  3381. var planes = this.planes;
  3382. var me = m.elements;
  3383. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3384. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3385. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3386. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3387. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3388. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3389. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3390. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3391. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3392. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3393. return this;
  3394. },
  3395. intersectsObject: function () {
  3396. var sphere = new THREE.Sphere();
  3397. return function ( object ) {
  3398. var geometry = object.geometry;
  3399. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3400. sphere.copy( geometry.boundingSphere );
  3401. sphere.applyMatrix4( object.matrixWorld );
  3402. return this.intersectsSphere( sphere );
  3403. };
  3404. }(),
  3405. intersectsSphere: function ( sphere ) {
  3406. var planes = this.planes;
  3407. var center = sphere.center;
  3408. var negRadius = -sphere.radius;
  3409. for ( var i = 0; i < 6; i ++ ) {
  3410. var distance = planes[ i ].distanceToPoint( center );
  3411. if ( distance < negRadius ) {
  3412. return false;
  3413. }
  3414. }
  3415. return true;
  3416. },
  3417. intersectsBox : function() {
  3418. var p1 = new THREE.Vector3(),
  3419. p2 = new THREE.Vector3();
  3420. return function( box ) {
  3421. var planes = this.planes;
  3422. for ( var i = 0; i < 6 ; i ++ ) {
  3423. var plane = planes[i];
  3424. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3425. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3426. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3427. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3428. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3429. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3430. var d1 = plane.distanceToPoint( p1 );
  3431. var d2 = plane.distanceToPoint( p2 );
  3432. // if both outside plane, no intersection
  3433. if ( d1 < 0 && d2 < 0 ) {
  3434. return false;
  3435. }
  3436. }
  3437. return true;
  3438. };
  3439. }(),
  3440. containsPoint: function ( point ) {
  3441. var planes = this.planes;
  3442. for ( var i = 0; i < 6; i ++ ) {
  3443. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3444. return false;
  3445. }
  3446. }
  3447. return true;
  3448. },
  3449. clone: function () {
  3450. return new THREE.Frustum().copy( this );
  3451. }
  3452. };
  3453. /**
  3454. * @author bhouston / http://exocortex.com
  3455. */
  3456. THREE.Plane = function ( normal, constant ) {
  3457. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3458. this.constant = ( constant !== undefined ) ? constant : 0;
  3459. };
  3460. THREE.Plane.prototype = {
  3461. constructor: THREE.Plane,
  3462. set: function ( normal, constant ) {
  3463. this.normal.copy( normal );
  3464. this.constant = constant;
  3465. return this;
  3466. },
  3467. setComponents: function ( x, y, z, w ) {
  3468. this.normal.set( x, y, z );
  3469. this.constant = w;
  3470. return this;
  3471. },
  3472. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3473. this.normal.copy( normal );
  3474. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3475. return this;
  3476. },
  3477. setFromCoplanarPoints: function() {
  3478. var v1 = new THREE.Vector3();
  3479. var v2 = new THREE.Vector3();
  3480. return function ( a, b, c ) {
  3481. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3482. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3483. this.setFromNormalAndCoplanarPoint( normal, a );
  3484. return this;
  3485. };
  3486. }(),
  3487. copy: function ( plane ) {
  3488. this.normal.copy( plane.normal );
  3489. this.constant = plane.constant;
  3490. return this;
  3491. },
  3492. normalize: function () {
  3493. // Note: will lead to a divide by zero if the plane is invalid.
  3494. var inverseNormalLength = 1.0 / this.normal.length();
  3495. this.normal.multiplyScalar( inverseNormalLength );
  3496. this.constant *= inverseNormalLength;
  3497. return this;
  3498. },
  3499. negate: function () {
  3500. this.constant *= -1;
  3501. this.normal.negate();
  3502. return this;
  3503. },
  3504. distanceToPoint: function ( point ) {
  3505. return this.normal.dot( point ) + this.constant;
  3506. },
  3507. distanceToSphere: function ( sphere ) {
  3508. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3509. },
  3510. projectPoint: function ( point, optionalTarget ) {
  3511. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3512. },
  3513. orthoPoint: function ( point, optionalTarget ) {
  3514. var perpendicularMagnitude = this.distanceToPoint( point );
  3515. var result = optionalTarget || new THREE.Vector3();
  3516. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3517. },
  3518. isIntersectionLine: function ( line ) {
  3519. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3520. var startSign = this.distanceToPoint( line.start );
  3521. var endSign = this.distanceToPoint( line.end );
  3522. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3523. },
  3524. intersectLine: function() {
  3525. var v1 = new THREE.Vector3();
  3526. return function ( line, optionalTarget ) {
  3527. var result = optionalTarget || new THREE.Vector3();
  3528. var direction = line.delta( v1 );
  3529. var denominator = this.normal.dot( direction );
  3530. if ( denominator == 0 ) {
  3531. // line is coplanar, return origin
  3532. if( this.distanceToPoint( line.start ) == 0 ) {
  3533. return result.copy( line.start );
  3534. }
  3535. // Unsure if this is the correct method to handle this case.
  3536. return undefined;
  3537. }
  3538. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3539. if( t < 0 || t > 1 ) {
  3540. return undefined;
  3541. }
  3542. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3543. };
  3544. }(),
  3545. coplanarPoint: function ( optionalTarget ) {
  3546. var result = optionalTarget || new THREE.Vector3();
  3547. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3548. },
  3549. applyMatrix4: function() {
  3550. var v1 = new THREE.Vector3();
  3551. var v2 = new THREE.Vector3();
  3552. var m1 = new THREE.Matrix3();
  3553. return function ( matrix, optionalNormalMatrix ) {
  3554. // compute new normal based on theory here:
  3555. // http://www.songho.ca/opengl/gl_normaltransform.html
  3556. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3557. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3558. var newCoplanarPoint = this.coplanarPoint( v2 );
  3559. newCoplanarPoint.applyMatrix4( matrix );
  3560. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3561. return this;
  3562. };
  3563. }(),
  3564. translate: function ( offset ) {
  3565. this.constant = this.constant - offset.dot( this.normal );
  3566. return this;
  3567. },
  3568. equals: function ( plane ) {
  3569. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3570. },
  3571. clone: function () {
  3572. return new THREE.Plane().copy( this );
  3573. }
  3574. };
  3575. /**
  3576. * @author alteredq / http://alteredqualia.com/
  3577. * @author mrdoob / http://mrdoob.com/
  3578. */
  3579. THREE.Math = {
  3580. PI2: Math.PI * 2,
  3581. generateUUID: function () {
  3582. // http://www.broofa.com/Tools/Math.uuid.htm
  3583. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3584. var uuid = new Array(36);
  3585. var rnd = 0, r;
  3586. return function () {
  3587. for ( var i = 0; i < 36; i ++ ) {
  3588. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3589. uuid[ i ] = '-';
  3590. } else if ( i == 14 ) {
  3591. uuid[ i ] = '4';
  3592. } else {
  3593. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3594. r = rnd & 0xf;
  3595. rnd = rnd >> 4;
  3596. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3597. }
  3598. }
  3599. return uuid.join('');
  3600. };
  3601. }(),
  3602. // Clamp value to range <a, b>
  3603. clamp: function ( x, a, b ) {
  3604. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3605. },
  3606. // Clamp value to range <a, inf)
  3607. clampBottom: function ( x, a ) {
  3608. return x < a ? a : x;
  3609. },
  3610. // Linear mapping from range <a1, a2> to range <b1, b2>
  3611. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3612. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3613. },
  3614. // http://en.wikipedia.org/wiki/Smoothstep
  3615. smoothstep: function ( x, min, max ) {
  3616. if ( x <= min ) return 0;
  3617. if ( x >= max ) return 1;
  3618. x = ( x - min )/( max - min );
  3619. return x*x*(3 - 2*x);
  3620. },
  3621. smootherstep: function ( x, min, max ) {
  3622. if ( x <= min ) return 0;
  3623. if ( x >= max ) return 1;
  3624. x = ( x - min )/( max - min );
  3625. return x*x*x*(x*(x*6 - 15) + 10);
  3626. },
  3627. // Random float from <0, 1> with 16 bits of randomness
  3628. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3629. random16: function () {
  3630. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3631. },
  3632. // Random integer from <low, high> interval
  3633. randInt: function ( low, high ) {
  3634. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3635. },
  3636. // Random float from <low, high> interval
  3637. randFloat: function ( low, high ) {
  3638. return low + Math.random() * ( high - low );
  3639. },
  3640. // Random float from <-range/2, range/2> interval
  3641. randFloatSpread: function ( range ) {
  3642. return range * ( 0.5 - Math.random() );
  3643. },
  3644. sign: function ( x ) {
  3645. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  3646. },
  3647. degToRad: function() {
  3648. var degreeToRadiansFactor = Math.PI / 180;
  3649. return function ( degrees ) {
  3650. return degrees * degreeToRadiansFactor;
  3651. };
  3652. }(),
  3653. radToDeg: function() {
  3654. var radianToDegreesFactor = 180 / Math.PI;
  3655. return function ( radians ) {
  3656. return radians * radianToDegreesFactor;
  3657. };
  3658. }()
  3659. };
  3660. /**
  3661. * Spline from Tween.js, slightly optimized (and trashed)
  3662. * http://sole.github.com/tween.js/examples/05_spline.html
  3663. *
  3664. * @author mrdoob / http://mrdoob.com/
  3665. * @author alteredq / http://alteredqualia.com/
  3666. */
  3667. THREE.Spline = function ( points ) {
  3668. this.points = points;
  3669. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3670. point, intPoint, weight, w2, w3,
  3671. pa, pb, pc, pd;
  3672. this.initFromArray = function( a ) {
  3673. this.points = [];
  3674. for ( var i = 0; i < a.length; i++ ) {
  3675. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3676. }
  3677. };
  3678. this.getPoint = function ( k ) {
  3679. point = ( this.points.length - 1 ) * k;
  3680. intPoint = Math.floor( point );
  3681. weight = point - intPoint;
  3682. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3683. c[ 1 ] = intPoint;
  3684. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3685. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3686. pa = this.points[ c[ 0 ] ];
  3687. pb = this.points[ c[ 1 ] ];
  3688. pc = this.points[ c[ 2 ] ];
  3689. pd = this.points[ c[ 3 ] ];
  3690. w2 = weight * weight;
  3691. w3 = weight * w2;
  3692. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3693. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3694. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3695. return v3;
  3696. };
  3697. this.getControlPointsArray = function () {
  3698. var i, p, l = this.points.length,
  3699. coords = [];
  3700. for ( i = 0; i < l; i ++ ) {
  3701. p = this.points[ i ];
  3702. coords[ i ] = [ p.x, p.y, p.z ];
  3703. }
  3704. return coords;
  3705. };
  3706. // approximate length by summing linear segments
  3707. this.getLength = function ( nSubDivisions ) {
  3708. var i, index, nSamples, position,
  3709. point = 0, intPoint = 0, oldIntPoint = 0,
  3710. oldPosition = new THREE.Vector3(),
  3711. tmpVec = new THREE.Vector3(),
  3712. chunkLengths = [],
  3713. totalLength = 0;
  3714. // first point has 0 length
  3715. chunkLengths[ 0 ] = 0;
  3716. if ( !nSubDivisions ) nSubDivisions = 100;
  3717. nSamples = this.points.length * nSubDivisions;
  3718. oldPosition.copy( this.points[ 0 ] );
  3719. for ( i = 1; i < nSamples; i ++ ) {
  3720. index = i / nSamples;
  3721. position = this.getPoint( index );
  3722. tmpVec.copy( position );
  3723. totalLength += tmpVec.distanceTo( oldPosition );
  3724. oldPosition.copy( position );
  3725. point = ( this.points.length - 1 ) * index;
  3726. intPoint = Math.floor( point );
  3727. if ( intPoint != oldIntPoint ) {
  3728. chunkLengths[ intPoint ] = totalLength;
  3729. oldIntPoint = intPoint;
  3730. }
  3731. }
  3732. // last point ends with total length
  3733. chunkLengths[ chunkLengths.length ] = totalLength;
  3734. return { chunks: chunkLengths, total: totalLength };
  3735. };
  3736. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3737. var i, j,
  3738. index, indexCurrent, indexNext,
  3739. linearDistance, realDistance,
  3740. sampling, position,
  3741. newpoints = [],
  3742. tmpVec = new THREE.Vector3(),
  3743. sl = this.getLength();
  3744. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3745. for ( i = 1; i < this.points.length; i++ ) {
  3746. //tmpVec.copy( this.points[ i - 1 ] );
  3747. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3748. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3749. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3750. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3751. indexNext = i / ( this.points.length - 1 );
  3752. for ( j = 1; j < sampling - 1; j++ ) {
  3753. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3754. position = this.getPoint( index );
  3755. newpoints.push( tmpVec.copy( position ).clone() );
  3756. }
  3757. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3758. }
  3759. this.points = newpoints;
  3760. };
  3761. // Catmull-Rom
  3762. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3763. var v0 = ( p2 - p0 ) * 0.5,
  3764. v1 = ( p3 - p1 ) * 0.5;
  3765. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3766. };
  3767. };
  3768. /**
  3769. * @author bhouston / http://exocortex.com
  3770. * @author mrdoob / http://mrdoob.com/
  3771. */
  3772. THREE.Triangle = function ( a, b, c ) {
  3773. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3774. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3775. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3776. };
  3777. THREE.Triangle.normal = function() {
  3778. var v0 = new THREE.Vector3();
  3779. return function ( a, b, c, optionalTarget ) {
  3780. var result = optionalTarget || new THREE.Vector3();
  3781. result.subVectors( c, b );
  3782. v0.subVectors( a, b );
  3783. result.cross( v0 );
  3784. var resultLengthSq = result.lengthSq();
  3785. if( resultLengthSq > 0 ) {
  3786. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3787. }
  3788. return result.set( 0, 0, 0 );
  3789. };
  3790. }();
  3791. // static/instance method to calculate barycoordinates
  3792. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3793. THREE.Triangle.barycoordFromPoint = function() {
  3794. var v0 = new THREE.Vector3();
  3795. var v1 = new THREE.Vector3();
  3796. var v2 = new THREE.Vector3();
  3797. return function ( point, a, b, c, optionalTarget ) {
  3798. v0.subVectors( c, a );
  3799. v1.subVectors( b, a );
  3800. v2.subVectors( point, a );
  3801. var dot00 = v0.dot( v0 );
  3802. var dot01 = v0.dot( v1 );
  3803. var dot02 = v0.dot( v2 );
  3804. var dot11 = v1.dot( v1 );
  3805. var dot12 = v1.dot( v2 );
  3806. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3807. var result = optionalTarget || new THREE.Vector3();
  3808. // colinear or singular triangle
  3809. if( denom == 0 ) {
  3810. // arbitrary location outside of triangle?
  3811. // not sure if this is the best idea, maybe should be returning undefined
  3812. return result.set( -2, -1, -1 );
  3813. }
  3814. var invDenom = 1 / denom;
  3815. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3816. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3817. // barycoordinates must always sum to 1
  3818. return result.set( 1 - u - v, v, u );
  3819. };
  3820. }();
  3821. THREE.Triangle.containsPoint = function() {
  3822. var v1 = new THREE.Vector3();
  3823. return function ( point, a, b, c ) {
  3824. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3825. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3826. };
  3827. }();
  3828. THREE.Triangle.prototype = {
  3829. constructor: THREE.Triangle,
  3830. set: function ( a, b, c ) {
  3831. this.a.copy( a );
  3832. this.b.copy( b );
  3833. this.c.copy( c );
  3834. return this;
  3835. },
  3836. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3837. this.a.copy( points[i0] );
  3838. this.b.copy( points[i1] );
  3839. this.c.copy( points[i2] );
  3840. return this;
  3841. },
  3842. copy: function ( triangle ) {
  3843. this.a.copy( triangle.a );
  3844. this.b.copy( triangle.b );
  3845. this.c.copy( triangle.c );
  3846. return this;
  3847. },
  3848. area: function() {
  3849. var v0 = new THREE.Vector3();
  3850. var v1 = new THREE.Vector3();
  3851. return function () {
  3852. v0.subVectors( this.c, this.b );
  3853. v1.subVectors( this.a, this.b );
  3854. return v0.cross( v1 ).length() * 0.5;
  3855. };
  3856. }(),
  3857. midpoint: function ( optionalTarget ) {
  3858. var result = optionalTarget || new THREE.Vector3();
  3859. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3860. },
  3861. normal: function ( optionalTarget ) {
  3862. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3863. },
  3864. plane: function ( optionalTarget ) {
  3865. var result = optionalTarget || new THREE.Plane();
  3866. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3867. },
  3868. barycoordFromPoint: function ( point, optionalTarget ) {
  3869. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3870. },
  3871. containsPoint: function ( point ) {
  3872. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3873. },
  3874. equals: function ( triangle ) {
  3875. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3876. },
  3877. clone: function () {
  3878. return new THREE.Triangle().copy( this );
  3879. }
  3880. };
  3881. /**
  3882. * @author mrdoob / http://mrdoob.com/
  3883. */
  3884. THREE.Vertex = function ( v ) {
  3885. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3886. return v;
  3887. };
  3888. /**
  3889. * @author mrdoob / http://mrdoob.com/
  3890. */
  3891. THREE.UV = function ( u, v ) {
  3892. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3893. return new THREE.Vector2( u, v );
  3894. };
  3895. /**
  3896. * @author alteredq / http://alteredqualia.com/
  3897. */
  3898. THREE.Clock = function ( autoStart ) {
  3899. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3900. this.startTime = 0;
  3901. this.oldTime = 0;
  3902. this.elapsedTime = 0;
  3903. this.running = false;
  3904. };
  3905. THREE.Clock.prototype = {
  3906. constructor: THREE.Clock,
  3907. start: function () {
  3908. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  3909. ? self.performance.now()
  3910. : Date.now();
  3911. this.oldTime = this.startTime;
  3912. this.running = true;
  3913. },
  3914. stop: function () {
  3915. this.getElapsedTime();
  3916. this.running = false;
  3917. },
  3918. getElapsedTime: function () {
  3919. this.getDelta();
  3920. return this.elapsedTime;
  3921. },
  3922. getDelta: function () {
  3923. var diff = 0;
  3924. if ( this.autoStart && ! this.running ) {
  3925. this.start();
  3926. }
  3927. if ( this.running ) {
  3928. var newTime = self.performance !== undefined && self.performance.now !== undefined
  3929. ? self.performance.now()
  3930. : Date.now();
  3931. diff = 0.001 * ( newTime - this.oldTime );
  3932. this.oldTime = newTime;
  3933. this.elapsedTime += diff;
  3934. }
  3935. return diff;
  3936. }
  3937. };
  3938. /**
  3939. * https://github.com/mrdoob/eventdispatcher.js/
  3940. */
  3941. THREE.EventDispatcher = function () {}
  3942. THREE.EventDispatcher.prototype = {
  3943. constructor: THREE.EventDispatcher,
  3944. apply: function ( object ) {
  3945. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  3946. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  3947. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  3948. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  3949. },
  3950. addEventListener: function ( type, listener ) {
  3951. if ( this._listeners === undefined ) this._listeners = {};
  3952. var listeners = this._listeners;
  3953. if ( listeners[ type ] === undefined ) {
  3954. listeners[ type ] = [];
  3955. }
  3956. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3957. listeners[ type ].push( listener );
  3958. }
  3959. },
  3960. hasEventListener: function ( type, listener ) {
  3961. if ( this._listeners === undefined ) return false;
  3962. var listeners = this._listeners;
  3963. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  3964. return true;
  3965. }
  3966. return false;
  3967. },
  3968. removeEventListener: function ( type, listener ) {
  3969. if ( this._listeners === undefined ) return;
  3970. var listeners = this._listeners;
  3971. var listenerArray = listeners[ type ];
  3972. if ( listenerArray !== undefined ) {
  3973. var index = listenerArray.indexOf( listener );
  3974. if ( index !== - 1 ) {
  3975. listenerArray.splice( index, 1 );
  3976. }
  3977. }
  3978. },
  3979. dispatchEvent: function () {
  3980. var array = [];
  3981. return function ( event ) {
  3982. if ( this._listeners === undefined ) return;
  3983. var listeners = this._listeners;
  3984. var listenerArray = listeners[ event.type ];
  3985. if ( listenerArray !== undefined ) {
  3986. event.target = this;
  3987. var length = listenerArray.length;
  3988. for ( var i = 0; i < length; i ++ ) {
  3989. array[ i ] = listenerArray[ i ];
  3990. }
  3991. for ( var i = 0; i < length; i ++ ) {
  3992. array[ i ].call( this, event );
  3993. }
  3994. }
  3995. };
  3996. }()
  3997. };
  3998. /**
  3999. * @author mrdoob / http://mrdoob.com/
  4000. * @author bhouston / http://exocortex.com/
  4001. * @author stephomi / http://stephaneginier.com/
  4002. */
  4003. ( function ( THREE ) {
  4004. THREE.Raycaster = function ( origin, direction, near, far ) {
  4005. this.ray = new THREE.Ray( origin, direction );
  4006. // direction is assumed to be normalized (for accurate distance calculations)
  4007. this.near = near || 0;
  4008. this.far = far || Infinity;
  4009. };
  4010. var sphere = new THREE.Sphere();
  4011. var localRay = new THREE.Ray();
  4012. var facePlane = new THREE.Plane();
  4013. var intersectPoint = new THREE.Vector3();
  4014. var matrixPosition = new THREE.Vector3();
  4015. var inverseMatrix = new THREE.Matrix4();
  4016. var descSort = function ( a, b ) {
  4017. return a.distance - b.distance;
  4018. };
  4019. var vA = new THREE.Vector3();
  4020. var vB = new THREE.Vector3();
  4021. var vC = new THREE.Vector3();
  4022. var intersectObject = function ( object, raycaster, intersects ) {
  4023. if ( object instanceof THREE.Sprite ) {
  4024. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4025. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  4026. if ( distance > object.scale.x ) {
  4027. return intersects;
  4028. }
  4029. intersects.push( {
  4030. distance: distance,
  4031. point: object.position,
  4032. face: null,
  4033. object: object
  4034. } );
  4035. } else if ( object instanceof THREE.LOD ) {
  4036. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4037. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  4038. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  4039. } else if ( object instanceof THREE.Mesh ) {
  4040. var geometry = object.geometry;
  4041. // Checking boundingSphere distance to ray
  4042. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4043. sphere.copy( geometry.boundingSphere );
  4044. sphere.applyMatrix4( object.matrixWorld );
  4045. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4046. return intersects;
  4047. }
  4048. // Check boundingBox before continuing
  4049. inverseMatrix.getInverse( object.matrixWorld );
  4050. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4051. if ( geometry.boundingBox !== null ) {
  4052. if ( localRay.isIntersectionBox( geometry.boundingBox ) === false ) {
  4053. return intersects;
  4054. }
  4055. }
  4056. if ( geometry instanceof THREE.BufferGeometry ) {
  4057. var material = object.material;
  4058. if ( material === undefined ) return intersects;
  4059. if ( geometry.dynamic === false ) return intersects;
  4060. var a, b, c;
  4061. var precision = raycaster.precision;
  4062. if ( geometry.attributes.index !== undefined ) {
  4063. var offsets = geometry.offsets;
  4064. var indices = geometry.attributes.index.array;
  4065. var positions = geometry.attributes.position.array;
  4066. var offLength = geometry.offsets.length;
  4067. var fl = geometry.attributes.index.array.length / 3;
  4068. for ( var oi = 0; oi < offLength; ++oi ) {
  4069. var start = offsets[ oi ].start;
  4070. var count = offsets[ oi ].count;
  4071. var index = offsets[ oi ].index;
  4072. for ( var i = start, il = start + count; i < il; i += 3 ) {
  4073. a = index + indices[ i ];
  4074. b = index + indices[ i + 1 ];
  4075. c = index + indices[ i + 2 ];
  4076. vA.set(
  4077. positions[ a * 3 ],
  4078. positions[ a * 3 + 1 ],
  4079. positions[ a * 3 + 2 ]
  4080. );
  4081. vB.set(
  4082. positions[ b * 3 ],
  4083. positions[ b * 3 + 1 ],
  4084. positions[ b * 3 + 2 ]
  4085. );
  4086. vC.set(
  4087. positions[ c * 3 ],
  4088. positions[ c * 3 + 1 ],
  4089. positions[ c * 3 + 2 ]
  4090. );
  4091. if ( material.side === THREE.BackSide ) {
  4092. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4093. } else {
  4094. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4095. }
  4096. if ( intersectionPoint === null ) continue;
  4097. intersectionPoint.applyMatrix4( object.matrixWorld );
  4098. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4099. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4100. intersects.push( {
  4101. distance: distance,
  4102. point: intersectionPoint,
  4103. face: null,
  4104. faceIndex: null,
  4105. object: object
  4106. } );
  4107. }
  4108. }
  4109. } else {
  4110. var offsets = geometry.offsets;
  4111. var positions = geometry.attributes.position.array;
  4112. var offLength = geometry.offsets.length;
  4113. var fl = geometry.attributes.position.array.length;
  4114. for ( var i = 0; i < fl; i += 3 ) {
  4115. a = i;
  4116. b = i + 1;
  4117. c = i + 2;
  4118. vA.set(
  4119. positions[ a * 3 ],
  4120. positions[ a * 3 + 1 ],
  4121. positions[ a * 3 + 2 ]
  4122. );
  4123. vB.set(
  4124. positions[ b * 3 ],
  4125. positions[ b * 3 + 1 ],
  4126. positions[ b * 3 + 2 ]
  4127. );
  4128. vC.set(
  4129. positions[ c * 3 ],
  4130. positions[ c * 3 + 1 ],
  4131. positions[ c * 3 + 2 ]
  4132. );
  4133. if ( material.side === THREE.BackSide ) {
  4134. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4135. } else {
  4136. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4137. }
  4138. if ( intersectionPoint === null ) continue;
  4139. intersectionPoint.applyMatrix4( object.matrixWorld );
  4140. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4141. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4142. intersects.push( {
  4143. distance: distance,
  4144. point: intersectionPoint,
  4145. face: null,
  4146. faceIndex: null,
  4147. object: object
  4148. } );
  4149. }
  4150. }
  4151. } else if ( geometry instanceof THREE.Geometry ) {
  4152. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4153. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  4154. var a, b, c, d;
  4155. var precision = raycaster.precision;
  4156. var vertices = geometry.vertices;
  4157. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  4158. var face = geometry.faces[ f ];
  4159. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  4160. if ( material === undefined ) continue;
  4161. a = vertices[ face.a ];
  4162. b = vertices[ face.b ];
  4163. c = vertices[ face.c ];
  4164. if ( material.side === THREE.BackSide ) {
  4165. var intersectionPoint = localRay.intersectTriangle( c, b, a, true );
  4166. } else {
  4167. var intersectionPoint = localRay.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
  4168. }
  4169. if ( intersectionPoint === null ) continue;
  4170. intersectionPoint.applyMatrix4( object.matrixWorld );
  4171. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4172. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4173. intersects.push( {
  4174. distance: distance,
  4175. point: intersectionPoint,
  4176. face: face,
  4177. faceIndex: f,
  4178. object: object
  4179. } );
  4180. }
  4181. }
  4182. } else if ( object instanceof THREE.Line ) {
  4183. var precision = raycaster.linePrecision;
  4184. var precisionSq = precision * precision;
  4185. var geometry = object.geometry;
  4186. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4187. // Checking boundingSphere distance to ray
  4188. sphere.copy( geometry.boundingSphere );
  4189. sphere.applyMatrix4( object.matrixWorld );
  4190. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4191. return intersects;
  4192. }
  4193. inverseMatrix.getInverse( object.matrixWorld );
  4194. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4195. /* if ( geometry instanceof THREE.BufferGeometry ) {
  4196. } else */ if ( geometry instanceof THREE.Geometry ) {
  4197. var vertices = geometry.vertices;
  4198. var nbVertices = vertices.length;
  4199. var interSegment = new THREE.Vector3();
  4200. var interRay = new THREE.Vector3();
  4201. var step = object.type === THREE.LineStrip ? 1 : 2;
  4202. for ( var i = 0; i < nbVertices - 1; i = i + step ) {
  4203. var distSq = localRay.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  4204. if ( distSq > precisionSq ) continue;
  4205. var distance = localRay.origin.distanceTo( interRay );
  4206. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  4207. intersects.push( {
  4208. distance: distance,
  4209. // What do we want? intersection point on the ray or on the segment??
  4210. // point: raycaster.ray.at( distance ),
  4211. point: interSegment.clone().applyMatrix4( object.matrixWorld ),
  4212. face: null,
  4213. faceIndex: null,
  4214. object: object
  4215. } );
  4216. }
  4217. }
  4218. }
  4219. };
  4220. var intersectDescendants = function ( object, raycaster, intersects ) {
  4221. var descendants = object.getDescendants();
  4222. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  4223. intersectObject( descendants[ i ], raycaster, intersects );
  4224. }
  4225. };
  4226. //
  4227. THREE.Raycaster.prototype.precision = 0.0001;
  4228. THREE.Raycaster.prototype.linePrecision = 1;
  4229. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  4230. this.ray.set( origin, direction );
  4231. // direction is assumed to be normalized (for accurate distance calculations)
  4232. };
  4233. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  4234. var intersects = [];
  4235. if ( recursive === true ) {
  4236. intersectDescendants( object, this, intersects );
  4237. }
  4238. intersectObject( object, this, intersects );
  4239. intersects.sort( descSort );
  4240. return intersects;
  4241. };
  4242. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  4243. var intersects = [];
  4244. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4245. intersectObject( objects[ i ], this, intersects );
  4246. if ( recursive === true ) {
  4247. intersectDescendants( objects[ i ], this, intersects );
  4248. }
  4249. }
  4250. intersects.sort( descSort );
  4251. return intersects;
  4252. };
  4253. }( THREE ) );
  4254. /**
  4255. * @author mrdoob / http://mrdoob.com/
  4256. * @author mikael emtinger / http://gomo.se/
  4257. * @author alteredq / http://alteredqualia.com/
  4258. * @author WestLangley / http://github.com/WestLangley
  4259. */
  4260. THREE.Object3D = function () {
  4261. this.id = THREE.Object3DIdCount ++;
  4262. this.uuid = THREE.Math.generateUUID();
  4263. this.name = '';
  4264. this.parent = undefined;
  4265. this.children = [];
  4266. this.up = new THREE.Vector3( 0, 1, 0 );
  4267. this.position = new THREE.Vector3();
  4268. this._rotation = new THREE.Euler();
  4269. this._quaternion = new THREE.Quaternion();
  4270. this.scale = new THREE.Vector3( 1, 1, 1 );
  4271. // keep rotation and quaternion in sync
  4272. this._rotation._quaternion = this.quaternion;
  4273. this._quaternion._euler = this.rotation;
  4274. this.renderDepth = null;
  4275. this.rotationAutoUpdate = true;
  4276. this.matrix = new THREE.Matrix4();
  4277. this.matrixWorld = new THREE.Matrix4();
  4278. this.matrixAutoUpdate = true;
  4279. this.matrixWorldNeedsUpdate = true;
  4280. this.visible = true;
  4281. this.castShadow = false;
  4282. this.receiveShadow = false;
  4283. this.frustumCulled = true;
  4284. this.userData = {};
  4285. };
  4286. THREE.Object3D.prototype = {
  4287. constructor: THREE.Object3D,
  4288. get rotation () {
  4289. return this._rotation;
  4290. },
  4291. set rotation ( value ) {
  4292. this._rotation = value;
  4293. this._rotation._quaternion = this._quaternion;
  4294. this._quaternion._euler = this._rotation;
  4295. this._rotation._updateQuaternion();
  4296. },
  4297. get quaternion () {
  4298. return this._quaternion;
  4299. },
  4300. set quaternion ( value ) {
  4301. this._quaternion = value;
  4302. this._quaternion._euler = this._rotation;
  4303. this._rotation._quaternion = this._quaternion;
  4304. this._quaternion._updateEuler();
  4305. },
  4306. get eulerOrder () {
  4307. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4308. return this.rotation.order;
  4309. },
  4310. set eulerOrder ( value ) {
  4311. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4312. this.rotation.order = value;
  4313. },
  4314. get useQuaternion () {
  4315. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4316. },
  4317. set useQuaternion ( value ) {
  4318. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4319. },
  4320. applyMatrix: function () {
  4321. var m1 = new THREE.Matrix4();
  4322. return function ( matrix ) {
  4323. this.matrix.multiplyMatrices( matrix, this.matrix );
  4324. this.position.setFromMatrixPosition( this.matrix );
  4325. this.scale.setFromMatrixScale( this.matrix );
  4326. m1.extractRotation( this.matrix );
  4327. this.quaternion.setFromRotationMatrix( m1 );
  4328. }
  4329. }(),
  4330. setRotationFromAxisAngle: function ( axis, angle ) {
  4331. // assumes axis is normalized
  4332. this.quaternion.setFromAxisAngle( axis, angle );
  4333. },
  4334. setRotationFromEuler: function ( euler ) {
  4335. this.quaternion.setFromEuler( euler, true );
  4336. },
  4337. setRotationFromMatrix: function ( m ) {
  4338. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4339. this.quaternion.setFromRotationMatrix( m );
  4340. },
  4341. setRotationFromQuaternion: function ( q ) {
  4342. // assumes q is normalized
  4343. this.quaternion.copy( q );
  4344. },
  4345. rotateOnAxis: function() {
  4346. // rotate object on axis in object space
  4347. // axis is assumed to be normalized
  4348. var q1 = new THREE.Quaternion();
  4349. return function ( axis, angle ) {
  4350. q1.setFromAxisAngle( axis, angle );
  4351. this.quaternion.multiply( q1 );
  4352. return this;
  4353. }
  4354. }(),
  4355. rotateX: function () {
  4356. var v1 = new THREE.Vector3( 1, 0, 0 );
  4357. return function ( angle ) {
  4358. return this.rotateOnAxis( v1, angle );
  4359. };
  4360. }(),
  4361. rotateY: function () {
  4362. var v1 = new THREE.Vector3( 0, 1, 0 );
  4363. return function ( angle ) {
  4364. return this.rotateOnAxis( v1, angle );
  4365. };
  4366. }(),
  4367. rotateZ: function () {
  4368. var v1 = new THREE.Vector3( 0, 0, 1 );
  4369. return function ( angle ) {
  4370. return this.rotateOnAxis( v1, angle );
  4371. };
  4372. }(),
  4373. translateOnAxis: function () {
  4374. // translate object by distance along axis in object space
  4375. // axis is assumed to be normalized
  4376. var v1 = new THREE.Vector3();
  4377. return function ( axis, distance ) {
  4378. v1.copy( axis );
  4379. v1.applyQuaternion( this.quaternion );
  4380. this.position.add( v1.multiplyScalar( distance ) );
  4381. return this;
  4382. }
  4383. }(),
  4384. translate: function ( distance, axis ) {
  4385. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  4386. return this.translateOnAxis( axis, distance );
  4387. },
  4388. translateX: function () {
  4389. var v1 = new THREE.Vector3( 1, 0, 0 );
  4390. return function ( distance ) {
  4391. return this.translateOnAxis( v1, distance );
  4392. };
  4393. }(),
  4394. translateY: function () {
  4395. var v1 = new THREE.Vector3( 0, 1, 0 );
  4396. return function ( distance ) {
  4397. return this.translateOnAxis( v1, distance );
  4398. };
  4399. }(),
  4400. translateZ: function () {
  4401. var v1 = new THREE.Vector3( 0, 0, 1 );
  4402. return function ( distance ) {
  4403. return this.translateOnAxis( v1, distance );
  4404. };
  4405. }(),
  4406. localToWorld: function ( vector ) {
  4407. return vector.applyMatrix4( this.matrixWorld );
  4408. },
  4409. worldToLocal: function () {
  4410. var m1 = new THREE.Matrix4();
  4411. return function ( vector ) {
  4412. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4413. };
  4414. }(),
  4415. lookAt: function () {
  4416. // This routine does not support objects with rotated and/or translated parent(s)
  4417. var m1 = new THREE.Matrix4();
  4418. return function ( vector ) {
  4419. m1.lookAt( vector, this.position, this.up );
  4420. this.quaternion.setFromRotationMatrix( m1 );
  4421. };
  4422. }(),
  4423. add: function ( object ) {
  4424. if ( object === this ) {
  4425. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  4426. return;
  4427. }
  4428. if ( object instanceof THREE.Object3D ) {
  4429. if ( object.parent !== undefined ) {
  4430. object.parent.remove( object );
  4431. }
  4432. object.parent = this;
  4433. object.dispatchEvent( { type: 'added' } );
  4434. this.children.push( object );
  4435. // add to scene
  4436. var scene = this;
  4437. while ( scene.parent !== undefined ) {
  4438. scene = scene.parent;
  4439. }
  4440. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4441. scene.__addObject( object );
  4442. }
  4443. }
  4444. },
  4445. remove: function ( object ) {
  4446. var index = this.children.indexOf( object );
  4447. if ( index !== - 1 ) {
  4448. object.parent = undefined;
  4449. object.dispatchEvent( { type: 'removed' } );
  4450. this.children.splice( index, 1 );
  4451. // remove from scene
  4452. var scene = this;
  4453. while ( scene.parent !== undefined ) {
  4454. scene = scene.parent;
  4455. }
  4456. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4457. scene.__removeObject( object );
  4458. }
  4459. }
  4460. },
  4461. traverse: function ( callback ) {
  4462. callback( this );
  4463. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4464. this.children[ i ].traverse( callback );
  4465. }
  4466. },
  4467. getObjectById: function ( id, recursive ) {
  4468. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4469. var child = this.children[ i ];
  4470. if ( child.id === id ) {
  4471. return child;
  4472. }
  4473. if ( recursive === true ) {
  4474. child = child.getObjectById( id, recursive );
  4475. if ( child !== undefined ) {
  4476. return child;
  4477. }
  4478. }
  4479. }
  4480. return undefined;
  4481. },
  4482. getObjectByName: function ( name, recursive ) {
  4483. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4484. var child = this.children[ i ];
  4485. if ( child.name === name ) {
  4486. return child;
  4487. }
  4488. if ( recursive === true ) {
  4489. child = child.getObjectByName( name, recursive );
  4490. if ( child !== undefined ) {
  4491. return child;
  4492. }
  4493. }
  4494. }
  4495. return undefined;
  4496. },
  4497. getChildByName: function ( name, recursive ) {
  4498. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  4499. return this.getObjectByName( name, recursive );
  4500. },
  4501. getDescendants: function ( array ) {
  4502. if ( array === undefined ) array = [];
  4503. Array.prototype.push.apply( array, this.children );
  4504. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4505. this.children[ i ].getDescendants( array );
  4506. }
  4507. return array;
  4508. },
  4509. updateMatrix: function () {
  4510. this.matrix.compose( this.position, this.quaternion, this.scale );
  4511. this.matrixWorldNeedsUpdate = true;
  4512. },
  4513. updateMatrixWorld: function ( force ) {
  4514. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4515. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4516. if ( this.parent === undefined ) {
  4517. this.matrixWorld.copy( this.matrix );
  4518. } else {
  4519. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4520. }
  4521. this.matrixWorldNeedsUpdate = false;
  4522. force = true;
  4523. }
  4524. // update children
  4525. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4526. this.children[ i ].updateMatrixWorld( force );
  4527. }
  4528. },
  4529. clone: function ( object, recursive ) {
  4530. if ( object === undefined ) object = new THREE.Object3D();
  4531. if ( recursive === undefined ) recursive = true;
  4532. object.name = this.name;
  4533. object.up.copy( this.up );
  4534. object.position.copy( this.position );
  4535. object.quaternion.copy( this.quaternion );
  4536. object.scale.copy( this.scale );
  4537. object.renderDepth = this.renderDepth;
  4538. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4539. object.matrix.copy( this.matrix );
  4540. object.matrixWorld.copy( this.matrixWorld );
  4541. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4542. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4543. object.visible = this.visible;
  4544. object.castShadow = this.castShadow;
  4545. object.receiveShadow = this.receiveShadow;
  4546. object.frustumCulled = this.frustumCulled;
  4547. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4548. if ( recursive === true ) {
  4549. for ( var i = 0; i < this.children.length; i ++ ) {
  4550. var child = this.children[ i ];
  4551. object.add( child.clone() );
  4552. }
  4553. }
  4554. return object;
  4555. }
  4556. };
  4557. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4558. THREE.Object3DIdCount = 0;
  4559. /**
  4560. * @author mrdoob / http://mrdoob.com/
  4561. * @author supereggbert / http://www.paulbrunt.co.uk/
  4562. * @author julianwa / https://github.com/julianwa
  4563. */
  4564. THREE.Projector = function () {
  4565. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4566. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4567. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  4568. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4569. _sprite, _spriteCount, _spritePool = [], _spritePoolLength = 0,
  4570. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  4571. _vector3 = new THREE.Vector3(),
  4572. _vector4 = new THREE.Vector4(),
  4573. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4574. _boundingBox = new THREE.Box3(),
  4575. _points3 = new Array( 3 ),
  4576. _points4 = new Array( 4 ),
  4577. _viewMatrix = new THREE.Matrix4(),
  4578. _viewProjectionMatrix = new THREE.Matrix4(),
  4579. _modelMatrix,
  4580. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4581. _normalMatrix = new THREE.Matrix3(),
  4582. _normalViewMatrix = new THREE.Matrix3(),
  4583. _centroid = new THREE.Vector3(),
  4584. _frustum = new THREE.Frustum(),
  4585. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4586. _clippedVertex2PositionScreen = new THREE.Vector4();
  4587. this.projectVector = function ( vector, camera ) {
  4588. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4589. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4590. return vector.applyProjection( _viewProjectionMatrix );
  4591. };
  4592. this.unprojectVector = function ( vector, camera ) {
  4593. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4594. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  4595. return vector.applyProjection( _viewProjectionMatrix );
  4596. };
  4597. this.pickingRay = function ( vector, camera ) {
  4598. // set two vectors with opposing z values
  4599. vector.z = -1.0;
  4600. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4601. this.unprojectVector( vector, camera );
  4602. this.unprojectVector( end, camera );
  4603. // find direction from vector to end
  4604. end.sub( vector ).normalize();
  4605. return new THREE.Raycaster( vector, end );
  4606. };
  4607. var getObject = function ( object ) {
  4608. _object = getNextObjectInPool();
  4609. _object.id = object.id;
  4610. _object.object = object;
  4611. if ( object.renderDepth !== null ) {
  4612. _object.z = object.renderDepth;
  4613. } else {
  4614. _vector3.setFromMatrixPosition( object.matrixWorld );
  4615. _vector3.applyProjection( _viewProjectionMatrix );
  4616. _object.z = _vector3.z;
  4617. }
  4618. return _object;
  4619. };
  4620. var projectObject = function ( object ) {
  4621. if ( object.visible === false ) return;
  4622. if ( object instanceof THREE.Light ) {
  4623. _renderData.lights.push( object );
  4624. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  4625. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4626. _renderData.objects.push( getObject( object ) );
  4627. }
  4628. } else if ( object instanceof THREE.Sprite ) {
  4629. _renderData.sprites.push( getObject( object ) );
  4630. }
  4631. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4632. projectObject( object.children[ i ] );
  4633. }
  4634. };
  4635. var projectGraph = function ( root, sortObjects ) {
  4636. _objectCount = 0;
  4637. _renderData.objects.length = 0;
  4638. _renderData.sprites.length = 0;
  4639. _renderData.lights.length = 0;
  4640. projectObject( root );
  4641. if ( sortObjects === true ) {
  4642. _renderData.objects.sort( painterSort );
  4643. }
  4644. };
  4645. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4646. var visible = false,
  4647. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  4648. geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  4649. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  4650. _face3Count = 0;
  4651. _lineCount = 0;
  4652. _spriteCount = 0;
  4653. _renderData.elements.length = 0;
  4654. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4655. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4656. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4657. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4658. _normalViewMatrix.getNormalMatrix( _viewMatrix );
  4659. _frustum.setFromMatrix( _viewProjectionMatrix );
  4660. projectGraph( scene, sortObjects );
  4661. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4662. object = _renderData.objects[ o ].object;
  4663. _modelMatrix = object.matrixWorld;
  4664. _vertexCount = 0;
  4665. if ( object instanceof THREE.Mesh ) {
  4666. geometry = object.geometry;
  4667. vertices = geometry.vertices;
  4668. faces = geometry.faces;
  4669. faceVertexUvs = geometry.faceVertexUvs;
  4670. _normalMatrix.getNormalMatrix( _modelMatrix );
  4671. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4672. objectMaterials = isFaceMaterial === true ? object.material : null;
  4673. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  4674. _vertex = getNextVertexInPool();
  4675. _vertex.positionWorld.copy( vertices[ v ] ).applyMatrix4( _modelMatrix );
  4676. _vertex.positionScreen.copy( _vertex.positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4677. var invW = 1 / _vertex.positionScreen.w;
  4678. _vertex.positionScreen.x *= invW;
  4679. _vertex.positionScreen.y *= invW;
  4680. _vertex.positionScreen.z *= invW;
  4681. _vertex.visible = ! ( _vertex.positionScreen.x < -1 || _vertex.positionScreen.x > 1 ||
  4682. _vertex.positionScreen.y < -1 || _vertex.positionScreen.y > 1 ||
  4683. _vertex.positionScreen.z < -1 || _vertex.positionScreen.z > 1 );
  4684. }
  4685. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  4686. face = faces[ f ];
  4687. var material = isFaceMaterial === true
  4688. ? objectMaterials.materials[ face.materialIndex ]
  4689. : object.material;
  4690. if ( material === undefined ) continue;
  4691. var side = material.side;
  4692. v1 = _vertexPool[ face.a ];
  4693. v2 = _vertexPool[ face.b ];
  4694. v3 = _vertexPool[ face.c ];
  4695. _points3[ 0 ] = v1.positionScreen;
  4696. _points3[ 1 ] = v2.positionScreen;
  4697. _points3[ 2 ] = v3.positionScreen;
  4698. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4699. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4700. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) *
  4701. ( v2.positionScreen.y - v1.positionScreen.y ) -
  4702. ( v3.positionScreen.y - v1.positionScreen.y ) *
  4703. ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4704. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4705. _face = getNextFace3InPool();
  4706. _face.id = object.id;
  4707. _face.v1.copy( v1 );
  4708. _face.v2.copy( v2 );
  4709. _face.v3.copy( v3 );
  4710. } else {
  4711. continue;
  4712. }
  4713. } else {
  4714. continue;
  4715. }
  4716. _face.normalModel.copy( face.normal );
  4717. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4718. _face.normalModel.negate();
  4719. }
  4720. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4721. _face.normalModelView.copy( _face.normalModel ).applyMatrix3( _normalViewMatrix );
  4722. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4723. faceVertexNormals = face.vertexNormals;
  4724. for ( n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) {
  4725. var normalModel = _face.vertexNormalsModel[ n ];
  4726. normalModel.copy( faceVertexNormals[ n ] );
  4727. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4728. normalModel.negate();
  4729. }
  4730. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4731. var normalModelView = _face.vertexNormalsModelView[ n ];
  4732. normalModelView.copy( normalModel ).applyMatrix3( _normalViewMatrix );
  4733. }
  4734. _face.vertexNormalsLength = faceVertexNormals.length;
  4735. for ( c = 0, cl = Math.min( faceVertexUvs.length, 3 ); c < cl; c ++ ) {
  4736. uvs = faceVertexUvs[ c ][ f ];
  4737. if ( uvs === undefined ) continue;
  4738. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  4739. _face.uvs[ c ][ u ] = uvs[ u ];
  4740. }
  4741. }
  4742. _face.color = face.color;
  4743. _face.material = material;
  4744. _centroid.copy( _face.centroidModel ).applyProjection( _viewProjectionMatrix );
  4745. _face.z = _centroid.z;
  4746. _renderData.elements.push( _face );
  4747. }
  4748. } else if ( object instanceof THREE.Line ) {
  4749. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4750. vertices = object.geometry.vertices;
  4751. v1 = getNextVertexInPool();
  4752. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4753. // Handle LineStrip and LinePieces
  4754. var step = object.type === THREE.LinePieces ? 2 : 1;
  4755. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  4756. v1 = getNextVertexInPool();
  4757. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4758. if ( ( v + 1 ) % step > 0 ) continue;
  4759. v2 = _vertexPool[ _vertexCount - 2 ];
  4760. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4761. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4762. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4763. // Perform the perspective divide
  4764. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4765. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4766. _line = getNextLineInPool();
  4767. _line.id = object.id;
  4768. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4769. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4770. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4771. _line.material = object.material;
  4772. if ( object.material.vertexColors === THREE.VertexColors ) {
  4773. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  4774. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  4775. }
  4776. _renderData.elements.push( _line );
  4777. }
  4778. }
  4779. }
  4780. }
  4781. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  4782. object = _renderData.sprites[ o ].object;
  4783. _modelMatrix = object.matrixWorld;
  4784. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4785. _vector4.applyMatrix4( _viewProjectionMatrix );
  4786. var invW = 1 / _vector4.w;
  4787. _vector4.z *= invW;
  4788. if ( _vector4.z >= -1 && _vector4.z <= 1 ) {
  4789. _sprite = getNextSpriteInPool();
  4790. _sprite.id = object.id;
  4791. _sprite.x = _vector4.x * invW;
  4792. _sprite.y = _vector4.y * invW;
  4793. _sprite.z = _vector4.z;
  4794. _sprite.object = object;
  4795. _sprite.rotation = object.rotation;
  4796. _sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4797. _sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4798. _sprite.material = object.material;
  4799. _renderData.elements.push( _sprite );
  4800. }
  4801. }
  4802. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4803. return _renderData;
  4804. };
  4805. // Pools
  4806. function getNextObjectInPool() {
  4807. if ( _objectCount === _objectPoolLength ) {
  4808. var object = new THREE.RenderableObject();
  4809. _objectPool.push( object );
  4810. _objectPoolLength ++;
  4811. _objectCount ++;
  4812. return object;
  4813. }
  4814. return _objectPool[ _objectCount ++ ];
  4815. }
  4816. function getNextVertexInPool() {
  4817. if ( _vertexCount === _vertexPoolLength ) {
  4818. var vertex = new THREE.RenderableVertex();
  4819. _vertexPool.push( vertex );
  4820. _vertexPoolLength ++;
  4821. _vertexCount ++;
  4822. return vertex;
  4823. }
  4824. return _vertexPool[ _vertexCount ++ ];
  4825. }
  4826. function getNextFace3InPool() {
  4827. if ( _face3Count === _face3PoolLength ) {
  4828. var face = new THREE.RenderableFace3();
  4829. _face3Pool.push( face );
  4830. _face3PoolLength ++;
  4831. _face3Count ++;
  4832. return face;
  4833. }
  4834. return _face3Pool[ _face3Count ++ ];
  4835. }
  4836. function getNextLineInPool() {
  4837. if ( _lineCount === _linePoolLength ) {
  4838. var line = new THREE.RenderableLine();
  4839. _linePool.push( line );
  4840. _linePoolLength ++;
  4841. _lineCount ++
  4842. return line;
  4843. }
  4844. return _linePool[ _lineCount ++ ];
  4845. }
  4846. function getNextSpriteInPool() {
  4847. if ( _spriteCount === _spritePoolLength ) {
  4848. var sprite = new THREE.RenderableSprite();
  4849. _spritePool.push( sprite );
  4850. _spritePoolLength ++;
  4851. _spriteCount ++
  4852. return sprite;
  4853. }
  4854. return _spritePool[ _spriteCount ++ ];
  4855. }
  4856. //
  4857. function painterSort( a, b ) {
  4858. if ( a.z !== b.z ) {
  4859. return b.z - a.z;
  4860. } else if ( a.id !== b.id ) {
  4861. return a.id - b.id;
  4862. } else {
  4863. return 0;
  4864. }
  4865. }
  4866. function clipLine( s1, s2 ) {
  4867. var alpha1 = 0, alpha2 = 1,
  4868. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4869. // Z = -1 and Z = +1, respectively.
  4870. bc1near = s1.z + s1.w,
  4871. bc2near = s2.z + s2.w,
  4872. bc1far = - s1.z + s1.w,
  4873. bc2far = - s2.z + s2.w;
  4874. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4875. // Both vertices lie entirely within all clip planes.
  4876. return true;
  4877. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4878. // Both vertices lie entirely outside one of the clip planes.
  4879. return false;
  4880. } else {
  4881. // The line segment spans at least one clip plane.
  4882. if ( bc1near < 0 ) {
  4883. // v1 lies outside the near plane, v2 inside
  4884. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4885. } else if ( bc2near < 0 ) {
  4886. // v2 lies outside the near plane, v1 inside
  4887. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4888. }
  4889. if ( bc1far < 0 ) {
  4890. // v1 lies outside the far plane, v2 inside
  4891. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4892. } else if ( bc2far < 0 ) {
  4893. // v2 lies outside the far plane, v2 inside
  4894. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4895. }
  4896. if ( alpha2 < alpha1 ) {
  4897. // The line segment spans two boundaries, but is outside both of them.
  4898. // (This can't happen when we're only clipping against just near/far but good
  4899. // to leave the check here for future usage if other clip planes are added.)
  4900. return false;
  4901. } else {
  4902. // Update the s1 and s2 vertices to match the clipped line segment.
  4903. s1.lerp( s2, alpha1 );
  4904. s2.lerp( s1, 1 - alpha2 );
  4905. return true;
  4906. }
  4907. }
  4908. }
  4909. };
  4910. /**
  4911. * @author mrdoob / http://mrdoob.com/
  4912. * @author alteredq / http://alteredqualia.com/
  4913. */
  4914. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4915. this.a = a;
  4916. this.b = b;
  4917. this.c = c;
  4918. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4919. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4920. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4921. this.vertexColors = color instanceof Array ? color : [];
  4922. this.vertexTangents = [];
  4923. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4924. this.centroid = new THREE.Vector3();
  4925. };
  4926. THREE.Face3.prototype = {
  4927. constructor: THREE.Face3,
  4928. clone: function () {
  4929. var face = new THREE.Face3( this.a, this.b, this.c );
  4930. face.normal.copy( this.normal );
  4931. face.color.copy( this.color );
  4932. face.centroid.copy( this.centroid );
  4933. face.materialIndex = this.materialIndex;
  4934. var i, il;
  4935. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4936. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4937. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4938. return face;
  4939. }
  4940. };
  4941. /**
  4942. * @author mrdoob / http://mrdoob.com/
  4943. */
  4944. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4945. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.')
  4946. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  4947. };
  4948. /**
  4949. * @author mrdoob / http://mrdoob.com/
  4950. * @author kile / http://kile.stravaganza.org/
  4951. * @author alteredq / http://alteredqualia.com/
  4952. * @author mikael emtinger / http://gomo.se/
  4953. * @author zz85 / http://www.lab4games.net/zz85/blog
  4954. * @author bhouston / http://exocortex.com
  4955. */
  4956. THREE.Geometry = function () {
  4957. this.id = THREE.GeometryIdCount ++;
  4958. this.uuid = THREE.Math.generateUUID();
  4959. this.name = '';
  4960. this.vertices = [];
  4961. this.colors = []; // one-to-one vertex colors, used in ParticleSystem and Line
  4962. this.faces = [];
  4963. this.faceVertexUvs = [[]];
  4964. this.morphTargets = [];
  4965. this.morphColors = [];
  4966. this.morphNormals = [];
  4967. this.skinWeights = [];
  4968. this.skinIndices = [];
  4969. this.lineDistances = [];
  4970. this.boundingBox = null;
  4971. this.boundingSphere = null;
  4972. this.hasTangents = false;
  4973. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4974. // update flags
  4975. this.verticesNeedUpdate = false;
  4976. this.elementsNeedUpdate = false;
  4977. this.uvsNeedUpdate = false;
  4978. this.normalsNeedUpdate = false;
  4979. this.tangentsNeedUpdate = false;
  4980. this.colorsNeedUpdate = false;
  4981. this.lineDistancesNeedUpdate = false;
  4982. this.buffersNeedUpdate = false;
  4983. };
  4984. THREE.Geometry.prototype = {
  4985. constructor: THREE.Geometry,
  4986. applyMatrix: function ( matrix ) {
  4987. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  4988. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4989. var vertex = this.vertices[ i ];
  4990. vertex.applyMatrix4( matrix );
  4991. }
  4992. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4993. var face = this.faces[ i ];
  4994. face.normal.applyMatrix3( normalMatrix ).normalize();
  4995. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4996. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4997. }
  4998. face.centroid.applyMatrix4( matrix );
  4999. }
  5000. if ( this.boundingBox instanceof THREE.Box3 ) {
  5001. this.computeBoundingBox();
  5002. }
  5003. if ( this.boundingSphere instanceof THREE.Sphere ) {
  5004. this.computeBoundingSphere();
  5005. }
  5006. },
  5007. computeCentroids: function () {
  5008. var f, fl, face;
  5009. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5010. face = this.faces[ f ];
  5011. face.centroid.set( 0, 0, 0 );
  5012. face.centroid.add( this.vertices[ face.a ] );
  5013. face.centroid.add( this.vertices[ face.b ] );
  5014. face.centroid.add( this.vertices[ face.c ] );
  5015. face.centroid.divideScalar( 3 );
  5016. }
  5017. },
  5018. computeFaceNormals: function () {
  5019. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5020. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5021. var face = this.faces[ f ];
  5022. var vA = this.vertices[ face.a ];
  5023. var vB = this.vertices[ face.b ];
  5024. var vC = this.vertices[ face.c ];
  5025. cb.subVectors( vC, vB );
  5026. ab.subVectors( vA, vB );
  5027. cb.cross( ab );
  5028. cb.normalize();
  5029. face.normal.copy( cb );
  5030. }
  5031. },
  5032. computeVertexNormals: function ( areaWeighted ) {
  5033. var v, vl, f, fl, face, vertices;
  5034. vertices = new Array( this.vertices.length );
  5035. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5036. vertices[ v ] = new THREE.Vector3();
  5037. }
  5038. if ( areaWeighted ) {
  5039. // vertex normals weighted by triangle areas
  5040. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5041. var vA, vB, vC, vD;
  5042. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  5043. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  5044. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5045. face = this.faces[ f ];
  5046. vA = this.vertices[ face.a ];
  5047. vB = this.vertices[ face.b ];
  5048. vC = this.vertices[ face.c ];
  5049. cb.subVectors( vC, vB );
  5050. ab.subVectors( vA, vB );
  5051. cb.cross( ab );
  5052. vertices[ face.a ].add( cb );
  5053. vertices[ face.b ].add( cb );
  5054. vertices[ face.c ].add( cb );
  5055. }
  5056. } else {
  5057. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5058. face = this.faces[ f ];
  5059. vertices[ face.a ].add( face.normal );
  5060. vertices[ face.b ].add( face.normal );
  5061. vertices[ face.c ].add( face.normal );
  5062. }
  5063. }
  5064. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5065. vertices[ v ].normalize();
  5066. }
  5067. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5068. face = this.faces[ f ];
  5069. face.vertexNormals[ 0 ] = vertices[ face.a ].clone();
  5070. face.vertexNormals[ 1 ] = vertices[ face.b ].clone();
  5071. face.vertexNormals[ 2 ] = vertices[ face.c ].clone();
  5072. }
  5073. },
  5074. computeMorphNormals: function () {
  5075. var i, il, f, fl, face;
  5076. // save original normals
  5077. // - create temp variables on first access
  5078. // otherwise just copy (for faster repeated calls)
  5079. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5080. face = this.faces[ f ];
  5081. if ( ! face.__originalFaceNormal ) {
  5082. face.__originalFaceNormal = face.normal.clone();
  5083. } else {
  5084. face.__originalFaceNormal.copy( face.normal );
  5085. }
  5086. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5087. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5088. if ( ! face.__originalVertexNormals[ i ] ) {
  5089. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5090. } else {
  5091. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  5092. }
  5093. }
  5094. }
  5095. // use temp geometry to compute face and vertex normals for each morph
  5096. var tmpGeo = new THREE.Geometry();
  5097. tmpGeo.faces = this.faces;
  5098. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  5099. // create on first access
  5100. if ( ! this.morphNormals[ i ] ) {
  5101. this.morphNormals[ i ] = {};
  5102. this.morphNormals[ i ].faceNormals = [];
  5103. this.morphNormals[ i ].vertexNormals = [];
  5104. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  5105. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  5106. var faceNormal, vertexNormals;
  5107. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5108. face = this.faces[ f ];
  5109. faceNormal = new THREE.Vector3();
  5110. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5111. dstNormalsFace.push( faceNormal );
  5112. dstNormalsVertex.push( vertexNormals );
  5113. }
  5114. }
  5115. var morphNormals = this.morphNormals[ i ];
  5116. // set vertices to morph target
  5117. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5118. // compute morph normals
  5119. tmpGeo.computeFaceNormals();
  5120. tmpGeo.computeVertexNormals();
  5121. // store morph normals
  5122. var faceNormal, vertexNormals;
  5123. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5124. face = this.faces[ f ];
  5125. faceNormal = morphNormals.faceNormals[ f ];
  5126. vertexNormals = morphNormals.vertexNormals[ f ];
  5127. faceNormal.copy( face.normal );
  5128. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5129. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5130. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5131. }
  5132. }
  5133. // restore original normals
  5134. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5135. face = this.faces[ f ];
  5136. face.normal = face.__originalFaceNormal;
  5137. face.vertexNormals = face.__originalVertexNormals;
  5138. }
  5139. },
  5140. computeTangents: function () {
  5141. // based on http://www.terathon.com/code/tangent.html
  5142. // tangents go to vertices
  5143. var f, fl, v, vl, i, il, vertexIndex,
  5144. face, uv, vA, vB, vC, uvA, uvB, uvC,
  5145. x1, x2, y1, y2, z1, z2,
  5146. s1, s2, t1, t2, r, t, test,
  5147. tan1 = [], tan2 = [],
  5148. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  5149. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  5150. n = new THREE.Vector3(), w;
  5151. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5152. tan1[ v ] = new THREE.Vector3();
  5153. tan2[ v ] = new THREE.Vector3();
  5154. }
  5155. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  5156. vA = context.vertices[ a ];
  5157. vB = context.vertices[ b ];
  5158. vC = context.vertices[ c ];
  5159. uvA = uv[ ua ];
  5160. uvB = uv[ ub ];
  5161. uvC = uv[ uc ];
  5162. x1 = vB.x - vA.x;
  5163. x2 = vC.x - vA.x;
  5164. y1 = vB.y - vA.y;
  5165. y2 = vC.y - vA.y;
  5166. z1 = vB.z - vA.z;
  5167. z2 = vC.z - vA.z;
  5168. s1 = uvB.x - uvA.x;
  5169. s2 = uvC.x - uvA.x;
  5170. t1 = uvB.y - uvA.y;
  5171. t2 = uvC.y - uvA.y;
  5172. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5173. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  5174. ( t2 * y1 - t1 * y2 ) * r,
  5175. ( t2 * z1 - t1 * z2 ) * r );
  5176. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  5177. ( s1 * y2 - s2 * y1 ) * r,
  5178. ( s1 * z2 - s2 * z1 ) * r );
  5179. tan1[ a ].add( sdir );
  5180. tan1[ b ].add( sdir );
  5181. tan1[ c ].add( sdir );
  5182. tan2[ a ].add( tdir );
  5183. tan2[ b ].add( tdir );
  5184. tan2[ c ].add( tdir );
  5185. }
  5186. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5187. face = this.faces[ f ];
  5188. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  5189. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  5190. }
  5191. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  5192. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5193. face = this.faces[ f ];
  5194. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i++ ) {
  5195. n.copy( face.vertexNormals[ i ] );
  5196. vertexIndex = face[ faceIndex[ i ] ];
  5197. t = tan1[ vertexIndex ];
  5198. // Gram-Schmidt orthogonalize
  5199. tmp.copy( t );
  5200. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5201. // Calculate handedness
  5202. tmp2.crossVectors( face.vertexNormals[ i ], t );
  5203. test = tmp2.dot( tan2[ vertexIndex ] );
  5204. w = (test < 0.0) ? -1.0 : 1.0;
  5205. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  5206. }
  5207. }
  5208. this.hasTangents = true;
  5209. },
  5210. computeLineDistances: function ( ) {
  5211. var d = 0;
  5212. var vertices = this.vertices;
  5213. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5214. if ( i > 0 ) {
  5215. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  5216. }
  5217. this.lineDistances[ i ] = d;
  5218. }
  5219. },
  5220. computeBoundingBox: function () {
  5221. if ( this.boundingBox === null ) {
  5222. this.boundingBox = new THREE.Box3();
  5223. }
  5224. this.boundingBox.setFromPoints( this.vertices );
  5225. },
  5226. computeBoundingSphere: function () {
  5227. if ( this.boundingSphere === null ) {
  5228. this.boundingSphere = new THREE.Sphere();
  5229. }
  5230. this.boundingSphere.setFromPoints( this.vertices );
  5231. },
  5232. /*
  5233. * Checks for duplicate vertices with hashmap.
  5234. * Duplicated vertices are removed
  5235. * and faces' vertices are updated.
  5236. */
  5237. mergeVertices: function () {
  5238. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  5239. var unique = [], changes = [];
  5240. var v, key;
  5241. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  5242. var precision = Math.pow( 10, precisionPoints );
  5243. var i,il, face;
  5244. var indices, k, j, jl, u;
  5245. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  5246. v = this.vertices[ i ];
  5247. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  5248. if ( verticesMap[ key ] === undefined ) {
  5249. verticesMap[ key ] = i;
  5250. unique.push( this.vertices[ i ] );
  5251. changes[ i ] = unique.length - 1;
  5252. } else {
  5253. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  5254. changes[ i ] = changes[ verticesMap[ key ] ];
  5255. }
  5256. };
  5257. // if faces are completely degenerate after merging vertices, we
  5258. // have to remove them from the geometry.
  5259. var faceIndicesToRemove = [];
  5260. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  5261. face = this.faces[ i ];
  5262. face.a = changes[ face.a ];
  5263. face.b = changes[ face.b ];
  5264. face.c = changes[ face.c ];
  5265. indices = [ face.a, face.b, face.c ];
  5266. var dupIndex = -1;
  5267. // if any duplicate vertices are found in a Face3
  5268. // we have to remove the face as nothing can be saved
  5269. for ( var n = 0; n < 3; n ++ ) {
  5270. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  5271. dupIndex = n;
  5272. faceIndicesToRemove.push( i );
  5273. break;
  5274. }
  5275. }
  5276. }
  5277. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  5278. var idx = faceIndicesToRemove[ i ];
  5279. this.faces.splice( idx, 1 );
  5280. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5281. this.faceVertexUvs[ j ].splice( idx, 1 );
  5282. }
  5283. }
  5284. // Use unique set of vertices
  5285. var diff = this.vertices.length - unique.length;
  5286. this.vertices = unique;
  5287. return diff;
  5288. },
  5289. clone: function () {
  5290. var geometry = new THREE.Geometry();
  5291. var vertices = this.vertices;
  5292. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5293. geometry.vertices.push( vertices[ i ].clone() );
  5294. }
  5295. var faces = this.faces;
  5296. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  5297. geometry.faces.push( faces[ i ].clone() );
  5298. }
  5299. var uvs = this.faceVertexUvs[ 0 ];
  5300. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  5301. var uv = uvs[ i ], uvCopy = [];
  5302. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5303. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  5304. }
  5305. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  5306. }
  5307. return geometry;
  5308. },
  5309. dispose: function () {
  5310. this.dispatchEvent( { type: 'dispose' } );
  5311. }
  5312. };
  5313. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  5314. THREE.GeometryIdCount = 0;
  5315. /**
  5316. * @author alteredq / http://alteredqualia.com/
  5317. */
  5318. THREE.BufferGeometry = function () {
  5319. this.id = THREE.GeometryIdCount ++;
  5320. this.uuid = THREE.Math.generateUUID();
  5321. this.name = '';
  5322. // attributes
  5323. this.attributes = {};
  5324. // attributes typed arrays are kept only if dynamic flag is set
  5325. this.dynamic = true;
  5326. // offsets for chunks when using indexed elements
  5327. this.offsets = [];
  5328. // boundings
  5329. this.boundingBox = null;
  5330. this.boundingSphere = null;
  5331. this.hasTangents = false;
  5332. // for compatibility
  5333. this.morphTargets = [];
  5334. };
  5335. THREE.BufferGeometry.prototype = {
  5336. constructor: THREE.BufferGeometry,
  5337. addAttribute: function( name, type, numItems, itemSize ) {
  5338. this.attributes[ name ] = {
  5339. itemSize: itemSize,
  5340. array: new type( numItems * itemSize )
  5341. };
  5342. },
  5343. applyMatrix: function ( matrix ) {
  5344. var positionArray;
  5345. var normalArray;
  5346. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  5347. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  5348. if ( positionArray !== undefined ) {
  5349. matrix.multiplyVector3Array( positionArray );
  5350. this.verticesNeedUpdate = true;
  5351. }
  5352. if ( normalArray !== undefined ) {
  5353. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5354. normalMatrix.multiplyVector3Array( normalArray );
  5355. this.normalizeNormals();
  5356. this.normalsNeedUpdate = true;
  5357. }
  5358. },
  5359. computeBoundingBox: function () {
  5360. if ( this.boundingBox === null ) {
  5361. this.boundingBox = new THREE.Box3();
  5362. }
  5363. var positions = this.attributes[ "position" ].array;
  5364. if ( positions ) {
  5365. var bb = this.boundingBox;
  5366. var x, y, z;
  5367. if( positions.length >= 3 ) {
  5368. bb.min.x = bb.max.x = positions[ 0 ];
  5369. bb.min.y = bb.max.y = positions[ 1 ];
  5370. bb.min.z = bb.max.z = positions[ 2 ];
  5371. }
  5372. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5373. x = positions[ i ];
  5374. y = positions[ i + 1 ];
  5375. z = positions[ i + 2 ];
  5376. // bounding box
  5377. if ( x < bb.min.x ) {
  5378. bb.min.x = x;
  5379. } else if ( x > bb.max.x ) {
  5380. bb.max.x = x;
  5381. }
  5382. if ( y < bb.min.y ) {
  5383. bb.min.y = y;
  5384. } else if ( y > bb.max.y ) {
  5385. bb.max.y = y;
  5386. }
  5387. if ( z < bb.min.z ) {
  5388. bb.min.z = z;
  5389. } else if ( z > bb.max.z ) {
  5390. bb.max.z = z;
  5391. }
  5392. }
  5393. }
  5394. if ( positions === undefined || positions.length === 0 ) {
  5395. this.boundingBox.min.set( 0, 0, 0 );
  5396. this.boundingBox.max.set( 0, 0, 0 );
  5397. }
  5398. },
  5399. computeBoundingSphere: function () {
  5400. var box = new THREE.Box3();
  5401. var vector = new THREE.Vector3();
  5402. return function () {
  5403. if ( this.boundingSphere === null ) {
  5404. this.boundingSphere = new THREE.Sphere();
  5405. }
  5406. var positions = this.attributes[ "position" ].array;
  5407. if ( positions ) {
  5408. var center = this.boundingSphere.center;
  5409. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5410. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5411. box.addPoint( vector );
  5412. }
  5413. box.center( center );
  5414. var maxRadiusSq = 0;
  5415. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5416. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5417. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5418. }
  5419. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5420. }
  5421. }
  5422. }(),
  5423. computeVertexNormals: function () {
  5424. if ( this.attributes[ "position" ] ) {
  5425. var i, il;
  5426. var j, jl;
  5427. var nVertexElements = this.attributes[ "position" ].array.length;
  5428. if ( this.attributes[ "normal" ] === undefined ) {
  5429. this.attributes[ "normal" ] = {
  5430. itemSize: 3,
  5431. array: new Float32Array( nVertexElements )
  5432. };
  5433. } else {
  5434. // reset existing normals to zero
  5435. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5436. this.attributes[ "normal" ].array[ i ] = 0;
  5437. }
  5438. }
  5439. var positions = this.attributes[ "position" ].array;
  5440. var normals = this.attributes[ "normal" ].array;
  5441. var vA, vB, vC, x, y, z,
  5442. pA = new THREE.Vector3(),
  5443. pB = new THREE.Vector3(),
  5444. pC = new THREE.Vector3(),
  5445. cb = new THREE.Vector3(),
  5446. ab = new THREE.Vector3();
  5447. // indexed elements
  5448. if ( this.attributes[ "index" ] ) {
  5449. var indices = this.attributes[ "index" ].array;
  5450. var offsets = this.offsets;
  5451. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5452. var start = offsets[ j ].start;
  5453. var count = offsets[ j ].count;
  5454. var index = offsets[ j ].index;
  5455. for ( i = start, il = start + count; i < il; i += 3 ) {
  5456. vA = index + indices[ i ];
  5457. vB = index + indices[ i + 1 ];
  5458. vC = index + indices[ i + 2 ];
  5459. x = positions[ vA * 3 ];
  5460. y = positions[ vA * 3 + 1 ];
  5461. z = positions[ vA * 3 + 2 ];
  5462. pA.set( x, y, z );
  5463. x = positions[ vB * 3 ];
  5464. y = positions[ vB * 3 + 1 ];
  5465. z = positions[ vB * 3 + 2 ];
  5466. pB.set( x, y, z );
  5467. x = positions[ vC * 3 ];
  5468. y = positions[ vC * 3 + 1 ];
  5469. z = positions[ vC * 3 + 2 ];
  5470. pC.set( x, y, z );
  5471. cb.subVectors( pC, pB );
  5472. ab.subVectors( pA, pB );
  5473. cb.cross( ab );
  5474. normals[ vA * 3 ] += cb.x;
  5475. normals[ vA * 3 + 1 ] += cb.y;
  5476. normals[ vA * 3 + 2 ] += cb.z;
  5477. normals[ vB * 3 ] += cb.x;
  5478. normals[ vB * 3 + 1 ] += cb.y;
  5479. normals[ vB * 3 + 2 ] += cb.z;
  5480. normals[ vC * 3 ] += cb.x;
  5481. normals[ vC * 3 + 1 ] += cb.y;
  5482. normals[ vC * 3 + 2 ] += cb.z;
  5483. }
  5484. }
  5485. // non-indexed elements (unconnected triangle soup)
  5486. } else {
  5487. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5488. x = positions[ i ];
  5489. y = positions[ i + 1 ];
  5490. z = positions[ i + 2 ];
  5491. pA.set( x, y, z );
  5492. x = positions[ i + 3 ];
  5493. y = positions[ i + 4 ];
  5494. z = positions[ i + 5 ];
  5495. pB.set( x, y, z );
  5496. x = positions[ i + 6 ];
  5497. y = positions[ i + 7 ];
  5498. z = positions[ i + 8 ];
  5499. pC.set( x, y, z );
  5500. cb.subVectors( pC, pB );
  5501. ab.subVectors( pA, pB );
  5502. cb.cross( ab );
  5503. normals[ i ] = cb.x;
  5504. normals[ i + 1 ] = cb.y;
  5505. normals[ i + 2 ] = cb.z;
  5506. normals[ i + 3 ] = cb.x;
  5507. normals[ i + 4 ] = cb.y;
  5508. normals[ i + 5 ] = cb.z;
  5509. normals[ i + 6 ] = cb.x;
  5510. normals[ i + 7 ] = cb.y;
  5511. normals[ i + 8 ] = cb.z;
  5512. }
  5513. }
  5514. this.normalizeNormals();
  5515. this.normalsNeedUpdate = true;
  5516. }
  5517. },
  5518. normalizeNormals: function () {
  5519. var normals = this.attributes[ "normal" ].array;
  5520. var x, y, z, n;
  5521. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5522. x = normals[ i ];
  5523. y = normals[ i + 1 ];
  5524. z = normals[ i + 2 ];
  5525. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5526. normals[ i ] *= n;
  5527. normals[ i + 1 ] *= n;
  5528. normals[ i + 2 ] *= n;
  5529. }
  5530. },
  5531. computeTangents: function () {
  5532. // based on http://www.terathon.com/code/tangent.html
  5533. // (per vertex tangents)
  5534. if ( this.attributes[ "index" ] === undefined ||
  5535. this.attributes[ "position" ] === undefined ||
  5536. this.attributes[ "normal" ] === undefined ||
  5537. this.attributes[ "uv" ] === undefined ) {
  5538. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5539. return;
  5540. }
  5541. var indices = this.attributes[ "index" ].array;
  5542. var positions = this.attributes[ "position" ].array;
  5543. var normals = this.attributes[ "normal" ].array;
  5544. var uvs = this.attributes[ "uv" ].array;
  5545. var nVertices = positions.length / 3;
  5546. if ( this.attributes[ "tangent" ] === undefined ) {
  5547. var nTangentElements = 4 * nVertices;
  5548. this.attributes[ "tangent" ] = {
  5549. itemSize: 4,
  5550. array: new Float32Array( nTangentElements )
  5551. };
  5552. }
  5553. var tangents = this.attributes[ "tangent" ].array;
  5554. var tan1 = [], tan2 = [];
  5555. for ( var k = 0; k < nVertices; k ++ ) {
  5556. tan1[ k ] = new THREE.Vector3();
  5557. tan2[ k ] = new THREE.Vector3();
  5558. }
  5559. var xA, yA, zA,
  5560. xB, yB, zB,
  5561. xC, yC, zC,
  5562. uA, vA,
  5563. uB, vB,
  5564. uC, vC,
  5565. x1, x2, y1, y2, z1, z2,
  5566. s1, s2, t1, t2, r;
  5567. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5568. function handleTriangle( a, b, c ) {
  5569. xA = positions[ a * 3 ];
  5570. yA = positions[ a * 3 + 1 ];
  5571. zA = positions[ a * 3 + 2 ];
  5572. xB = positions[ b * 3 ];
  5573. yB = positions[ b * 3 + 1 ];
  5574. zB = positions[ b * 3 + 2 ];
  5575. xC = positions[ c * 3 ];
  5576. yC = positions[ c * 3 + 1 ];
  5577. zC = positions[ c * 3 + 2 ];
  5578. uA = uvs[ a * 2 ];
  5579. vA = uvs[ a * 2 + 1 ];
  5580. uB = uvs[ b * 2 ];
  5581. vB = uvs[ b * 2 + 1 ];
  5582. uC = uvs[ c * 2 ];
  5583. vC = uvs[ c * 2 + 1 ];
  5584. x1 = xB - xA;
  5585. x2 = xC - xA;
  5586. y1 = yB - yA;
  5587. y2 = yC - yA;
  5588. z1 = zB - zA;
  5589. z2 = zC - zA;
  5590. s1 = uB - uA;
  5591. s2 = uC - uA;
  5592. t1 = vB - vA;
  5593. t2 = vC - vA;
  5594. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5595. sdir.set(
  5596. ( t2 * x1 - t1 * x2 ) * r,
  5597. ( t2 * y1 - t1 * y2 ) * r,
  5598. ( t2 * z1 - t1 * z2 ) * r
  5599. );
  5600. tdir.set(
  5601. ( s1 * x2 - s2 * x1 ) * r,
  5602. ( s1 * y2 - s2 * y1 ) * r,
  5603. ( s1 * z2 - s2 * z1 ) * r
  5604. );
  5605. tan1[ a ].add( sdir );
  5606. tan1[ b ].add( sdir );
  5607. tan1[ c ].add( sdir );
  5608. tan2[ a ].add( tdir );
  5609. tan2[ b ].add( tdir );
  5610. tan2[ c ].add( tdir );
  5611. }
  5612. var i, il;
  5613. var j, jl;
  5614. var iA, iB, iC;
  5615. var offsets = this.offsets;
  5616. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5617. var start = offsets[ j ].start;
  5618. var count = offsets[ j ].count;
  5619. var index = offsets[ j ].index;
  5620. for ( i = start, il = start + count; i < il; i += 3 ) {
  5621. iA = index + indices[ i ];
  5622. iB = index + indices[ i + 1 ];
  5623. iC = index + indices[ i + 2 ];
  5624. handleTriangle( iA, iB, iC );
  5625. }
  5626. }
  5627. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5628. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5629. var w, t, test;
  5630. function handleVertex( v ) {
  5631. n.x = normals[ v * 3 ];
  5632. n.y = normals[ v * 3 + 1 ];
  5633. n.z = normals[ v * 3 + 2 ];
  5634. n2.copy( n );
  5635. t = tan1[ v ];
  5636. // Gram-Schmidt orthogonalize
  5637. tmp.copy( t );
  5638. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5639. // Calculate handedness
  5640. tmp2.crossVectors( n2, t );
  5641. test = tmp2.dot( tan2[ v ] );
  5642. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5643. tangents[ v * 4 ] = tmp.x;
  5644. tangents[ v * 4 + 1 ] = tmp.y;
  5645. tangents[ v * 4 + 2 ] = tmp.z;
  5646. tangents[ v * 4 + 3 ] = w;
  5647. }
  5648. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5649. var start = offsets[ j ].start;
  5650. var count = offsets[ j ].count;
  5651. var index = offsets[ j ].index;
  5652. for ( i = start, il = start + count; i < il; i += 3 ) {
  5653. iA = index + indices[ i ];
  5654. iB = index + indices[ i + 1 ];
  5655. iC = index + indices[ i + 2 ];
  5656. handleVertex( iA );
  5657. handleVertex( iB );
  5658. handleVertex( iC );
  5659. }
  5660. }
  5661. this.hasTangents = true;
  5662. this.tangentsNeedUpdate = true;
  5663. },
  5664. clone: function () {
  5665. var geometry = new THREE.BufferGeometry();
  5666. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5667. for ( var attr in this.attributes ) {
  5668. var sourceAttr = this.attributes[ attr ];
  5669. var sourceArray = sourceAttr.array;
  5670. var attribute = {
  5671. itemSize: sourceAttr.itemSize,
  5672. numItems: sourceAttr.numItems,
  5673. array: null
  5674. };
  5675. for ( var i = 0, il = types.length; i < il; i ++ ) {
  5676. var type = types[ i ];
  5677. if ( sourceArray instanceof type ) {
  5678. attribute.array = new type( sourceArray );
  5679. break;
  5680. }
  5681. }
  5682. geometry.attributes[ attr ] = attribute;
  5683. }
  5684. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  5685. var offset = this.offsets[ i ];
  5686. geometry.offsets.push( {
  5687. start: offset.start,
  5688. index: offset.index,
  5689. count: offset.count
  5690. } );
  5691. }
  5692. return geometry;
  5693. },
  5694. dispose: function () {
  5695. this.dispatchEvent( { type: 'dispose' } );
  5696. }
  5697. };
  5698. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  5699. /**
  5700. * @author mrdoob / http://mrdoob.com/
  5701. * @author mikael emtinger / http://gomo.se/
  5702. * @author WestLangley / http://github.com/WestLangley
  5703. */
  5704. THREE.Camera = function () {
  5705. THREE.Object3D.call( this );
  5706. this.matrixWorldInverse = new THREE.Matrix4();
  5707. this.projectionMatrix = new THREE.Matrix4();
  5708. this.projectionMatrixInverse = new THREE.Matrix4();
  5709. };
  5710. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5711. THREE.Camera.prototype.lookAt = function () {
  5712. // This routine does not support cameras with rotated and/or translated parent(s)
  5713. var m1 = new THREE.Matrix4();
  5714. return function ( vector ) {
  5715. m1.lookAt( this.position, vector, this.up );
  5716. this.quaternion.setFromRotationMatrix( m1 );
  5717. };
  5718. }();
  5719. THREE.Camera.prototype.clone = function (camera) {
  5720. if ( camera === undefined ) camera = new THREE.Camera();
  5721. THREE.Object3D.prototype.clone.call( this, camera );
  5722. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  5723. camera.projectionMatrix.copy( this.projectionMatrix );
  5724. camera.projectionMatrixInverse.copy( this.projectionMatrixInverse );
  5725. return camera;
  5726. };
  5727. /**
  5728. * @author alteredq / http://alteredqualia.com/
  5729. */
  5730. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5731. THREE.Camera.call( this );
  5732. this.left = left;
  5733. this.right = right;
  5734. this.top = top;
  5735. this.bottom = bottom;
  5736. this.near = ( near !== undefined ) ? near : 0.1;
  5737. this.far = ( far !== undefined ) ? far : 2000;
  5738. this.updateProjectionMatrix();
  5739. };
  5740. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5741. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5742. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5743. };
  5744. THREE.OrthographicCamera.prototype.clone = function () {
  5745. var camera = new THREE.OrthographicCamera();
  5746. THREE.Camera.prototype.clone.call( this, camera );
  5747. camera.left = this.left;
  5748. camera.right = this.right;
  5749. camera.top = this.top;
  5750. camera.bottom = this.bottom;
  5751. camera.near = this.near;
  5752. camera.far = this.far;
  5753. return camera;
  5754. };
  5755. /**
  5756. * @author mrdoob / http://mrdoob.com/
  5757. * @author greggman / http://games.greggman.com/
  5758. * @author zz85 / http://www.lab4games.net/zz85/blog
  5759. */
  5760. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5761. THREE.Camera.call( this );
  5762. this.fov = fov !== undefined ? fov : 50;
  5763. this.aspect = aspect !== undefined ? aspect : 1;
  5764. this.near = near !== undefined ? near : 0.1;
  5765. this.far = far !== undefined ? far : 2000;
  5766. this.updateProjectionMatrix();
  5767. };
  5768. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5769. /**
  5770. * Uses Focal Length (in mm) to estimate and set FOV
  5771. * 35mm (fullframe) camera is used if frame size is not specified;
  5772. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5773. */
  5774. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5775. if ( frameHeight === undefined ) frameHeight = 24;
  5776. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5777. this.updateProjectionMatrix();
  5778. }
  5779. /**
  5780. * Sets an offset in a larger frustum. This is useful for multi-window or
  5781. * multi-monitor/multi-machine setups.
  5782. *
  5783. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5784. * the monitors are in grid like this
  5785. *
  5786. * +---+---+---+
  5787. * | A | B | C |
  5788. * +---+---+---+
  5789. * | D | E | F |
  5790. * +---+---+---+
  5791. *
  5792. * then for each monitor you would call it like this
  5793. *
  5794. * var w = 1920;
  5795. * var h = 1080;
  5796. * var fullWidth = w * 3;
  5797. * var fullHeight = h * 2;
  5798. *
  5799. * --A--
  5800. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5801. * --B--
  5802. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5803. * --C--
  5804. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5805. * --D--
  5806. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5807. * --E--
  5808. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5809. * --F--
  5810. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5811. *
  5812. * Note there is no reason monitors have to be the same size or in a grid.
  5813. */
  5814. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5815. this.fullWidth = fullWidth;
  5816. this.fullHeight = fullHeight;
  5817. this.x = x;
  5818. this.y = y;
  5819. this.width = width;
  5820. this.height = height;
  5821. this.updateProjectionMatrix();
  5822. };
  5823. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5824. if ( this.fullWidth ) {
  5825. var aspect = this.fullWidth / this.fullHeight;
  5826. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5827. var bottom = -top;
  5828. var left = aspect * bottom;
  5829. var right = aspect * top;
  5830. var width = Math.abs( right - left );
  5831. var height = Math.abs( top - bottom );
  5832. this.projectionMatrix.makeFrustum(
  5833. left + this.x * width / this.fullWidth,
  5834. left + ( this.x + this.width ) * width / this.fullWidth,
  5835. top - ( this.y + this.height ) * height / this.fullHeight,
  5836. top - this.y * height / this.fullHeight,
  5837. this.near,
  5838. this.far
  5839. );
  5840. } else {
  5841. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5842. }
  5843. };
  5844. THREE.PerspectiveCamera.prototype.clone = function () {
  5845. var camera = new THREE.PerspectiveCamera();
  5846. THREE.Camera.prototype.clone.call( this, camera );
  5847. camera.fov = this.fov;
  5848. camera.aspect = this.aspect;
  5849. camera.near = this.near;
  5850. camera.far = this.far;
  5851. return camera;
  5852. };
  5853. /**
  5854. * @author mrdoob / http://mrdoob.com/
  5855. * @author alteredq / http://alteredqualia.com/
  5856. */
  5857. THREE.Light = function ( hex ) {
  5858. THREE.Object3D.call( this );
  5859. this.color = new THREE.Color( hex );
  5860. };
  5861. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5862. THREE.Light.prototype.clone = function ( light ) {
  5863. if ( light === undefined ) light = new THREE.Light();
  5864. THREE.Object3D.prototype.clone.call( this, light );
  5865. light.color.copy( this.color );
  5866. return light;
  5867. };
  5868. /**
  5869. * @author mrdoob / http://mrdoob.com/
  5870. */
  5871. THREE.AmbientLight = function ( hex ) {
  5872. THREE.Light.call( this, hex );
  5873. };
  5874. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5875. THREE.AmbientLight.prototype.clone = function () {
  5876. var light = new THREE.AmbientLight();
  5877. THREE.Light.prototype.clone.call( this, light );
  5878. return light;
  5879. };
  5880. /**
  5881. * @author MPanknin / http://www.redplant.de/
  5882. * @author alteredq / http://alteredqualia.com/
  5883. */
  5884. THREE.AreaLight = function ( hex, intensity ) {
  5885. THREE.Light.call( this, hex );
  5886. this.normal = new THREE.Vector3( 0, -1, 0 );
  5887. this.right = new THREE.Vector3( 1, 0, 0 );
  5888. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5889. this.width = 1.0;
  5890. this.height = 1.0;
  5891. this.constantAttenuation = 1.5;
  5892. this.linearAttenuation = 0.5;
  5893. this.quadraticAttenuation = 0.1;
  5894. };
  5895. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5896. /**
  5897. * @author mrdoob / http://mrdoob.com/
  5898. * @author alteredq / http://alteredqualia.com/
  5899. */
  5900. THREE.DirectionalLight = function ( hex, intensity ) {
  5901. THREE.Light.call( this, hex );
  5902. this.position.set( 0, 1, 0 );
  5903. this.target = new THREE.Object3D();
  5904. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5905. this.castShadow = false;
  5906. this.onlyShadow = false;
  5907. //
  5908. this.shadowCameraNear = 50;
  5909. this.shadowCameraFar = 5000;
  5910. this.shadowCameraLeft = -500;
  5911. this.shadowCameraRight = 500;
  5912. this.shadowCameraTop = 500;
  5913. this.shadowCameraBottom = -500;
  5914. this.shadowCameraVisible = false;
  5915. this.shadowBias = 0;
  5916. this.shadowDarkness = 0.5;
  5917. this.shadowMapWidth = 512;
  5918. this.shadowMapHeight = 512;
  5919. //
  5920. this.shadowCascade = false;
  5921. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5922. this.shadowCascadeCount = 2;
  5923. this.shadowCascadeBias = [ 0, 0, 0 ];
  5924. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5925. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5926. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5927. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5928. this.shadowCascadeArray = [];
  5929. //
  5930. this.shadowMap = null;
  5931. this.shadowMapSize = null;
  5932. this.shadowCamera = null;
  5933. this.shadowMatrix = null;
  5934. };
  5935. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5936. THREE.DirectionalLight.prototype.clone = function () {
  5937. var light = new THREE.DirectionalLight();
  5938. THREE.Light.prototype.clone.call( this, light );
  5939. light.target = this.target.clone();
  5940. light.intensity = this.intensity;
  5941. light.castShadow = this.castShadow;
  5942. light.onlyShadow = this.onlyShadow;
  5943. return light;
  5944. };
  5945. /**
  5946. * @author alteredq / http://alteredqualia.com/
  5947. */
  5948. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5949. THREE.Light.call( this, skyColorHex );
  5950. this.position.set( 0, 100, 0 );
  5951. this.groundColor = new THREE.Color( groundColorHex );
  5952. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5953. };
  5954. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5955. THREE.HemisphereLight.prototype.clone = function () {
  5956. var light = new THREE.HemisphereLight();
  5957. THREE.Light.prototype.clone.call( this, light );
  5958. light.groundColor.copy( this.groundColor );
  5959. light.intensity = this.intensity;
  5960. return light;
  5961. };
  5962. /**
  5963. * @author mrdoob / http://mrdoob.com/
  5964. */
  5965. THREE.PointLight = function ( hex, intensity, distance ) {
  5966. THREE.Light.call( this, hex );
  5967. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5968. this.distance = ( distance !== undefined ) ? distance : 0;
  5969. };
  5970. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5971. THREE.PointLight.prototype.clone = function () {
  5972. var light = new THREE.PointLight();
  5973. THREE.Light.prototype.clone.call( this, light );
  5974. light.intensity = this.intensity;
  5975. light.distance = this.distance;
  5976. return light;
  5977. };
  5978. /**
  5979. * @author alteredq / http://alteredqualia.com/
  5980. */
  5981. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5982. THREE.Light.call( this, hex );
  5983. this.position.set( 0, 1, 0 );
  5984. this.target = new THREE.Object3D();
  5985. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5986. this.distance = ( distance !== undefined ) ? distance : 0;
  5987. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  5988. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5989. this.castShadow = false;
  5990. this.onlyShadow = false;
  5991. //
  5992. this.shadowCameraNear = 50;
  5993. this.shadowCameraFar = 5000;
  5994. this.shadowCameraFov = 50;
  5995. this.shadowCameraVisible = false;
  5996. this.shadowBias = 0;
  5997. this.shadowDarkness = 0.5;
  5998. this.shadowMapWidth = 512;
  5999. this.shadowMapHeight = 512;
  6000. //
  6001. this.shadowMap = null;
  6002. this.shadowMapSize = null;
  6003. this.shadowCamera = null;
  6004. this.shadowMatrix = null;
  6005. };
  6006. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  6007. THREE.SpotLight.prototype.clone = function () {
  6008. var light = new THREE.SpotLight();
  6009. THREE.Light.prototype.clone.call( this, light );
  6010. light.target = this.target.clone();
  6011. light.intensity = this.intensity;
  6012. light.distance = this.distance;
  6013. light.angle = this.angle;
  6014. light.exponent = this.exponent;
  6015. light.castShadow = this.castShadow;
  6016. light.onlyShadow = this.onlyShadow;
  6017. return light;
  6018. };
  6019. /**
  6020. * @author alteredq / http://alteredqualia.com/
  6021. */
  6022. THREE.Loader = function ( showStatus ) {
  6023. this.showStatus = showStatus;
  6024. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6025. this.onLoadStart = function () {};
  6026. this.onLoadProgress = function () {};
  6027. this.onLoadComplete = function () {};
  6028. };
  6029. THREE.Loader.prototype = {
  6030. constructor: THREE.Loader,
  6031. crossOrigin: 'anonymous',
  6032. addStatusElement: function () {
  6033. var e = document.createElement( "div" );
  6034. e.style.position = "absolute";
  6035. e.style.right = "0px";
  6036. e.style.top = "0px";
  6037. e.style.fontSize = "0.8em";
  6038. e.style.textAlign = "left";
  6039. e.style.background = "rgba(0,0,0,0.25)";
  6040. e.style.color = "#fff";
  6041. e.style.width = "120px";
  6042. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  6043. e.style.zIndex = 1000;
  6044. e.innerHTML = "Loading ...";
  6045. return e;
  6046. },
  6047. updateProgress: function ( progress ) {
  6048. var message = "Loaded ";
  6049. if ( progress.total ) {
  6050. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  6051. } else {
  6052. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  6053. }
  6054. this.statusDomElement.innerHTML = message;
  6055. },
  6056. extractUrlBase: function ( url ) {
  6057. var parts = url.split( '/' );
  6058. parts.pop();
  6059. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  6060. },
  6061. initMaterials: function ( materials, texturePath ) {
  6062. var array = [];
  6063. for ( var i = 0; i < materials.length; ++ i ) {
  6064. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  6065. }
  6066. return array;
  6067. },
  6068. needsTangents: function ( materials ) {
  6069. for( var i = 0, il = materials.length; i < il; i ++ ) {
  6070. var m = materials[ i ];
  6071. if ( m instanceof THREE.ShaderMaterial ) return true;
  6072. }
  6073. return false;
  6074. },
  6075. createMaterial: function ( m, texturePath ) {
  6076. var _this = this;
  6077. function is_pow2( n ) {
  6078. var l = Math.log( n ) / Math.LN2;
  6079. return Math.floor( l ) == l;
  6080. }
  6081. function nearest_pow2( n ) {
  6082. var l = Math.log( n ) / Math.LN2;
  6083. return Math.pow( 2, Math.round( l ) );
  6084. }
  6085. function load_image( where, url ) {
  6086. var image = new Image();
  6087. image.onload = function () {
  6088. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  6089. var width = nearest_pow2( this.width );
  6090. var height = nearest_pow2( this.height );
  6091. where.image.width = width;
  6092. where.image.height = height;
  6093. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  6094. } else {
  6095. where.image = this;
  6096. }
  6097. where.needsUpdate = true;
  6098. };
  6099. image.crossOrigin = _this.crossOrigin;
  6100. image.src = url;
  6101. }
  6102. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  6103. var isCompressed = /\.dds$/i.test( sourceFile );
  6104. var fullPath = texturePath + "/" + sourceFile;
  6105. if ( isCompressed ) {
  6106. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  6107. where[ name ] = texture;
  6108. } else {
  6109. var texture = document.createElement( 'canvas' );
  6110. where[ name ] = new THREE.Texture( texture );
  6111. }
  6112. where[ name ].sourceFile = sourceFile;
  6113. if( repeat ) {
  6114. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6115. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  6116. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  6117. }
  6118. if ( offset ) {
  6119. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  6120. }
  6121. if ( wrap ) {
  6122. var wrapMap = {
  6123. "repeat": THREE.RepeatWrapping,
  6124. "mirror": THREE.MirroredRepeatWrapping
  6125. }
  6126. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  6127. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  6128. }
  6129. if ( anisotropy ) {
  6130. where[ name ].anisotropy = anisotropy;
  6131. }
  6132. if ( ! isCompressed ) {
  6133. load_image( where[ name ], fullPath );
  6134. }
  6135. }
  6136. function rgb2hex( rgb ) {
  6137. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6138. }
  6139. // defaults
  6140. var mtype = "MeshLambertMaterial";
  6141. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  6142. // parameters from model file
  6143. if ( m.shading ) {
  6144. var shading = m.shading.toLowerCase();
  6145. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  6146. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  6147. }
  6148. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6149. mpars.blending = THREE[ m.blending ];
  6150. }
  6151. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  6152. mpars.transparent = m.transparent;
  6153. }
  6154. if ( m.depthTest !== undefined ) {
  6155. mpars.depthTest = m.depthTest;
  6156. }
  6157. if ( m.depthWrite !== undefined ) {
  6158. mpars.depthWrite = m.depthWrite;
  6159. }
  6160. if ( m.visible !== undefined ) {
  6161. mpars.visible = m.visible;
  6162. }
  6163. if ( m.flipSided !== undefined ) {
  6164. mpars.side = THREE.BackSide;
  6165. }
  6166. if ( m.doubleSided !== undefined ) {
  6167. mpars.side = THREE.DoubleSide;
  6168. }
  6169. if ( m.wireframe !== undefined ) {
  6170. mpars.wireframe = m.wireframe;
  6171. }
  6172. if ( m.vertexColors !== undefined ) {
  6173. if ( m.vertexColors === "face" ) {
  6174. mpars.vertexColors = THREE.FaceColors;
  6175. } else if ( m.vertexColors ) {
  6176. mpars.vertexColors = THREE.VertexColors;
  6177. }
  6178. }
  6179. // colors
  6180. if ( m.colorDiffuse ) {
  6181. mpars.color = rgb2hex( m.colorDiffuse );
  6182. } else if ( m.DbgColor ) {
  6183. mpars.color = m.DbgColor;
  6184. }
  6185. if ( m.colorSpecular ) {
  6186. mpars.specular = rgb2hex( m.colorSpecular );
  6187. }
  6188. if ( m.colorAmbient ) {
  6189. mpars.ambient = rgb2hex( m.colorAmbient );
  6190. }
  6191. // modifiers
  6192. if ( m.transparency ) {
  6193. mpars.opacity = m.transparency;
  6194. }
  6195. if ( m.specularCoef ) {
  6196. mpars.shininess = m.specularCoef;
  6197. }
  6198. // textures
  6199. if ( m.mapDiffuse && texturePath ) {
  6200. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  6201. }
  6202. if ( m.mapLight && texturePath ) {
  6203. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  6204. }
  6205. if ( m.mapBump && texturePath ) {
  6206. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  6207. }
  6208. if ( m.mapNormal && texturePath ) {
  6209. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  6210. }
  6211. if ( m.mapSpecular && texturePath ) {
  6212. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  6213. }
  6214. //
  6215. if ( m.mapBumpScale ) {
  6216. mpars.bumpScale = m.mapBumpScale;
  6217. }
  6218. // special case for normal mapped material
  6219. if ( m.mapNormal ) {
  6220. var shader = THREE.ShaderLib[ "normalmap" ];
  6221. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6222. uniforms[ "tNormal" ].value = mpars.normalMap;
  6223. if ( m.mapNormalFactor ) {
  6224. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  6225. }
  6226. if ( mpars.map ) {
  6227. uniforms[ "tDiffuse" ].value = mpars.map;
  6228. uniforms[ "enableDiffuse" ].value = true;
  6229. }
  6230. if ( mpars.specularMap ) {
  6231. uniforms[ "tSpecular" ].value = mpars.specularMap;
  6232. uniforms[ "enableSpecular" ].value = true;
  6233. }
  6234. if ( mpars.lightMap ) {
  6235. uniforms[ "tAO" ].value = mpars.lightMap;
  6236. uniforms[ "enableAO" ].value = true;
  6237. }
  6238. // for the moment don't handle displacement texture
  6239. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  6240. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  6241. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  6242. uniforms[ "uShininess" ].value = mpars.shininess;
  6243. if ( mpars.opacity !== undefined ) {
  6244. uniforms[ "uOpacity" ].value = mpars.opacity;
  6245. }
  6246. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6247. var material = new THREE.ShaderMaterial( parameters );
  6248. if ( mpars.transparent ) {
  6249. material.transparent = true;
  6250. }
  6251. } else {
  6252. var material = new THREE[ mtype ]( mpars );
  6253. }
  6254. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6255. return material;
  6256. }
  6257. };
  6258. /**
  6259. * @author mrdoob / http://mrdoob.com/
  6260. */
  6261. THREE.XHRLoader = function ( manager ) {
  6262. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6263. };
  6264. THREE.XHRLoader.prototype = {
  6265. constructor: THREE.XHRLoader,
  6266. load: function ( url, onLoad, onProgress, onError ) {
  6267. var scope = this;
  6268. var request = new XMLHttpRequest();
  6269. if ( onLoad !== undefined ) {
  6270. request.addEventListener( 'load', function ( event ) {
  6271. onLoad( event.target.responseText );
  6272. scope.manager.itemEnd( url );
  6273. }, false );
  6274. }
  6275. if ( onProgress !== undefined ) {
  6276. request.addEventListener( 'progress', function ( event ) {
  6277. onProgress( event );
  6278. }, false );
  6279. }
  6280. if ( onError !== undefined ) {
  6281. request.addEventListener( 'error', function ( event ) {
  6282. onError( event );
  6283. }, false );
  6284. }
  6285. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6286. request.open( 'GET', url, true );
  6287. request.send( null );
  6288. scope.manager.itemStart( url );
  6289. },
  6290. setCrossOrigin: function ( value ) {
  6291. this.crossOrigin = value;
  6292. }
  6293. };
  6294. /**
  6295. * @author mrdoob / http://mrdoob.com/
  6296. */
  6297. THREE.ImageLoader = function ( manager ) {
  6298. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6299. };
  6300. THREE.ImageLoader.prototype = {
  6301. constructor: THREE.ImageLoader,
  6302. load: function ( url, onLoad, onProgress, onError ) {
  6303. var scope = this;
  6304. var image = document.createElement( 'img' );
  6305. if ( onLoad !== undefined ) {
  6306. image.addEventListener( 'load', function ( event ) {
  6307. scope.manager.itemEnd( url );
  6308. onLoad( this );
  6309. }, false );
  6310. }
  6311. if ( onProgress !== undefined ) {
  6312. image.addEventListener( 'progress', function ( event ) {
  6313. onProgress( event );
  6314. }, false );
  6315. }
  6316. if ( onError !== undefined ) {
  6317. image.addEventListener( 'error', function ( event ) {
  6318. onError( event );
  6319. }, false );
  6320. }
  6321. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  6322. image.src = url;
  6323. scope.manager.itemStart( url );
  6324. return image;
  6325. },
  6326. setCrossOrigin: function ( value ) {
  6327. this.crossOrigin = value;
  6328. }
  6329. }
  6330. /**
  6331. * @author mrdoob / http://mrdoob.com/
  6332. * @author alteredq / http://alteredqualia.com/
  6333. */
  6334. THREE.JSONLoader = function ( showStatus ) {
  6335. THREE.Loader.call( this, showStatus );
  6336. this.withCredentials = false;
  6337. };
  6338. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  6339. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  6340. var scope = this;
  6341. // todo: unify load API to for easier SceneLoader use
  6342. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  6343. this.onLoadStart();
  6344. this.loadAjaxJSON( this, url, callback, texturePath );
  6345. };
  6346. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  6347. var xhr = new XMLHttpRequest();
  6348. var length = 0;
  6349. xhr.onreadystatechange = function () {
  6350. if ( xhr.readyState === xhr.DONE ) {
  6351. if ( xhr.status === 200 || xhr.status === 0 ) {
  6352. if ( xhr.responseText ) {
  6353. var json = JSON.parse( xhr.responseText );
  6354. var result = context.parse( json, texturePath );
  6355. callback( result.geometry, result.materials );
  6356. } else {
  6357. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  6358. }
  6359. // in context of more complex asset initialization
  6360. // do not block on single failed file
  6361. // maybe should go even one more level up
  6362. context.onLoadComplete();
  6363. } else {
  6364. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  6365. }
  6366. } else if ( xhr.readyState === xhr.LOADING ) {
  6367. if ( callbackProgress ) {
  6368. if ( length === 0 ) {
  6369. length = xhr.getResponseHeader( "Content-Length" );
  6370. }
  6371. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  6372. }
  6373. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  6374. if ( callbackProgress !== undefined ) {
  6375. length = xhr.getResponseHeader( "Content-Length" );
  6376. }
  6377. }
  6378. };
  6379. xhr.open( "GET", url, true );
  6380. xhr.withCredentials = this.withCredentials;
  6381. xhr.send( null );
  6382. };
  6383. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  6384. var scope = this,
  6385. geometry = new THREE.Geometry(),
  6386. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  6387. parseModel( scale );
  6388. parseSkin();
  6389. parseMorphing( scale );
  6390. geometry.computeCentroids();
  6391. geometry.computeFaceNormals();
  6392. geometry.computeBoundingSphere();
  6393. function parseModel( scale ) {
  6394. function isBitSet( value, position ) {
  6395. return value & ( 1 << position );
  6396. }
  6397. var i, j, fi,
  6398. offset, zLength,
  6399. colorIndex, normalIndex, uvIndex, materialIndex,
  6400. type,
  6401. isQuad,
  6402. hasMaterial,
  6403. hasFaceVertexUv,
  6404. hasFaceNormal, hasFaceVertexNormal,
  6405. hasFaceColor, hasFaceVertexColor,
  6406. vertex, face, faceA, faceB, color, hex, normal,
  6407. uvLayer, uv, u, v,
  6408. faces = json.faces,
  6409. vertices = json.vertices,
  6410. normals = json.normals,
  6411. colors = json.colors,
  6412. nUvLayers = 0;
  6413. if ( json.uvs !== undefined ) {
  6414. // disregard empty arrays
  6415. for ( i = 0; i < json.uvs.length; i++ ) {
  6416. if ( json.uvs[ i ].length ) nUvLayers ++;
  6417. }
  6418. for ( i = 0; i < nUvLayers; i++ ) {
  6419. geometry.faceVertexUvs[ i ] = [];
  6420. }
  6421. }
  6422. offset = 0;
  6423. zLength = vertices.length;
  6424. while ( offset < zLength ) {
  6425. vertex = new THREE.Vector3();
  6426. vertex.x = vertices[ offset ++ ] * scale;
  6427. vertex.y = vertices[ offset ++ ] * scale;
  6428. vertex.z = vertices[ offset ++ ] * scale;
  6429. geometry.vertices.push( vertex );
  6430. }
  6431. offset = 0;
  6432. zLength = faces.length;
  6433. while ( offset < zLength ) {
  6434. type = faces[ offset ++ ];
  6435. isQuad = isBitSet( type, 0 );
  6436. hasMaterial = isBitSet( type, 1 );
  6437. hasFaceVertexUv = isBitSet( type, 3 );
  6438. hasFaceNormal = isBitSet( type, 4 );
  6439. hasFaceVertexNormal = isBitSet( type, 5 );
  6440. hasFaceColor = isBitSet( type, 6 );
  6441. hasFaceVertexColor = isBitSet( type, 7 );
  6442. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  6443. if ( isQuad ) {
  6444. faceA = new THREE.Face3();
  6445. faceA.a = faces[ offset ];
  6446. faceA.b = faces[ offset + 1 ];
  6447. faceA.c = faces[ offset + 3 ];
  6448. faceB = new THREE.Face3();
  6449. faceB.a = faces[ offset + 1 ];
  6450. faceB.b = faces[ offset + 2 ];
  6451. faceB.c = faces[ offset + 3 ];
  6452. offset += 4;
  6453. if ( hasMaterial ) {
  6454. materialIndex = faces[ offset ++ ];
  6455. faceA.materialIndex = materialIndex;
  6456. faceB.materialIndex = materialIndex;
  6457. }
  6458. // to get face <=> uv index correspondence
  6459. fi = geometry.faces.length;
  6460. if ( hasFaceVertexUv ) {
  6461. for ( i = 0; i < nUvLayers; i++ ) {
  6462. uvLayer = json.uvs[ i ];
  6463. geometry.faceVertexUvs[ i ][ fi ] = [];
  6464. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  6465. for ( j = 0; j < 4; j ++ ) {
  6466. uvIndex = faces[ offset ++ ];
  6467. u = uvLayer[ uvIndex * 2 ];
  6468. v = uvLayer[ uvIndex * 2 + 1 ];
  6469. uv = new THREE.Vector2( u, v );
  6470. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  6471. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  6472. }
  6473. }
  6474. }
  6475. if ( hasFaceNormal ) {
  6476. normalIndex = faces[ offset ++ ] * 3;
  6477. faceA.normal.set(
  6478. normals[ normalIndex ++ ],
  6479. normals[ normalIndex ++ ],
  6480. normals[ normalIndex ]
  6481. );
  6482. faceB.normal.copy( faceA.normal );
  6483. }
  6484. if ( hasFaceVertexNormal ) {
  6485. for ( i = 0; i < 4; i++ ) {
  6486. normalIndex = faces[ offset ++ ] * 3;
  6487. normal = new THREE.Vector3(
  6488. normals[ normalIndex ++ ],
  6489. normals[ normalIndex ++ ],
  6490. normals[ normalIndex ]
  6491. );
  6492. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  6493. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  6494. }
  6495. }
  6496. if ( hasFaceColor ) {
  6497. colorIndex = faces[ offset ++ ];
  6498. hex = colors[ colorIndex ];
  6499. faceA.color.setHex( hex );
  6500. faceB.color.setHex( hex );
  6501. }
  6502. if ( hasFaceVertexColor ) {
  6503. for ( i = 0; i < 4; i++ ) {
  6504. colorIndex = faces[ offset ++ ];
  6505. hex = colors[ colorIndex ];
  6506. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  6507. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  6508. }
  6509. }
  6510. geometry.faces.push( faceA );
  6511. geometry.faces.push( faceB );
  6512. } else {
  6513. face = new THREE.Face3();
  6514. face.a = faces[ offset ++ ];
  6515. face.b = faces[ offset ++ ];
  6516. face.c = faces[ offset ++ ];
  6517. if ( hasMaterial ) {
  6518. materialIndex = faces[ offset ++ ];
  6519. face.materialIndex = materialIndex;
  6520. }
  6521. // to get face <=> uv index correspondence
  6522. fi = geometry.faces.length;
  6523. if ( hasFaceVertexUv ) {
  6524. for ( i = 0; i < nUvLayers; i++ ) {
  6525. uvLayer = json.uvs[ i ];
  6526. geometry.faceVertexUvs[ i ][ fi ] = [];
  6527. for ( j = 0; j < 3; j ++ ) {
  6528. uvIndex = faces[ offset ++ ];
  6529. u = uvLayer[ uvIndex * 2 ];
  6530. v = uvLayer[ uvIndex * 2 + 1 ];
  6531. uv = new THREE.Vector2( u, v );
  6532. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  6533. }
  6534. }
  6535. }
  6536. if ( hasFaceNormal ) {
  6537. normalIndex = faces[ offset ++ ] * 3;
  6538. face.normal.set(
  6539. normals[ normalIndex ++ ],
  6540. normals[ normalIndex ++ ],
  6541. normals[ normalIndex ]
  6542. );
  6543. }
  6544. if ( hasFaceVertexNormal ) {
  6545. for ( i = 0; i < 3; i++ ) {
  6546. normalIndex = faces[ offset ++ ] * 3;
  6547. normal = new THREE.Vector3(
  6548. normals[ normalIndex ++ ],
  6549. normals[ normalIndex ++ ],
  6550. normals[ normalIndex ]
  6551. );
  6552. face.vertexNormals.push( normal );
  6553. }
  6554. }
  6555. if ( hasFaceColor ) {
  6556. colorIndex = faces[ offset ++ ];
  6557. face.color.setHex( colors[ colorIndex ] );
  6558. }
  6559. if ( hasFaceVertexColor ) {
  6560. for ( i = 0; i < 3; i++ ) {
  6561. colorIndex = faces[ offset ++ ];
  6562. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  6563. }
  6564. }
  6565. geometry.faces.push( face );
  6566. }
  6567. }
  6568. };
  6569. function parseSkin() {
  6570. var i, l, x, y, z, w, a, b, c, d;
  6571. if ( json.skinWeights ) {
  6572. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  6573. x = json.skinWeights[ i ];
  6574. y = json.skinWeights[ i + 1 ];
  6575. z = 0;
  6576. w = 0;
  6577. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  6578. }
  6579. }
  6580. if ( json.skinIndices ) {
  6581. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  6582. a = json.skinIndices[ i ];
  6583. b = json.skinIndices[ i + 1 ];
  6584. c = 0;
  6585. d = 0;
  6586. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  6587. }
  6588. }
  6589. geometry.bones = json.bones;
  6590. // could change this to json.animations[0] or remove completely
  6591. geometry.animation = json.animation;
  6592. geometry.animations = json.animations;
  6593. };
  6594. function parseMorphing( scale ) {
  6595. if ( json.morphTargets !== undefined ) {
  6596. var i, l, v, vl, dstVertices, srcVertices;
  6597. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  6598. geometry.morphTargets[ i ] = {};
  6599. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  6600. geometry.morphTargets[ i ].vertices = [];
  6601. dstVertices = geometry.morphTargets[ i ].vertices;
  6602. srcVertices = json.morphTargets [ i ].vertices;
  6603. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  6604. var vertex = new THREE.Vector3();
  6605. vertex.x = srcVertices[ v ] * scale;
  6606. vertex.y = srcVertices[ v + 1 ] * scale;
  6607. vertex.z = srcVertices[ v + 2 ] * scale;
  6608. dstVertices.push( vertex );
  6609. }
  6610. }
  6611. }
  6612. if ( json.morphColors !== undefined ) {
  6613. var i, l, c, cl, dstColors, srcColors, color;
  6614. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  6615. geometry.morphColors[ i ] = {};
  6616. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  6617. geometry.morphColors[ i ].colors = [];
  6618. dstColors = geometry.morphColors[ i ].colors;
  6619. srcColors = json.morphColors [ i ].colors;
  6620. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  6621. color = new THREE.Color( 0xffaa00 );
  6622. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  6623. dstColors.push( color );
  6624. }
  6625. }
  6626. }
  6627. };
  6628. if ( json.materials === undefined ) {
  6629. return { geometry: geometry };
  6630. } else {
  6631. var materials = this.initMaterials( json.materials, texturePath );
  6632. if ( this.needsTangents( materials ) ) {
  6633. geometry.computeTangents();
  6634. }
  6635. return { geometry: geometry, materials: materials };
  6636. }
  6637. };
  6638. /**
  6639. * @author mrdoob / http://mrdoob.com/
  6640. */
  6641. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  6642. var scope = this;
  6643. var loaded = 0, total = 0;
  6644. this.onLoad = onLoad;
  6645. this.onProgress = onProgress;
  6646. this.onError = onError;
  6647. this.itemStart = function ( url ) {
  6648. total ++;
  6649. };
  6650. this.itemEnd = function ( url ) {
  6651. loaded ++;
  6652. if ( scope.onProgress !== undefined ) {
  6653. scope.onProgress( url, loaded, total );
  6654. }
  6655. if ( loaded === total && scope.onLoad !== undefined ) {
  6656. scope.onLoad();
  6657. }
  6658. };
  6659. };
  6660. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  6661. /**
  6662. * @author mrdoob / http://mrdoob.com/
  6663. */
  6664. THREE.BufferGeometryLoader = function ( manager ) {
  6665. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6666. };
  6667. THREE.BufferGeometryLoader.prototype = {
  6668. constructor: THREE.BufferGeometryLoader,
  6669. load: function ( url, onLoad, onProgress, onError ) {
  6670. var scope = this;
  6671. var loader = new THREE.XHRLoader();
  6672. loader.setCrossOrigin( this.crossOrigin );
  6673. loader.load( url, function ( text ) {
  6674. onLoad( scope.parse( JSON.parse( text ) ) );
  6675. } );
  6676. },
  6677. setCrossOrigin: function ( value ) {
  6678. this.crossOrigin = value;
  6679. },
  6680. parse: function ( json ) {
  6681. var geometry = new THREE.BufferGeometry();
  6682. var attributes = json.attributes;
  6683. var offsets = json.offsets;
  6684. var boundingSphere = json.boundingSphere;
  6685. for ( var key in attributes ) {
  6686. var attribute = attributes[ key ];
  6687. geometry.attributes[ key ] = {
  6688. itemSize: attribute.itemSize,
  6689. array: new self[ attribute.type ]( attribute.array )
  6690. }
  6691. }
  6692. if ( offsets !== undefined ) {
  6693. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  6694. }
  6695. if ( boundingSphere !== undefined ) {
  6696. geometry.boundingSphere = new THREE.Sphere(
  6697. new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
  6698. boundingSphere.radius
  6699. );
  6700. }
  6701. return geometry;
  6702. }
  6703. };
  6704. /**
  6705. * @author mrdoob / http://mrdoob.com/
  6706. */
  6707. THREE.GeometryLoader = function ( manager ) {
  6708. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6709. };
  6710. THREE.GeometryLoader.prototype = {
  6711. constructor: THREE.GeometryLoader,
  6712. load: function ( url, onLoad, onProgress, onError ) {
  6713. var scope = this;
  6714. var loader = new THREE.XHRLoader();
  6715. loader.setCrossOrigin( this.crossOrigin );
  6716. loader.load( url, function ( text ) {
  6717. onLoad( scope.parse( JSON.parse( text ) ) );
  6718. } );
  6719. },
  6720. setCrossOrigin: function ( value ) {
  6721. this.crossOrigin = value;
  6722. },
  6723. parse: function ( json ) {
  6724. }
  6725. };
  6726. /**
  6727. * @author mrdoob / http://mrdoob.com/
  6728. */
  6729. THREE.MaterialLoader = function ( manager ) {
  6730. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6731. };
  6732. THREE.MaterialLoader.prototype = {
  6733. constructor: THREE.MaterialLoader,
  6734. load: function ( url, onLoad, onProgress, onError ) {
  6735. var scope = this;
  6736. var loader = new THREE.XHRLoader();
  6737. loader.setCrossOrigin( this.crossOrigin );
  6738. loader.load( url, function ( text ) {
  6739. onLoad( scope.parse( JSON.parse( text ) ) );
  6740. } );
  6741. },
  6742. setCrossOrigin: function ( value ) {
  6743. this.crossOrigin = value;
  6744. },
  6745. parse: function ( json ) {
  6746. var material = new THREE[ json.type ];
  6747. if ( json.color !== undefined ) material.color.setHex( json.color );
  6748. if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient );
  6749. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  6750. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  6751. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  6752. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  6753. if ( json.blending !== undefined ) material.blending = json.blending;
  6754. if ( json.side !== undefined ) material.side = json.side;
  6755. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  6756. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  6757. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  6758. if ( json.materials !== undefined ) {
  6759. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  6760. material.materials.push( this.parse( json.materials[ i ] ) );
  6761. }
  6762. }
  6763. return material;
  6764. }
  6765. };
  6766. /**
  6767. * @author mrdoob / http://mrdoob.com/
  6768. */
  6769. THREE.ObjectLoader = function ( manager ) {
  6770. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6771. };
  6772. THREE.ObjectLoader.prototype = {
  6773. constructor: THREE.ObjectLoader,
  6774. load: function ( url, onLoad, onProgress, onError ) {
  6775. var scope = this;
  6776. var loader = new THREE.XHRLoader( scope.manager );
  6777. loader.setCrossOrigin( this.crossOrigin );
  6778. loader.load( url, function ( text ) {
  6779. onLoad( scope.parse( JSON.parse( text ) ) );
  6780. } );
  6781. },
  6782. setCrossOrigin: function ( value ) {
  6783. this.crossOrigin = value;
  6784. },
  6785. parse: function ( json ) {
  6786. var geometries = this.parseGeometries( json.geometries );
  6787. var materials = this.parseMaterials( json.materials );
  6788. var object = this.parseObject( json.object, geometries, materials );
  6789. return object;
  6790. },
  6791. parseGeometries: function ( json ) {
  6792. var geometries = {};
  6793. if ( json !== undefined ) {
  6794. var geometryLoader = new THREE.JSONLoader();
  6795. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  6796. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6797. var geometry;
  6798. var data = json[ i ];
  6799. switch ( data.type ) {
  6800. case 'PlaneGeometry':
  6801. geometry = new THREE.PlaneGeometry(
  6802. data.width,
  6803. data.height,
  6804. data.widthSegments,
  6805. data.heightSegments
  6806. );
  6807. break;
  6808. case 'CircleGeometry':
  6809. geometry = new THREE.CircleGeometry(
  6810. data.radius,
  6811. data.segments
  6812. );
  6813. break;
  6814. case 'CubeGeometry':
  6815. geometry = new THREE.CubeGeometry(
  6816. data.width,
  6817. data.height,
  6818. data.depth,
  6819. data.widthSegments,
  6820. data.heightSegments,
  6821. data.depthSegments
  6822. );
  6823. break;
  6824. case 'CylinderGeometry':
  6825. geometry = new THREE.CylinderGeometry(
  6826. data.radiusTop,
  6827. data.radiusBottom,
  6828. data.height,
  6829. data.radialSegments,
  6830. data.heightSegments,
  6831. data.openEnded
  6832. );
  6833. break;
  6834. case 'SphereGeometry':
  6835. geometry = new THREE.SphereGeometry(
  6836. data.radius,
  6837. data.widthSegments,
  6838. data.heightSegments,
  6839. data.phiStart,
  6840. data.phiLength,
  6841. data.thetaStart,
  6842. data.thetaLength
  6843. );
  6844. break;
  6845. case 'IcosahedronGeometry':
  6846. geometry = new THREE.IcosahedronGeometry(
  6847. data.radius,
  6848. data.detail
  6849. );
  6850. break;
  6851. case 'TorusGeometry':
  6852. geometry = new THREE.TorusGeometry(
  6853. data.radius,
  6854. data.tube,
  6855. data.radialSegments,
  6856. data.tubularSegments,
  6857. data.arc
  6858. );
  6859. break;
  6860. case 'TorusKnotGeometry':
  6861. geometry = new THREE.TorusKnotGeometry(
  6862. data.radius,
  6863. data.tube,
  6864. data.radialSegments,
  6865. data.tubularSegments,
  6866. data.p,
  6867. data.q,
  6868. data.heightScale
  6869. );
  6870. break;
  6871. case 'BufferGeometry':
  6872. geometry = bufferGeometryLoader.parse( data.data );
  6873. break;
  6874. case 'Geometry':
  6875. geometry = geometryLoader.parse( data.data ).geometry;
  6876. break;
  6877. }
  6878. geometry.uuid = data.uuid;
  6879. if ( data.name !== undefined ) geometry.name = data.name;
  6880. geometries[ data.uuid ] = geometry;
  6881. }
  6882. }
  6883. return geometries;
  6884. },
  6885. parseMaterials: function ( json ) {
  6886. var materials = {};
  6887. if ( json !== undefined ) {
  6888. var loader = new THREE.MaterialLoader();
  6889. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6890. var data = json[ i ];
  6891. var material = loader.parse( data );
  6892. material.uuid = data.uuid;
  6893. if ( data.name !== undefined ) material.name = data.name;
  6894. materials[ data.uuid ] = material;
  6895. }
  6896. }
  6897. return materials;
  6898. },
  6899. parseObject: function () {
  6900. var matrix = new THREE.Matrix4();
  6901. return function ( data, geometries, materials ) {
  6902. var object;
  6903. switch ( data.type ) {
  6904. case 'Scene':
  6905. object = new THREE.Scene();
  6906. break;
  6907. case 'PerspectiveCamera':
  6908. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  6909. break;
  6910. case 'OrthographicCamera':
  6911. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  6912. break;
  6913. case 'AmbientLight':
  6914. object = new THREE.AmbientLight( data.color );
  6915. break;
  6916. case 'DirectionalLight':
  6917. object = new THREE.DirectionalLight( data.color, data.intensity );
  6918. break;
  6919. case 'PointLight':
  6920. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  6921. break;
  6922. case 'SpotLight':
  6923. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  6924. break;
  6925. case 'HemisphereLight':
  6926. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  6927. break;
  6928. case 'Mesh':
  6929. var geometry = geometries[ data.geometry ];
  6930. var material = materials[ data.material ];
  6931. if ( geometry === undefined ) {
  6932. console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry );
  6933. }
  6934. if ( material === undefined ) {
  6935. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  6936. }
  6937. object = new THREE.Mesh( geometry, material );
  6938. break;
  6939. case 'Sprite':
  6940. var material = materials[ data.material ];
  6941. if ( material === undefined ) {
  6942. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  6943. }
  6944. object = new THREE.Sprite( material );
  6945. break;
  6946. default:
  6947. object = new THREE.Object3D();
  6948. }
  6949. object.uuid = data.uuid;
  6950. if ( data.name !== undefined ) object.name = data.name;
  6951. if ( data.matrix !== undefined ) {
  6952. matrix.fromArray( data.matrix );
  6953. matrix.decompose( object.position, object.quaternion, object.scale );
  6954. } else {
  6955. if ( data.position !== undefined ) object.position.fromArray( data.position );
  6956. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  6957. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  6958. }
  6959. if ( data.visible !== undefined ) object.visible = data.visible;
  6960. if ( data.userData !== undefined ) object.userData = data.userData;
  6961. if ( data.children !== undefined ) {
  6962. for ( var child in data.children ) {
  6963. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  6964. }
  6965. }
  6966. return object;
  6967. }
  6968. }()
  6969. };
  6970. /**
  6971. * @author alteredq / http://alteredqualia.com/
  6972. */
  6973. THREE.SceneLoader = function () {
  6974. this.onLoadStart = function () {};
  6975. this.onLoadProgress = function() {};
  6976. this.onLoadComplete = function () {};
  6977. this.callbackSync = function () {};
  6978. this.callbackProgress = function () {};
  6979. this.geometryHandlers = {};
  6980. this.hierarchyHandlers = {};
  6981. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  6982. };
  6983. THREE.SceneLoader.prototype = {
  6984. constructor: THREE.SceneLoader,
  6985. load: function ( url, onLoad, onProgress, onError ) {
  6986. var scope = this;
  6987. var loader = new THREE.XHRLoader( scope.manager );
  6988. loader.setCrossOrigin( this.crossOrigin );
  6989. loader.load( url, function ( text ) {
  6990. scope.parse( JSON.parse( text ), onLoad, url );
  6991. } );
  6992. },
  6993. setCrossOrigin: function ( value ) {
  6994. this.crossOrigin = value;
  6995. },
  6996. addGeometryHandler: function ( typeID, loaderClass ) {
  6997. this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass };
  6998. },
  6999. addHierarchyHandler: function ( typeID, loaderClass ) {
  7000. this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass };
  7001. },
  7002. parse: function ( json, callbackFinished, url ) {
  7003. var scope = this;
  7004. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  7005. var geometry, material, camera, fog,
  7006. texture, images, color,
  7007. light, hex, intensity,
  7008. counter_models, counter_textures,
  7009. total_models, total_textures,
  7010. result;
  7011. var target_array = [];
  7012. var data = json;
  7013. // async geometry loaders
  7014. for ( var typeID in this.geometryHandlers ) {
  7015. var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ];
  7016. this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7017. }
  7018. // async hierachy loaders
  7019. for ( var typeID in this.hierarchyHandlers ) {
  7020. var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ];
  7021. this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7022. }
  7023. counter_models = 0;
  7024. counter_textures = 0;
  7025. result = {
  7026. scene: new THREE.Scene(),
  7027. geometries: {},
  7028. face_materials: {},
  7029. materials: {},
  7030. textures: {},
  7031. objects: {},
  7032. cameras: {},
  7033. lights: {},
  7034. fogs: {},
  7035. empties: {},
  7036. groups: {}
  7037. };
  7038. if ( data.transform ) {
  7039. var position = data.transform.position,
  7040. rotation = data.transform.rotation,
  7041. scale = data.transform.scale;
  7042. if ( position ) {
  7043. result.scene.position.fromArray( position );
  7044. }
  7045. if ( rotation ) {
  7046. result.scene.rotation.fromArray( rotation );
  7047. }
  7048. if ( scale ) {
  7049. result.scene.scale.fromArray( scale );
  7050. }
  7051. if ( position || rotation || scale ) {
  7052. result.scene.updateMatrix();
  7053. result.scene.updateMatrixWorld();
  7054. }
  7055. }
  7056. function get_url( source_url, url_type ) {
  7057. if ( url_type == "relativeToHTML" ) {
  7058. return source_url;
  7059. } else {
  7060. return urlBase + "/" + source_url;
  7061. }
  7062. };
  7063. // toplevel loader function, delegates to handle_children
  7064. function handle_objects() {
  7065. handle_children( result.scene, data.objects );
  7066. }
  7067. // handle all the children from the loaded json and attach them to given parent
  7068. function handle_children( parent, children ) {
  7069. var mat, dst, pos, rot, scl, quat;
  7070. for ( var objID in children ) {
  7071. // check by id if child has already been handled,
  7072. // if not, create new object
  7073. var object = result.objects[ objID ];
  7074. var objJSON = children[ objID ];
  7075. if ( object === undefined ) {
  7076. // meshes
  7077. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7078. if ( objJSON.loading === undefined ) {
  7079. var reservedTypes = {
  7080. "type": 1, "url": 1, "material": 1,
  7081. "position": 1, "rotation": 1, "scale" : 1,
  7082. "visible": 1, "children": 1, "userData": 1,
  7083. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
  7084. };
  7085. var loaderParameters = {};
  7086. for ( var parType in objJSON ) {
  7087. if ( ! ( parType in reservedTypes ) ) {
  7088. loaderParameters[ parType ] = objJSON[ parType ];
  7089. }
  7090. }
  7091. material = result.materials[ objJSON.material ];
  7092. objJSON.loading = true;
  7093. var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
  7094. // ColladaLoader
  7095. if ( loader.options ) {
  7096. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  7097. // UTF8Loader
  7098. // OBJLoader
  7099. } else {
  7100. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  7101. }
  7102. }
  7103. } else if ( objJSON.geometry !== undefined ) {
  7104. geometry = result.geometries[ objJSON.geometry ];
  7105. // geometry already loaded
  7106. if ( geometry ) {
  7107. var needsTangents = false;
  7108. material = result.materials[ objJSON.material ];
  7109. needsTangents = material instanceof THREE.ShaderMaterial;
  7110. pos = objJSON.position;
  7111. rot = objJSON.rotation;
  7112. scl = objJSON.scale;
  7113. mat = objJSON.matrix;
  7114. quat = objJSON.quaternion;
  7115. // use materials from the model file
  7116. // if there is no material specified in the object
  7117. if ( ! objJSON.material ) {
  7118. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7119. }
  7120. // use materials from the model file
  7121. // if there is just empty face material
  7122. // (must create new material as each model has its own face material)
  7123. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  7124. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7125. }
  7126. if ( material instanceof THREE.MeshFaceMaterial ) {
  7127. for ( var i = 0; i < material.materials.length; i ++ ) {
  7128. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  7129. }
  7130. }
  7131. if ( needsTangents ) {
  7132. geometry.computeTangents();
  7133. }
  7134. if ( objJSON.skin ) {
  7135. object = new THREE.SkinnedMesh( geometry, material );
  7136. } else if ( objJSON.morph ) {
  7137. object = new THREE.MorphAnimMesh( geometry, material );
  7138. if ( objJSON.duration !== undefined ) {
  7139. object.duration = objJSON.duration;
  7140. }
  7141. if ( objJSON.time !== undefined ) {
  7142. object.time = objJSON.time;
  7143. }
  7144. if ( objJSON.mirroredLoop !== undefined ) {
  7145. object.mirroredLoop = objJSON.mirroredLoop;
  7146. }
  7147. if ( material.morphNormals ) {
  7148. geometry.computeMorphNormals();
  7149. }
  7150. } else {
  7151. object = new THREE.Mesh( geometry, material );
  7152. }
  7153. object.name = objID;
  7154. if ( mat ) {
  7155. object.matrixAutoUpdate = false;
  7156. object.matrix.set(
  7157. mat[0], mat[1], mat[2], mat[3],
  7158. mat[4], mat[5], mat[6], mat[7],
  7159. mat[8], mat[9], mat[10], mat[11],
  7160. mat[12], mat[13], mat[14], mat[15]
  7161. );
  7162. } else {
  7163. object.position.fromArray( pos );
  7164. if ( quat ) {
  7165. object.quaternion.fromArray( quat );
  7166. } else {
  7167. object.rotation.fromArray( rot );
  7168. }
  7169. object.scale.fromArray( scl );
  7170. }
  7171. object.visible = objJSON.visible;
  7172. object.castShadow = objJSON.castShadow;
  7173. object.receiveShadow = objJSON.receiveShadow;
  7174. parent.add( object );
  7175. result.objects[ objID ] = object;
  7176. }
  7177. // lights
  7178. } else if ( objJSON.type === "AmbientLight" || objJSON.type === "PointLight" ||
  7179. objJSON.type === "DirectionalLight" || objJSON.type === "SpotLight" ||
  7180. objJSON.type === "HemisphereLight" || objJSON.type === "AreaLight" ) {
  7181. var color = objJSON.color;
  7182. var intensity = objJSON.intensity;
  7183. var distance = objJSON.distance;
  7184. var position = objJSON.position;
  7185. var rotation = objJSON.rotation;
  7186. switch ( objJSON.type ) {
  7187. case 'AmbientLight':
  7188. light = new THREE.AmbientLight( color );
  7189. break;
  7190. case 'PointLight':
  7191. light = new THREE.PointLight( color, intensity, distance );
  7192. light.position.fromArray( position );
  7193. break;
  7194. case 'DirectionalLight':
  7195. light = new THREE.DirectionalLight( color, intensity );
  7196. light.position.fromArray( objJSON.direction );
  7197. break;
  7198. case 'SpotLight':
  7199. light = new THREE.SpotLight( color, intensity, distance, 1 );
  7200. light.angle = objJSON.angle;
  7201. light.position.fromArray( position );
  7202. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  7203. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  7204. break;
  7205. case 'HemisphereLight':
  7206. light = new THREE.DirectionalLight( color, intensity, distance );
  7207. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  7208. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  7209. break;
  7210. case 'AreaLight':
  7211. light = new THREE.AreaLight(color, intensity);
  7212. light.position.fromArray( position );
  7213. light.width = objJSON.size;
  7214. light.height = objJSON.size_y;
  7215. break;
  7216. }
  7217. parent.add( light );
  7218. light.name = objID;
  7219. result.lights[ objID ] = light;
  7220. result.objects[ objID ] = light;
  7221. // cameras
  7222. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  7223. pos = objJSON.position;
  7224. rot = objJSON.rotation;
  7225. quat = objJSON.quaternion;
  7226. if ( objJSON.type === "PerspectiveCamera" ) {
  7227. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  7228. } else if ( objJSON.type === "OrthographicCamera" ) {
  7229. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  7230. }
  7231. camera.name = objID;
  7232. camera.position.fromArray( pos );
  7233. if ( quat !== undefined ) {
  7234. camera.quaternion.fromArray( quat );
  7235. } else if ( rot !== undefined ) {
  7236. camera.rotation.fromArray( rot );
  7237. }
  7238. parent.add( camera );
  7239. result.cameras[ objID ] = camera;
  7240. result.objects[ objID ] = camera;
  7241. // pure Object3D
  7242. } else {
  7243. pos = objJSON.position;
  7244. rot = objJSON.rotation;
  7245. scl = objJSON.scale;
  7246. quat = objJSON.quaternion;
  7247. object = new THREE.Object3D();
  7248. object.name = objID;
  7249. object.position.fromArray( pos );
  7250. if ( quat ) {
  7251. object.quaternion.fromArray( quat );
  7252. } else {
  7253. object.rotation.fromArray( rot );
  7254. }
  7255. object.scale.fromArray( scl );
  7256. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  7257. parent.add( object );
  7258. result.objects[ objID ] = object;
  7259. result.empties[ objID ] = object;
  7260. }
  7261. if ( object ) {
  7262. if ( objJSON.userData !== undefined ) {
  7263. for ( var key in objJSON.userData ) {
  7264. var value = objJSON.userData[ key ];
  7265. object.userData[ key ] = value;
  7266. }
  7267. }
  7268. if ( objJSON.groups !== undefined ) {
  7269. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  7270. var groupID = objJSON.groups[ i ];
  7271. if ( result.groups[ groupID ] === undefined ) {
  7272. result.groups[ groupID ] = [];
  7273. }
  7274. result.groups[ groupID ].push( objID );
  7275. }
  7276. }
  7277. }
  7278. }
  7279. if ( object !== undefined && objJSON.children !== undefined ) {
  7280. handle_children( object, objJSON.children );
  7281. }
  7282. }
  7283. };
  7284. function handle_mesh( geo, mat, id ) {
  7285. result.geometries[ id ] = geo;
  7286. result.face_materials[ id ] = mat;
  7287. handle_objects();
  7288. };
  7289. function handle_hierarchy( node, id, parent, material, obj ) {
  7290. var p = obj.position;
  7291. var r = obj.rotation;
  7292. var q = obj.quaternion;
  7293. var s = obj.scale;
  7294. node.position.fromArray( p );
  7295. if ( q ) {
  7296. node.quaternion.fromArray( q );
  7297. } else {
  7298. node.rotation.fromArray( r );
  7299. }
  7300. node.scale.fromArray( s );
  7301. // override children materials
  7302. // if object material was specified in JSON explicitly
  7303. if ( material ) {
  7304. node.traverse( function ( child ) {
  7305. child.material = material;
  7306. } );
  7307. }
  7308. // override children visibility
  7309. // with root node visibility as specified in JSON
  7310. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  7311. node.traverse( function ( child ) {
  7312. child.visible = visible;
  7313. } );
  7314. parent.add( node );
  7315. node.name = id;
  7316. result.objects[ id ] = node;
  7317. handle_objects();
  7318. };
  7319. function create_callback_geometry( id ) {
  7320. return function ( geo, mat ) {
  7321. geo.name = id;
  7322. handle_mesh( geo, mat, id );
  7323. counter_models -= 1;
  7324. scope.onLoadComplete();
  7325. async_callback_gate();
  7326. }
  7327. };
  7328. function create_callback_hierachy( id, parent, material, obj ) {
  7329. return function ( event ) {
  7330. var result;
  7331. // loaders which use EventDispatcher
  7332. if ( event.content ) {
  7333. result = event.content;
  7334. // ColladaLoader
  7335. } else if ( event.dae ) {
  7336. result = event.scene;
  7337. // UTF8Loader
  7338. } else {
  7339. result = event;
  7340. }
  7341. handle_hierarchy( result, id, parent, material, obj );
  7342. counter_models -= 1;
  7343. scope.onLoadComplete();
  7344. async_callback_gate();
  7345. }
  7346. };
  7347. function create_callback_embed( id ) {
  7348. return function ( geo, mat ) {
  7349. geo.name = id;
  7350. result.geometries[ id ] = geo;
  7351. result.face_materials[ id ] = mat;
  7352. }
  7353. };
  7354. function async_callback_gate() {
  7355. var progress = {
  7356. totalModels : total_models,
  7357. totalTextures : total_textures,
  7358. loadedModels : total_models - counter_models,
  7359. loadedTextures : total_textures - counter_textures
  7360. };
  7361. scope.callbackProgress( progress, result );
  7362. scope.onLoadProgress();
  7363. if ( counter_models === 0 && counter_textures === 0 ) {
  7364. finalize();
  7365. callbackFinished( result );
  7366. }
  7367. };
  7368. function finalize() {
  7369. // take care of targets which could be asynchronously loaded objects
  7370. for ( var i = 0; i < target_array.length; i ++ ) {
  7371. var ta = target_array[ i ];
  7372. var target = result.objects[ ta.targetName ];
  7373. if ( target ) {
  7374. ta.object.target = target;
  7375. } else {
  7376. // if there was error and target of specified name doesn't exist in the scene file
  7377. // create instead dummy target
  7378. // (target must be added to scene explicitly as parent is already added)
  7379. ta.object.target = new THREE.Object3D();
  7380. result.scene.add( ta.object.target );
  7381. }
  7382. ta.object.target.userData.targetInverse = ta.object;
  7383. }
  7384. };
  7385. var callbackTexture = function ( count ) {
  7386. counter_textures -= count;
  7387. async_callback_gate();
  7388. scope.onLoadComplete();
  7389. };
  7390. // must use this instead of just directly calling callbackTexture
  7391. // because of closure in the calling context loop
  7392. var generateTextureCallback = function ( count ) {
  7393. return function () {
  7394. callbackTexture( count );
  7395. };
  7396. };
  7397. function traverse_json_hierarchy( objJSON, callback ) {
  7398. callback( objJSON );
  7399. if ( objJSON.children !== undefined ) {
  7400. for ( var objChildID in objJSON.children ) {
  7401. traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
  7402. }
  7403. }
  7404. };
  7405. // first go synchronous elements
  7406. // fogs
  7407. var fogID, fogJSON;
  7408. for ( fogID in data.fogs ) {
  7409. fogJSON = data.fogs[ fogID ];
  7410. if ( fogJSON.type === "linear" ) {
  7411. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  7412. } else if ( fogJSON.type === "exp2" ) {
  7413. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  7414. }
  7415. color = fogJSON.color;
  7416. fog.color.setRGB( color[0], color[1], color[2] );
  7417. result.fogs[ fogID ] = fog;
  7418. }
  7419. // now come potentially asynchronous elements
  7420. // geometries
  7421. // count how many geometries will be loaded asynchronously
  7422. var geoID, geoJSON;
  7423. for ( geoID in data.geometries ) {
  7424. geoJSON = data.geometries[ geoID ];
  7425. if ( geoJSON.type in this.geometryHandlers ) {
  7426. counter_models += 1;
  7427. scope.onLoadStart();
  7428. }
  7429. }
  7430. // count how many hierarchies will be loaded asynchronously
  7431. for ( var objID in data.objects ) {
  7432. traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
  7433. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7434. counter_models += 1;
  7435. scope.onLoadStart();
  7436. }
  7437. });
  7438. }
  7439. total_models = counter_models;
  7440. for ( geoID in data.geometries ) {
  7441. geoJSON = data.geometries[ geoID ];
  7442. if ( geoJSON.type === "cube" ) {
  7443. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  7444. geometry.name = geoID;
  7445. result.geometries[ geoID ] = geometry;
  7446. } else if ( geoJSON.type === "plane" ) {
  7447. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  7448. geometry.name = geoID;
  7449. result.geometries[ geoID ] = geometry;
  7450. } else if ( geoJSON.type === "sphere" ) {
  7451. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  7452. geometry.name = geoID;
  7453. result.geometries[ geoID ] = geometry;
  7454. } else if ( geoJSON.type === "cylinder" ) {
  7455. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  7456. geometry.name = geoID;
  7457. result.geometries[ geoID ] = geometry;
  7458. } else if ( geoJSON.type === "torus" ) {
  7459. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  7460. geometry.name = geoID;
  7461. result.geometries[ geoID ] = geometry;
  7462. } else if ( geoJSON.type === "icosahedron" ) {
  7463. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  7464. geometry.name = geoID;
  7465. result.geometries[ geoID ] = geometry;
  7466. } else if ( geoJSON.type in this.geometryHandlers ) {
  7467. var loaderParameters = {};
  7468. for ( var parType in geoJSON ) {
  7469. if ( parType !== "type" && parType !== "url" ) {
  7470. loaderParameters[ parType ] = geoJSON[ parType ];
  7471. }
  7472. }
  7473. var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ];
  7474. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  7475. } else if ( geoJSON.type === "embedded" ) {
  7476. var modelJson = data.embeds[ geoJSON.id ],
  7477. texture_path = "";
  7478. // pass metadata along to jsonLoader so it knows the format version
  7479. modelJson.metadata = data.metadata;
  7480. if ( modelJson ) {
  7481. var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ];
  7482. var model = jsonLoader.parse( modelJson, texture_path );
  7483. create_callback_embed( geoID )( model.geometry, model.materials );
  7484. }
  7485. }
  7486. }
  7487. // textures
  7488. // count how many textures will be loaded asynchronously
  7489. var textureID, textureJSON;
  7490. for ( textureID in data.textures ) {
  7491. textureJSON = data.textures[ textureID ];
  7492. if ( textureJSON.url instanceof Array ) {
  7493. counter_textures += textureJSON.url.length;
  7494. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  7495. scope.onLoadStart();
  7496. }
  7497. } else {
  7498. counter_textures += 1;
  7499. scope.onLoadStart();
  7500. }
  7501. }
  7502. total_textures = counter_textures;
  7503. for ( textureID in data.textures ) {
  7504. textureJSON = data.textures[ textureID ];
  7505. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  7506. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  7507. }
  7508. if ( textureJSON.url instanceof Array ) {
  7509. var count = textureJSON.url.length;
  7510. var url_array = [];
  7511. for( var i = 0; i < count; i ++ ) {
  7512. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  7513. }
  7514. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  7515. if ( isCompressed ) {
  7516. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7517. } else {
  7518. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7519. }
  7520. } else {
  7521. var isCompressed = /\.dds$/i.test( textureJSON.url );
  7522. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  7523. var textureCallback = generateTextureCallback( 1 );
  7524. if ( isCompressed ) {
  7525. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  7526. } else {
  7527. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  7528. }
  7529. if ( THREE[ textureJSON.minFilter ] !== undefined )
  7530. texture.minFilter = THREE[ textureJSON.minFilter ];
  7531. if ( THREE[ textureJSON.magFilter ] !== undefined )
  7532. texture.magFilter = THREE[ textureJSON.magFilter ];
  7533. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  7534. if ( textureJSON.repeat ) {
  7535. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  7536. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  7537. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  7538. }
  7539. if ( textureJSON.offset ) {
  7540. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  7541. }
  7542. // handle wrap after repeat so that default repeat can be overriden
  7543. if ( textureJSON.wrap ) {
  7544. var wrapMap = {
  7545. "repeat": THREE.RepeatWrapping,
  7546. "mirror": THREE.MirroredRepeatWrapping
  7547. }
  7548. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  7549. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  7550. }
  7551. }
  7552. result.textures[ textureID ] = texture;
  7553. }
  7554. // materials
  7555. var matID, matJSON;
  7556. var parID;
  7557. for ( matID in data.materials ) {
  7558. matJSON = data.materials[ matID ];
  7559. for ( parID in matJSON.parameters ) {
  7560. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  7561. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  7562. } else if ( parID === "shading" ) {
  7563. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  7564. } else if ( parID === "side" ) {
  7565. if ( matJSON.parameters[ parID ] == "double" ) {
  7566. matJSON.parameters[ parID ] = THREE.DoubleSide;
  7567. } else if ( matJSON.parameters[ parID ] == "back" ) {
  7568. matJSON.parameters[ parID ] = THREE.BackSide;
  7569. } else {
  7570. matJSON.parameters[ parID ] = THREE.FrontSide;
  7571. }
  7572. } else if ( parID === "blending" ) {
  7573. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  7574. } else if ( parID === "combine" ) {
  7575. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  7576. } else if ( parID === "vertexColors" ) {
  7577. if ( matJSON.parameters[ parID ] == "face" ) {
  7578. matJSON.parameters[ parID ] = THREE.FaceColors;
  7579. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  7580. } else if ( matJSON.parameters[ parID ] ) {
  7581. matJSON.parameters[ parID ] = THREE.VertexColors;
  7582. }
  7583. } else if ( parID === "wrapRGB" ) {
  7584. var v3 = matJSON.parameters[ parID ];
  7585. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  7586. }
  7587. }
  7588. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  7589. matJSON.parameters.transparent = true;
  7590. }
  7591. if ( matJSON.parameters.normalMap ) {
  7592. var shader = THREE.ShaderLib[ "normalmap" ];
  7593. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  7594. var diffuse = matJSON.parameters.color;
  7595. var specular = matJSON.parameters.specular;
  7596. var ambient = matJSON.parameters.ambient;
  7597. var shininess = matJSON.parameters.shininess;
  7598. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  7599. if ( matJSON.parameters.normalScale ) {
  7600. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  7601. }
  7602. if ( matJSON.parameters.map ) {
  7603. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  7604. uniforms[ "enableDiffuse" ].value = true;
  7605. }
  7606. if ( matJSON.parameters.envMap ) {
  7607. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  7608. uniforms[ "enableReflection" ].value = true;
  7609. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  7610. }
  7611. if ( matJSON.parameters.lightMap ) {
  7612. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  7613. uniforms[ "enableAO" ].value = true;
  7614. }
  7615. if ( matJSON.parameters.specularMap ) {
  7616. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  7617. uniforms[ "enableSpecular" ].value = true;
  7618. }
  7619. if ( matJSON.parameters.displacementMap ) {
  7620. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  7621. uniforms[ "enableDisplacement" ].value = true;
  7622. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  7623. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  7624. }
  7625. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  7626. uniforms[ "uSpecularColor" ].value.setHex( specular );
  7627. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  7628. uniforms[ "uShininess" ].value = shininess;
  7629. if ( matJSON.parameters.opacity ) {
  7630. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  7631. }
  7632. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  7633. material = new THREE.ShaderMaterial( parameters );
  7634. } else {
  7635. material = new THREE[ matJSON.type ]( matJSON.parameters );
  7636. }
  7637. material.name = matID;
  7638. result.materials[ matID ] = material;
  7639. }
  7640. // second pass through all materials to initialize MeshFaceMaterials
  7641. // that could be referring to other materials out of order
  7642. for ( matID in data.materials ) {
  7643. matJSON = data.materials[ matID ];
  7644. if ( matJSON.parameters.materials ) {
  7645. var materialArray = [];
  7646. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  7647. var label = matJSON.parameters.materials[ i ];
  7648. materialArray.push( result.materials[ label ] );
  7649. }
  7650. result.materials[ matID ].materials = materialArray;
  7651. }
  7652. }
  7653. // objects ( synchronous init of procedural primitives )
  7654. handle_objects();
  7655. // defaults
  7656. if ( result.cameras && data.defaults.camera ) {
  7657. result.currentCamera = result.cameras[ data.defaults.camera ];
  7658. }
  7659. if ( result.fogs && data.defaults.fog ) {
  7660. result.scene.fog = result.fogs[ data.defaults.fog ];
  7661. }
  7662. // synchronous callback
  7663. scope.callbackSync( result );
  7664. // just in case there are no async elements
  7665. async_callback_gate();
  7666. }
  7667. }
  7668. /**
  7669. * @author mrdoob / http://mrdoob.com/
  7670. */
  7671. THREE.TextureLoader = function ( manager ) {
  7672. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7673. };
  7674. THREE.TextureLoader.prototype = {
  7675. constructor: THREE.TextureLoader,
  7676. load: function ( url, onLoad, onProgress, onError ) {
  7677. var scope = this;
  7678. var loader = new THREE.ImageLoader( scope.manager );
  7679. loader.setCrossOrigin( this.crossOrigin );
  7680. loader.load( url, function ( image ) {
  7681. var texture = new THREE.Texture( image );
  7682. texture.needsUpdate = true;
  7683. if ( onLoad !== undefined ) {
  7684. onLoad( texture );
  7685. }
  7686. } );
  7687. },
  7688. setCrossOrigin: function ( value ) {
  7689. this.crossOrigin = value;
  7690. }
  7691. };
  7692. /**
  7693. * @author mrdoob / http://mrdoob.com/
  7694. * @author alteredq / http://alteredqualia.com/
  7695. */
  7696. THREE.Material = function () {
  7697. this.id = THREE.MaterialIdCount ++;
  7698. this.uuid = THREE.Math.generateUUID();
  7699. this.name = '';
  7700. this.side = THREE.FrontSide;
  7701. this.opacity = 1;
  7702. this.transparent = false;
  7703. this.blending = THREE.NormalBlending;
  7704. this.blendSrc = THREE.SrcAlphaFactor;
  7705. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  7706. this.blendEquation = THREE.AddEquation;
  7707. this.depthTest = true;
  7708. this.depthWrite = true;
  7709. this.polygonOffset = false;
  7710. this.polygonOffsetFactor = 0;
  7711. this.polygonOffsetUnits = 0;
  7712. this.alphaTest = 0;
  7713. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  7714. this.visible = true;
  7715. this.needsUpdate = true;
  7716. };
  7717. THREE.Material.prototype = {
  7718. constructor: THREE.Material,
  7719. setValues: function ( values ) {
  7720. if ( values === undefined ) return;
  7721. for ( var key in values ) {
  7722. var newValue = values[ key ];
  7723. if ( newValue === undefined ) {
  7724. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  7725. continue;
  7726. }
  7727. if ( key in this ) {
  7728. var currentValue = this[ key ];
  7729. if ( currentValue instanceof THREE.Color ) {
  7730. currentValue.set( newValue );
  7731. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  7732. currentValue.copy( newValue );
  7733. } else if ( key == 'overdraw') {
  7734. // ensure overdraw is backwards-compatable with legacy boolean type
  7735. this[ key ] = Number(newValue);
  7736. } else {
  7737. this[ key ] = newValue;
  7738. }
  7739. }
  7740. }
  7741. },
  7742. clone: function ( material ) {
  7743. if ( material === undefined ) material = new THREE.Material();
  7744. material.name = this.name;
  7745. material.side = this.side;
  7746. material.opacity = this.opacity;
  7747. material.transparent = this.transparent;
  7748. material.blending = this.blending;
  7749. material.blendSrc = this.blendSrc;
  7750. material.blendDst = this.blendDst;
  7751. material.blendEquation = this.blendEquation;
  7752. material.depthTest = this.depthTest;
  7753. material.depthWrite = this.depthWrite;
  7754. material.polygonOffset = this.polygonOffset;
  7755. material.polygonOffsetFactor = this.polygonOffsetFactor;
  7756. material.polygonOffsetUnits = this.polygonOffsetUnits;
  7757. material.alphaTest = this.alphaTest;
  7758. material.overdraw = this.overdraw;
  7759. material.visible = this.visible;
  7760. return material;
  7761. },
  7762. dispose: function () {
  7763. this.dispatchEvent( { type: 'dispose' } );
  7764. }
  7765. };
  7766. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  7767. THREE.MaterialIdCount = 0;
  7768. /**
  7769. * @author mrdoob / http://mrdoob.com/
  7770. * @author alteredq / http://alteredqualia.com/
  7771. *
  7772. * parameters = {
  7773. * color: <hex>,
  7774. * opacity: <float>,
  7775. *
  7776. * blending: THREE.NormalBlending,
  7777. * depthTest: <bool>,
  7778. * depthWrite: <bool>,
  7779. *
  7780. * linewidth: <float>,
  7781. * linecap: "round",
  7782. * linejoin: "round",
  7783. *
  7784. * vertexColors: <bool>
  7785. *
  7786. * fog: <bool>
  7787. * }
  7788. */
  7789. THREE.LineBasicMaterial = function ( parameters ) {
  7790. THREE.Material.call( this );
  7791. this.color = new THREE.Color( 0xffffff );
  7792. this.linewidth = 1;
  7793. this.linecap = 'round';
  7794. this.linejoin = 'round';
  7795. this.vertexColors = false;
  7796. this.fog = true;
  7797. this.setValues( parameters );
  7798. };
  7799. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7800. THREE.LineBasicMaterial.prototype.clone = function () {
  7801. var material = new THREE.LineBasicMaterial();
  7802. THREE.Material.prototype.clone.call( this, material );
  7803. material.color.copy( this.color );
  7804. material.linewidth = this.linewidth;
  7805. material.linecap = this.linecap;
  7806. material.linejoin = this.linejoin;
  7807. material.vertexColors = this.vertexColors;
  7808. material.fog = this.fog;
  7809. return material;
  7810. };
  7811. /**
  7812. * @author alteredq / http://alteredqualia.com/
  7813. *
  7814. * parameters = {
  7815. * color: <hex>,
  7816. * opacity: <float>,
  7817. *
  7818. * blending: THREE.NormalBlending,
  7819. * depthTest: <bool>,
  7820. * depthWrite: <bool>,
  7821. *
  7822. * linewidth: <float>,
  7823. *
  7824. * scale: <float>,
  7825. * dashSize: <float>,
  7826. * gapSize: <float>,
  7827. *
  7828. * vertexColors: <bool>
  7829. *
  7830. * fog: <bool>
  7831. * }
  7832. */
  7833. THREE.LineDashedMaterial = function ( parameters ) {
  7834. THREE.Material.call( this );
  7835. this.color = new THREE.Color( 0xffffff );
  7836. this.linewidth = 1;
  7837. this.scale = 1;
  7838. this.dashSize = 3;
  7839. this.gapSize = 1;
  7840. this.vertexColors = false;
  7841. this.fog = true;
  7842. this.setValues( parameters );
  7843. };
  7844. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  7845. THREE.LineDashedMaterial.prototype.clone = function () {
  7846. var material = new THREE.LineDashedMaterial();
  7847. THREE.Material.prototype.clone.call( this, material );
  7848. material.color.copy( this.color );
  7849. material.linewidth = this.linewidth;
  7850. material.scale = this.scale;
  7851. material.dashSize = this.dashSize;
  7852. material.gapSize = this.gapSize;
  7853. material.vertexColors = this.vertexColors;
  7854. material.fog = this.fog;
  7855. return material;
  7856. };
  7857. /**
  7858. * @author mrdoob / http://mrdoob.com/
  7859. * @author alteredq / http://alteredqualia.com/
  7860. *
  7861. * parameters = {
  7862. * color: <hex>,
  7863. * opacity: <float>,
  7864. * map: new THREE.Texture( <Image> ),
  7865. *
  7866. * lightMap: new THREE.Texture( <Image> ),
  7867. *
  7868. * specularMap: new THREE.Texture( <Image> ),
  7869. *
  7870. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7871. * combine: THREE.Multiply,
  7872. * reflectivity: <float>,
  7873. * refractionRatio: <float>,
  7874. *
  7875. * shading: THREE.SmoothShading,
  7876. * blending: THREE.NormalBlending,
  7877. * depthTest: <bool>,
  7878. * depthWrite: <bool>,
  7879. *
  7880. * wireframe: <boolean>,
  7881. * wireframeLinewidth: <float>,
  7882. *
  7883. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7884. *
  7885. * skinning: <bool>,
  7886. * morphTargets: <bool>,
  7887. *
  7888. * fog: <bool>
  7889. * }
  7890. */
  7891. THREE.MeshBasicMaterial = function ( parameters ) {
  7892. THREE.Material.call( this );
  7893. this.color = new THREE.Color( 0xffffff ); // emissive
  7894. this.map = null;
  7895. this.lightMap = null;
  7896. this.specularMap = null;
  7897. this.envMap = null;
  7898. this.combine = THREE.MultiplyOperation;
  7899. this.reflectivity = 1;
  7900. this.refractionRatio = 0.98;
  7901. this.fog = true;
  7902. this.shading = THREE.SmoothShading;
  7903. this.wireframe = false;
  7904. this.wireframeLinewidth = 1;
  7905. this.wireframeLinecap = 'round';
  7906. this.wireframeLinejoin = 'round';
  7907. this.vertexColors = THREE.NoColors;
  7908. this.skinning = false;
  7909. this.morphTargets = false;
  7910. this.setValues( parameters );
  7911. };
  7912. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7913. THREE.MeshBasicMaterial.prototype.clone = function () {
  7914. var material = new THREE.MeshBasicMaterial();
  7915. THREE.Material.prototype.clone.call( this, material );
  7916. material.color.copy( this.color );
  7917. material.map = this.map;
  7918. material.lightMap = this.lightMap;
  7919. material.specularMap = this.specularMap;
  7920. material.envMap = this.envMap;
  7921. material.combine = this.combine;
  7922. material.reflectivity = this.reflectivity;
  7923. material.refractionRatio = this.refractionRatio;
  7924. material.fog = this.fog;
  7925. material.shading = this.shading;
  7926. material.wireframe = this.wireframe;
  7927. material.wireframeLinewidth = this.wireframeLinewidth;
  7928. material.wireframeLinecap = this.wireframeLinecap;
  7929. material.wireframeLinejoin = this.wireframeLinejoin;
  7930. material.vertexColors = this.vertexColors;
  7931. material.skinning = this.skinning;
  7932. material.morphTargets = this.morphTargets;
  7933. return material;
  7934. };
  7935. /**
  7936. * @author mrdoob / http://mrdoob.com/
  7937. * @author alteredq / http://alteredqualia.com/
  7938. *
  7939. * parameters = {
  7940. * color: <hex>,
  7941. * ambient: <hex>,
  7942. * emissive: <hex>,
  7943. * opacity: <float>,
  7944. *
  7945. * map: new THREE.Texture( <Image> ),
  7946. *
  7947. * lightMap: new THREE.Texture( <Image> ),
  7948. *
  7949. * specularMap: new THREE.Texture( <Image> ),
  7950. *
  7951. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7952. * combine: THREE.Multiply,
  7953. * reflectivity: <float>,
  7954. * refractionRatio: <float>,
  7955. *
  7956. * shading: THREE.SmoothShading,
  7957. * blending: THREE.NormalBlending,
  7958. * depthTest: <bool>,
  7959. * depthWrite: <bool>,
  7960. *
  7961. * wireframe: <boolean>,
  7962. * wireframeLinewidth: <float>,
  7963. *
  7964. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7965. *
  7966. * skinning: <bool>,
  7967. * morphTargets: <bool>,
  7968. * morphNormals: <bool>,
  7969. *
  7970. * fog: <bool>
  7971. * }
  7972. */
  7973. THREE.MeshLambertMaterial = function ( parameters ) {
  7974. THREE.Material.call( this );
  7975. this.color = new THREE.Color( 0xffffff ); // diffuse
  7976. this.ambient = new THREE.Color( 0xffffff );
  7977. this.emissive = new THREE.Color( 0x000000 );
  7978. this.wrapAround = false;
  7979. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7980. this.map = null;
  7981. this.lightMap = null;
  7982. this.specularMap = null;
  7983. this.envMap = null;
  7984. this.combine = THREE.MultiplyOperation;
  7985. this.reflectivity = 1;
  7986. this.refractionRatio = 0.98;
  7987. this.fog = true;
  7988. this.shading = THREE.SmoothShading;
  7989. this.wireframe = false;
  7990. this.wireframeLinewidth = 1;
  7991. this.wireframeLinecap = 'round';
  7992. this.wireframeLinejoin = 'round';
  7993. this.vertexColors = THREE.NoColors;
  7994. this.skinning = false;
  7995. this.morphTargets = false;
  7996. this.morphNormals = false;
  7997. this.setValues( parameters );
  7998. };
  7999. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  8000. THREE.MeshLambertMaterial.prototype.clone = function () {
  8001. var material = new THREE.MeshLambertMaterial();
  8002. THREE.Material.prototype.clone.call( this, material );
  8003. material.color.copy( this.color );
  8004. material.ambient.copy( this.ambient );
  8005. material.emissive.copy( this.emissive );
  8006. material.wrapAround = this.wrapAround;
  8007. material.wrapRGB.copy( this.wrapRGB );
  8008. material.map = this.map;
  8009. material.lightMap = this.lightMap;
  8010. material.specularMap = this.specularMap;
  8011. material.envMap = this.envMap;
  8012. material.combine = this.combine;
  8013. material.reflectivity = this.reflectivity;
  8014. material.refractionRatio = this.refractionRatio;
  8015. material.fog = this.fog;
  8016. material.shading = this.shading;
  8017. material.wireframe = this.wireframe;
  8018. material.wireframeLinewidth = this.wireframeLinewidth;
  8019. material.wireframeLinecap = this.wireframeLinecap;
  8020. material.wireframeLinejoin = this.wireframeLinejoin;
  8021. material.vertexColors = this.vertexColors;
  8022. material.skinning = this.skinning;
  8023. material.morphTargets = this.morphTargets;
  8024. material.morphNormals = this.morphNormals;
  8025. return material;
  8026. };
  8027. /**
  8028. * @author mrdoob / http://mrdoob.com/
  8029. * @author alteredq / http://alteredqualia.com/
  8030. *
  8031. * parameters = {
  8032. * color: <hex>,
  8033. * ambient: <hex>,
  8034. * emissive: <hex>,
  8035. * specular: <hex>,
  8036. * shininess: <float>,
  8037. * opacity: <float>,
  8038. *
  8039. * map: new THREE.Texture( <Image> ),
  8040. *
  8041. * lightMap: new THREE.Texture( <Image> ),
  8042. *
  8043. * bumpMap: new THREE.Texture( <Image> ),
  8044. * bumpScale: <float>,
  8045. *
  8046. * normalMap: new THREE.Texture( <Image> ),
  8047. * normalScale: <Vector2>,
  8048. *
  8049. * specularMap: new THREE.Texture( <Image> ),
  8050. *
  8051. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8052. * combine: THREE.Multiply,
  8053. * reflectivity: <float>,
  8054. * refractionRatio: <float>,
  8055. *
  8056. * shading: THREE.SmoothShading,
  8057. * blending: THREE.NormalBlending,
  8058. * depthTest: <bool>,
  8059. * depthWrite: <bool>,
  8060. *
  8061. * wireframe: <boolean>,
  8062. * wireframeLinewidth: <float>,
  8063. *
  8064. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8065. *
  8066. * skinning: <bool>,
  8067. * morphTargets: <bool>,
  8068. * morphNormals: <bool>,
  8069. *
  8070. * fog: <bool>
  8071. * }
  8072. */
  8073. THREE.MeshPhongMaterial = function ( parameters ) {
  8074. THREE.Material.call( this );
  8075. this.color = new THREE.Color( 0xffffff ); // diffuse
  8076. this.ambient = new THREE.Color( 0xffffff );
  8077. this.emissive = new THREE.Color( 0x000000 );
  8078. this.specular = new THREE.Color( 0x111111 );
  8079. this.shininess = 30;
  8080. this.metal = false;
  8081. this.perPixel = true;
  8082. this.wrapAround = false;
  8083. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8084. this.map = null;
  8085. this.lightMap = null;
  8086. this.bumpMap = null;
  8087. this.bumpScale = 1;
  8088. this.normalMap = null;
  8089. this.normalScale = new THREE.Vector2( 1, 1 );
  8090. this.specularMap = null;
  8091. this.envMap = null;
  8092. this.combine = THREE.MultiplyOperation;
  8093. this.reflectivity = 1;
  8094. this.refractionRatio = 0.98;
  8095. this.fog = true;
  8096. this.shading = THREE.SmoothShading;
  8097. this.wireframe = false;
  8098. this.wireframeLinewidth = 1;
  8099. this.wireframeLinecap = 'round';
  8100. this.wireframeLinejoin = 'round';
  8101. this.vertexColors = THREE.NoColors;
  8102. this.skinning = false;
  8103. this.morphTargets = false;
  8104. this.morphNormals = false;
  8105. this.setValues( parameters );
  8106. };
  8107. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8108. THREE.MeshPhongMaterial.prototype.clone = function () {
  8109. var material = new THREE.MeshPhongMaterial();
  8110. THREE.Material.prototype.clone.call( this, material );
  8111. material.color.copy( this.color );
  8112. material.ambient.copy( this.ambient );
  8113. material.emissive.copy( this.emissive );
  8114. material.specular.copy( this.specular );
  8115. material.shininess = this.shininess;
  8116. material.metal = this.metal;
  8117. material.perPixel = this.perPixel;
  8118. material.wrapAround = this.wrapAround;
  8119. material.wrapRGB.copy( this.wrapRGB );
  8120. material.map = this.map;
  8121. material.lightMap = this.lightMap;
  8122. material.bumpMap = this.bumpMap;
  8123. material.bumpScale = this.bumpScale;
  8124. material.normalMap = this.normalMap;
  8125. material.normalScale.copy( this.normalScale );
  8126. material.specularMap = this.specularMap;
  8127. material.envMap = this.envMap;
  8128. material.combine = this.combine;
  8129. material.reflectivity = this.reflectivity;
  8130. material.refractionRatio = this.refractionRatio;
  8131. material.fog = this.fog;
  8132. material.shading = this.shading;
  8133. material.wireframe = this.wireframe;
  8134. material.wireframeLinewidth = this.wireframeLinewidth;
  8135. material.wireframeLinecap = this.wireframeLinecap;
  8136. material.wireframeLinejoin = this.wireframeLinejoin;
  8137. material.vertexColors = this.vertexColors;
  8138. material.skinning = this.skinning;
  8139. material.morphTargets = this.morphTargets;
  8140. material.morphNormals = this.morphNormals;
  8141. return material;
  8142. };
  8143. /**
  8144. * @author mrdoob / http://mrdoob.com/
  8145. * @author alteredq / http://alteredqualia.com/
  8146. *
  8147. * parameters = {
  8148. * opacity: <float>,
  8149. *
  8150. * blending: THREE.NormalBlending,
  8151. * depthTest: <bool>,
  8152. * depthWrite: <bool>,
  8153. *
  8154. * wireframe: <boolean>,
  8155. * wireframeLinewidth: <float>
  8156. * }
  8157. */
  8158. THREE.MeshDepthMaterial = function ( parameters ) {
  8159. THREE.Material.call( this );
  8160. this.wireframe = false;
  8161. this.wireframeLinewidth = 1;
  8162. this.setValues( parameters );
  8163. };
  8164. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  8165. THREE.MeshDepthMaterial.prototype.clone = function () {
  8166. var material = new THREE.MeshDepthMaterial();
  8167. THREE.Material.prototype.clone.call( this, material );
  8168. material.wireframe = this.wireframe;
  8169. material.wireframeLinewidth = this.wireframeLinewidth;
  8170. return material;
  8171. };
  8172. /**
  8173. * @author mrdoob / http://mrdoob.com/
  8174. *
  8175. * parameters = {
  8176. * opacity: <float>,
  8177. *
  8178. * shading: THREE.FlatShading,
  8179. * blending: THREE.NormalBlending,
  8180. * depthTest: <bool>,
  8181. * depthWrite: <bool>,
  8182. *
  8183. * wireframe: <boolean>,
  8184. * wireframeLinewidth: <float>
  8185. * }
  8186. */
  8187. THREE.MeshNormalMaterial = function ( parameters ) {
  8188. THREE.Material.call( this, parameters );
  8189. this.shading = THREE.FlatShading;
  8190. this.wireframe = false;
  8191. this.wireframeLinewidth = 1;
  8192. this.morphTargets = false;
  8193. this.setValues( parameters );
  8194. };
  8195. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  8196. THREE.MeshNormalMaterial.prototype.clone = function () {
  8197. var material = new THREE.MeshNormalMaterial();
  8198. THREE.Material.prototype.clone.call( this, material );
  8199. material.shading = this.shading;
  8200. material.wireframe = this.wireframe;
  8201. material.wireframeLinewidth = this.wireframeLinewidth;
  8202. return material;
  8203. };
  8204. /**
  8205. * @author mrdoob / http://mrdoob.com/
  8206. */
  8207. THREE.MeshFaceMaterial = function ( materials ) {
  8208. this.materials = materials instanceof Array ? materials : [];
  8209. };
  8210. THREE.MeshFaceMaterial.prototype.clone = function () {
  8211. var material = new THREE.MeshFaceMaterial();
  8212. for ( var i = 0; i < this.materials.length; i ++ ) {
  8213. material.materials.push( this.materials[ i ].clone() );
  8214. }
  8215. return material;
  8216. };
  8217. /**
  8218. * @author mrdoob / http://mrdoob.com/
  8219. * @author alteredq / http://alteredqualia.com/
  8220. *
  8221. * parameters = {
  8222. * color: <hex>,
  8223. * opacity: <float>,
  8224. * map: new THREE.Texture( <Image> ),
  8225. *
  8226. * size: <float>,
  8227. *
  8228. * blending: THREE.NormalBlending,
  8229. * depthTest: <bool>,
  8230. * depthWrite: <bool>,
  8231. *
  8232. * vertexColors: <bool>,
  8233. *
  8234. * fog: <bool>
  8235. * }
  8236. */
  8237. THREE.ParticleSystemMaterial = function ( parameters ) {
  8238. THREE.Material.call( this );
  8239. this.color = new THREE.Color( 0xffffff );
  8240. this.map = null;
  8241. this.size = 1;
  8242. this.sizeAttenuation = true;
  8243. this.vertexColors = false;
  8244. this.fog = true;
  8245. this.setValues( parameters );
  8246. };
  8247. THREE.ParticleSystemMaterial.prototype = Object.create( THREE.Material.prototype );
  8248. THREE.ParticleSystemMaterial.prototype.clone = function () {
  8249. var material = new THREE.ParticleSystemMaterial();
  8250. THREE.Material.prototype.clone.call( this, material );
  8251. material.color.copy( this.color );
  8252. material.map = this.map;
  8253. material.size = this.size;
  8254. material.sizeAttenuation = this.sizeAttenuation;
  8255. material.vertexColors = this.vertexColors;
  8256. material.fog = this.fog;
  8257. return material;
  8258. };
  8259. // backwards compatibility
  8260. THREE.ParticleBasicMaterial = THREE.ParticleSystemMaterial;
  8261. /**
  8262. * @author alteredq / http://alteredqualia.com/
  8263. *
  8264. * parameters = {
  8265. * fragmentShader: <string>,
  8266. * vertexShader: <string>,
  8267. *
  8268. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  8269. *
  8270. * defines: { "label" : "value" },
  8271. *
  8272. * shading: THREE.SmoothShading,
  8273. * blending: THREE.NormalBlending,
  8274. * depthTest: <bool>,
  8275. * depthWrite: <bool>,
  8276. *
  8277. * wireframe: <boolean>,
  8278. * wireframeLinewidth: <float>,
  8279. *
  8280. * lights: <bool>,
  8281. *
  8282. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8283. *
  8284. * skinning: <bool>,
  8285. * morphTargets: <bool>,
  8286. * morphNormals: <bool>,
  8287. *
  8288. * fog: <bool>
  8289. * }
  8290. */
  8291. THREE.ShaderMaterial = function ( parameters ) {
  8292. THREE.Material.call( this );
  8293. this.fragmentShader = "void main() {}";
  8294. this.vertexShader = "void main() {}";
  8295. this.uniforms = {};
  8296. this.defines = {};
  8297. this.attributes = null;
  8298. this.shading = THREE.SmoothShading;
  8299. this.linewidth = 1;
  8300. this.wireframe = false;
  8301. this.wireframeLinewidth = 1;
  8302. this.fog = false; // set to use scene fog
  8303. this.lights = false; // set to use scene lights
  8304. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  8305. this.skinning = false; // set to use skinning attribute streams
  8306. this.morphTargets = false; // set to use morph targets
  8307. this.morphNormals = false; // set to use morph normals
  8308. // When rendered geometry doesn't include these attributes but the material does,
  8309. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8310. this.defaultAttributeValues = {
  8311. "color" : [ 1, 1, 1],
  8312. "uv" : [ 0, 0 ],
  8313. "uv2" : [ 0, 0 ]
  8314. };
  8315. // By default, bind position to attribute index 0. In WebGL, attribute 0
  8316. // should always be used to avoid potentially expensive emulation.
  8317. this.index0AttributeName = "position";
  8318. this.setValues( parameters );
  8319. };
  8320. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  8321. THREE.ShaderMaterial.prototype.clone = function () {
  8322. var material = new THREE.ShaderMaterial();
  8323. THREE.Material.prototype.clone.call( this, material );
  8324. material.fragmentShader = this.fragmentShader;
  8325. material.vertexShader = this.vertexShader;
  8326. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  8327. material.attributes = this.attributes;
  8328. material.defines = this.defines;
  8329. material.shading = this.shading;
  8330. material.wireframe = this.wireframe;
  8331. material.wireframeLinewidth = this.wireframeLinewidth;
  8332. material.fog = this.fog;
  8333. material.lights = this.lights;
  8334. material.vertexColors = this.vertexColors;
  8335. material.skinning = this.skinning;
  8336. material.morphTargets = this.morphTargets;
  8337. material.morphNormals = this.morphNormals;
  8338. return material;
  8339. };
  8340. /**
  8341. * @author alteredq / http://alteredqualia.com/
  8342. *
  8343. * parameters = {
  8344. * color: <hex>,
  8345. * opacity: <float>,
  8346. * map: new THREE.Texture( <Image> ),
  8347. *
  8348. * blending: THREE.NormalBlending,
  8349. * depthTest: <bool>,
  8350. * depthWrite: <bool>,
  8351. *
  8352. * uvOffset: new THREE.Vector2(),
  8353. * uvScale: new THREE.Vector2(),
  8354. *
  8355. * fog: <bool>
  8356. * }
  8357. */
  8358. THREE.SpriteMaterial = function ( parameters ) {
  8359. THREE.Material.call( this );
  8360. // defaults
  8361. this.color = new THREE.Color( 0xffffff );
  8362. this.map = null;
  8363. this.rotation = 0;
  8364. this.fog = false;
  8365. this.uvOffset = new THREE.Vector2( 0, 0 );
  8366. this.uvScale = new THREE.Vector2( 1, 1 );
  8367. // set parameters
  8368. this.setValues( parameters );
  8369. };
  8370. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8371. THREE.SpriteMaterial.prototype.clone = function () {
  8372. var material = new THREE.SpriteMaterial();
  8373. THREE.Material.prototype.clone.call( this, material );
  8374. material.color.copy( this.color );
  8375. material.map = this.map;
  8376. material.rotation = this.rotation;
  8377. material.uvOffset.copy( this.uvOffset );
  8378. material.uvScale.copy( this.uvScale );
  8379. material.fog = this.fog;
  8380. return material;
  8381. };
  8382. /**
  8383. * @author mrdoob / http://mrdoob.com/
  8384. *
  8385. * parameters = {
  8386. * color: <hex>,
  8387. * program: <function>,
  8388. * opacity: <float>,
  8389. * blending: THREE.NormalBlending
  8390. * }
  8391. */
  8392. THREE.SpriteCanvasMaterial = function ( parameters ) {
  8393. THREE.Material.call( this );
  8394. this.color = new THREE.Color( 0xffffff );
  8395. this.program = function ( context, color ) {};
  8396. this.setValues( parameters );
  8397. };
  8398. THREE.SpriteCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  8399. THREE.SpriteCanvasMaterial.prototype.clone = function () {
  8400. var material = new THREE.SpriteCanvasMaterial();
  8401. THREE.Material.prototype.clone.call( this, material );
  8402. material.color.copy( this.color );
  8403. material.program = this.program;
  8404. return material;
  8405. };
  8406. // backwards compatibility
  8407. THREE.ParticleCanvasMaterial = THREE.SpriteCanvasMaterial;
  8408. /**
  8409. * @author mrdoob / http://mrdoob.com/
  8410. * @author alteredq / http://alteredqualia.com/
  8411. * @author szimek / https://github.com/szimek/
  8412. */
  8413. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8414. this.id = THREE.TextureIdCount ++;
  8415. this.uuid = THREE.Math.generateUUID();
  8416. this.name = '';
  8417. this.image = image;
  8418. this.mipmaps = [];
  8419. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  8420. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8421. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8422. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8423. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8424. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8425. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8426. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8427. this.offset = new THREE.Vector2( 0, 0 );
  8428. this.repeat = new THREE.Vector2( 1, 1 );
  8429. this.generateMipmaps = true;
  8430. this.premultiplyAlpha = false;
  8431. this.flipY = true;
  8432. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8433. this.needsUpdate = false;
  8434. this.onUpdate = null;
  8435. };
  8436. THREE.Texture.prototype = {
  8437. constructor: THREE.Texture,
  8438. clone: function ( texture ) {
  8439. if ( texture === undefined ) texture = new THREE.Texture();
  8440. texture.image = this.image;
  8441. texture.mipmaps = this.mipmaps.slice(0);
  8442. texture.mapping = this.mapping;
  8443. texture.wrapS = this.wrapS;
  8444. texture.wrapT = this.wrapT;
  8445. texture.magFilter = this.magFilter;
  8446. texture.minFilter = this.minFilter;
  8447. texture.anisotropy = this.anisotropy;
  8448. texture.format = this.format;
  8449. texture.type = this.type;
  8450. texture.offset.copy( this.offset );
  8451. texture.repeat.copy( this.repeat );
  8452. texture.generateMipmaps = this.generateMipmaps;
  8453. texture.premultiplyAlpha = this.premultiplyAlpha;
  8454. texture.flipY = this.flipY;
  8455. texture.unpackAlignment = this.unpackAlignment;
  8456. return texture;
  8457. },
  8458. dispose: function () {
  8459. this.dispatchEvent( { type: 'dispose' } );
  8460. }
  8461. };
  8462. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  8463. THREE.TextureIdCount = 0;
  8464. /**
  8465. * @author alteredq / http://alteredqualia.com/
  8466. */
  8467. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8468. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8469. this.image = { width: width, height: height };
  8470. this.mipmaps = mipmaps;
  8471. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  8472. };
  8473. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8474. THREE.CompressedTexture.prototype.clone = function () {
  8475. var texture = new THREE.CompressedTexture();
  8476. THREE.Texture.prototype.clone.call( this, texture );
  8477. return texture;
  8478. };
  8479. /**
  8480. * @author alteredq / http://alteredqualia.com/
  8481. */
  8482. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8483. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8484. this.image = { data: data, width: width, height: height };
  8485. };
  8486. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8487. THREE.DataTexture.prototype.clone = function () {
  8488. var texture = new THREE.DataTexture();
  8489. THREE.Texture.prototype.clone.call( this, texture );
  8490. return texture;
  8491. };
  8492. /**
  8493. * @author alteredq / http://alteredqualia.com/
  8494. */
  8495. THREE.ParticleSystem = function ( geometry, material ) {
  8496. THREE.Object3D.call( this );
  8497. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8498. this.material = material !== undefined ? material : new THREE.ParticleSystemMaterial( { color: Math.random() * 0xffffff } );
  8499. this.sortParticles = false;
  8500. this.frustumCulled = false;
  8501. };
  8502. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  8503. THREE.ParticleSystem.prototype.clone = function ( object ) {
  8504. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  8505. object.sortParticles = this.sortParticles;
  8506. THREE.Object3D.prototype.clone.call( this, object );
  8507. return object;
  8508. };
  8509. /**
  8510. * @author mrdoob / http://mrdoob.com/
  8511. */
  8512. THREE.Line = function ( geometry, material, type ) {
  8513. THREE.Object3D.call( this );
  8514. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8515. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  8516. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  8517. };
  8518. THREE.LineStrip = 0;
  8519. THREE.LinePieces = 1;
  8520. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  8521. THREE.Line.prototype.clone = function ( object ) {
  8522. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  8523. THREE.Object3D.prototype.clone.call( this, object );
  8524. return object;
  8525. };
  8526. /**
  8527. * @author mrdoob / http://mrdoob.com/
  8528. * @author alteredq / http://alteredqualia.com/
  8529. * @author mikael emtinger / http://gomo.se/
  8530. * @author jonobr1 / http://jonobr1.com/
  8531. */
  8532. THREE.Mesh = function ( geometry, material ) {
  8533. THREE.Object3D.call( this );
  8534. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8535. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  8536. this.updateMorphTargets();
  8537. };
  8538. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  8539. THREE.Mesh.prototype.updateMorphTargets = function () {
  8540. if ( this.geometry.morphTargets.length > 0 ) {
  8541. this.morphTargetBase = -1;
  8542. this.morphTargetForcedOrder = [];
  8543. this.morphTargetInfluences = [];
  8544. this.morphTargetDictionary = {};
  8545. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  8546. this.morphTargetInfluences.push( 0 );
  8547. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  8548. }
  8549. }
  8550. };
  8551. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  8552. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  8553. return this.morphTargetDictionary[ name ];
  8554. }
  8555. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  8556. return 0;
  8557. };
  8558. THREE.Mesh.prototype.clone = function ( object ) {
  8559. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  8560. THREE.Object3D.prototype.clone.call( this, object );
  8561. return object;
  8562. };
  8563. /**
  8564. * @author mikael emtinger / http://gomo.se/
  8565. * @author alteredq / http://alteredqualia.com/
  8566. */
  8567. THREE.Bone = function( belongsToSkin ) {
  8568. THREE.Object3D.call( this );
  8569. this.skin = belongsToSkin;
  8570. this.skinMatrix = new THREE.Matrix4();
  8571. };
  8572. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  8573. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  8574. // update local
  8575. if ( this.matrixAutoUpdate ) {
  8576. forceUpdate |= this.updateMatrix();
  8577. }
  8578. // update skin matrix
  8579. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  8580. if( parentSkinMatrix ) {
  8581. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  8582. } else {
  8583. this.skinMatrix.copy( this.matrix );
  8584. }
  8585. this.matrixWorldNeedsUpdate = false;
  8586. forceUpdate = true;
  8587. }
  8588. // update children
  8589. var child, i, l = this.children.length;
  8590. for ( i = 0; i < l; i ++ ) {
  8591. this.children[ i ].update( this.skinMatrix, forceUpdate );
  8592. }
  8593. };
  8594. /**
  8595. * @author mikael emtinger / http://gomo.se/
  8596. * @author alteredq / http://alteredqualia.com/
  8597. */
  8598. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  8599. THREE.Mesh.call( this, geometry, material );
  8600. //
  8601. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  8602. // init bones
  8603. this.identityMatrix = new THREE.Matrix4();
  8604. this.bones = [];
  8605. this.boneMatrices = [];
  8606. var b, bone, gbone, p, q, s;
  8607. if ( this.geometry && this.geometry.bones !== undefined ) {
  8608. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  8609. gbone = this.geometry.bones[ b ];
  8610. p = gbone.pos;
  8611. q = gbone.rotq;
  8612. s = gbone.scl;
  8613. bone = this.addBone();
  8614. bone.name = gbone.name;
  8615. bone.position.set( p[0], p[1], p[2] );
  8616. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  8617. if ( s !== undefined ) {
  8618. bone.scale.set( s[0], s[1], s[2] );
  8619. } else {
  8620. bone.scale.set( 1, 1, 1 );
  8621. }
  8622. }
  8623. for ( b = 0; b < this.bones.length; b ++ ) {
  8624. gbone = this.geometry.bones[ b ];
  8625. bone = this.bones[ b ];
  8626. if ( gbone.parent === -1 ) {
  8627. this.add( bone );
  8628. } else {
  8629. this.bones[ gbone.parent ].add( bone );
  8630. }
  8631. }
  8632. //
  8633. var nBones = this.bones.length;
  8634. if ( this.useVertexTexture ) {
  8635. // layout (1 matrix = 4 pixels)
  8636. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8637. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  8638. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  8639. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  8640. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  8641. var size;
  8642. if ( nBones > 256 )
  8643. size = 64;
  8644. else if ( nBones > 64 )
  8645. size = 32;
  8646. else if ( nBones > 16 )
  8647. size = 16;
  8648. else
  8649. size = 8;
  8650. this.boneTextureWidth = size;
  8651. this.boneTextureHeight = size;
  8652. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  8653. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  8654. this.boneTexture.minFilter = THREE.NearestFilter;
  8655. this.boneTexture.magFilter = THREE.NearestFilter;
  8656. this.boneTexture.generateMipmaps = false;
  8657. this.boneTexture.flipY = false;
  8658. } else {
  8659. this.boneMatrices = new Float32Array( 16 * nBones );
  8660. }
  8661. this.pose();
  8662. }
  8663. };
  8664. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  8665. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  8666. if ( bone === undefined ) {
  8667. bone = new THREE.Bone( this );
  8668. }
  8669. this.bones.push( bone );
  8670. return bone;
  8671. };
  8672. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  8673. var offsetMatrix = new THREE.Matrix4();
  8674. return function ( force ) {
  8675. this.matrixAutoUpdate && this.updateMatrix();
  8676. // update matrixWorld
  8677. if ( this.matrixWorldNeedsUpdate || force ) {
  8678. if ( this.parent ) {
  8679. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8680. } else {
  8681. this.matrixWorld.copy( this.matrix );
  8682. }
  8683. this.matrixWorldNeedsUpdate = false;
  8684. force = true;
  8685. }
  8686. // update children
  8687. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8688. var child = this.children[ i ];
  8689. if ( child instanceof THREE.Bone ) {
  8690. child.update( this.identityMatrix, false );
  8691. } else {
  8692. child.updateMatrixWorld( true );
  8693. }
  8694. }
  8695. // make a snapshot of the bones' rest position
  8696. if ( this.boneInverses == undefined ) {
  8697. this.boneInverses = [];
  8698. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8699. var inverse = new THREE.Matrix4();
  8700. inverse.getInverse( this.bones[ b ].skinMatrix );
  8701. this.boneInverses.push( inverse );
  8702. }
  8703. }
  8704. // flatten bone matrices to array
  8705. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8706. // compute the offset between the current and the original transform;
  8707. // TODO: we could get rid of this multiplication step if the skinMatrix
  8708. // was already representing the offset; however, this requires some
  8709. // major changes to the animation system
  8710. offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  8711. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  8712. }
  8713. if ( this.useVertexTexture ) {
  8714. this.boneTexture.needsUpdate = true;
  8715. }
  8716. };
  8717. }();
  8718. THREE.SkinnedMesh.prototype.pose = function () {
  8719. this.updateMatrixWorld( true );
  8720. this.normalizeSkinWeights();
  8721. };
  8722. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  8723. if ( this.geometry instanceof THREE.Geometry ) {
  8724. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  8725. var sw = this.geometry.skinWeights[ i ];
  8726. var scale = 1.0 / sw.lengthManhattan();
  8727. if ( scale !== Infinity ) {
  8728. sw.multiplyScalar( scale );
  8729. } else {
  8730. sw.set( 1 ); // this will be normalized by the shader anyway
  8731. }
  8732. }
  8733. } else {
  8734. // skinning weights assumed to be normalized for THREE.BufferGeometry
  8735. }
  8736. };
  8737. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  8738. if ( object === undefined ) {
  8739. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  8740. }
  8741. THREE.Mesh.prototype.clone.call( this, object );
  8742. return object;
  8743. };
  8744. /**
  8745. * @author alteredq / http://alteredqualia.com/
  8746. */
  8747. THREE.MorphAnimMesh = function ( geometry, material ) {
  8748. THREE.Mesh.call( this, geometry, material );
  8749. // API
  8750. this.duration = 1000; // milliseconds
  8751. this.mirroredLoop = false;
  8752. this.time = 0;
  8753. // internals
  8754. this.lastKeyframe = 0;
  8755. this.currentKeyframe = 0;
  8756. this.direction = 1;
  8757. this.directionBackwards = false;
  8758. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  8759. };
  8760. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  8761. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  8762. this.startKeyframe = start;
  8763. this.endKeyframe = end;
  8764. this.length = this.endKeyframe - this.startKeyframe + 1;
  8765. };
  8766. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  8767. this.direction = 1;
  8768. this.directionBackwards = false;
  8769. };
  8770. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  8771. this.direction = -1;
  8772. this.directionBackwards = true;
  8773. };
  8774. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  8775. var geometry = this.geometry;
  8776. if ( ! geometry.animations ) geometry.animations = {};
  8777. var firstAnimation, animations = geometry.animations;
  8778. var pattern = /([a-z]+)(\d+)/;
  8779. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  8780. var morph = geometry.morphTargets[ i ];
  8781. var parts = morph.name.match( pattern );
  8782. if ( parts && parts.length > 1 ) {
  8783. var label = parts[ 1 ];
  8784. var num = parts[ 2 ];
  8785. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  8786. var animation = animations[ label ];
  8787. if ( i < animation.start ) animation.start = i;
  8788. if ( i > animation.end ) animation.end = i;
  8789. if ( ! firstAnimation ) firstAnimation = label;
  8790. }
  8791. }
  8792. geometry.firstAnimation = firstAnimation;
  8793. };
  8794. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  8795. if ( ! this.geometry.animations ) this.geometry.animations = {};
  8796. this.geometry.animations[ label ] = { start: start, end: end };
  8797. };
  8798. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  8799. var animation = this.geometry.animations[ label ];
  8800. if ( animation ) {
  8801. this.setFrameRange( animation.start, animation.end );
  8802. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  8803. this.time = 0;
  8804. } else {
  8805. console.warn( "animation[" + label + "] undefined" );
  8806. }
  8807. };
  8808. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  8809. var frameTime = this.duration / this.length;
  8810. this.time += this.direction * delta;
  8811. if ( this.mirroredLoop ) {
  8812. if ( this.time > this.duration || this.time < 0 ) {
  8813. this.direction *= -1;
  8814. if ( this.time > this.duration ) {
  8815. this.time = this.duration;
  8816. this.directionBackwards = true;
  8817. }
  8818. if ( this.time < 0 ) {
  8819. this.time = 0;
  8820. this.directionBackwards = false;
  8821. }
  8822. }
  8823. } else {
  8824. this.time = this.time % this.duration;
  8825. if ( this.time < 0 ) this.time += this.duration;
  8826. }
  8827. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  8828. if ( keyframe !== this.currentKeyframe ) {
  8829. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  8830. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  8831. this.morphTargetInfluences[ keyframe ] = 0;
  8832. this.lastKeyframe = this.currentKeyframe;
  8833. this.currentKeyframe = keyframe;
  8834. }
  8835. var mix = ( this.time % frameTime ) / frameTime;
  8836. if ( this.directionBackwards ) {
  8837. mix = 1 - mix;
  8838. }
  8839. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  8840. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  8841. };
  8842. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  8843. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  8844. object.duration = this.duration;
  8845. object.mirroredLoop = this.mirroredLoop;
  8846. object.time = this.time;
  8847. object.lastKeyframe = this.lastKeyframe;
  8848. object.currentKeyframe = this.currentKeyframe;
  8849. object.direction = this.direction;
  8850. object.directionBackwards = this.directionBackwards;
  8851. THREE.Mesh.prototype.clone.call( this, object );
  8852. return object;
  8853. };
  8854. /**
  8855. * @author mikael emtinger / http://gomo.se/
  8856. * @author alteredq / http://alteredqualia.com/
  8857. * @author mrdoob / http://mrdoob.com/
  8858. */
  8859. THREE.LOD = function () {
  8860. THREE.Object3D.call( this );
  8861. this.objects = [];
  8862. };
  8863. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  8864. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  8865. if ( distance === undefined ) distance = 0;
  8866. distance = Math.abs( distance );
  8867. for ( var l = 0; l < this.objects.length; l ++ ) {
  8868. if ( distance < this.objects[ l ].distance ) {
  8869. break;
  8870. }
  8871. }
  8872. this.objects.splice( l, 0, { distance: distance, object: object } );
  8873. this.add( object );
  8874. };
  8875. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  8876. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8877. if ( distance < this.objects[ i ].distance ) {
  8878. break;
  8879. }
  8880. }
  8881. return this.objects[ i - 1 ].object;
  8882. };
  8883. THREE.LOD.prototype.update = function () {
  8884. var v1 = new THREE.Vector3();
  8885. var v2 = new THREE.Vector3();
  8886. return function ( camera ) {
  8887. if ( this.objects.length > 1 ) {
  8888. v1.setFromMatrixPosition( camera.matrixWorld );
  8889. v2.setFromMatrixPosition( this.matrixWorld );
  8890. var distance = v1.distanceTo( v2 );
  8891. this.objects[ 0 ].object.visible = true;
  8892. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8893. if ( distance >= this.objects[ i ].distance ) {
  8894. this.objects[ i - 1 ].object.visible = false;
  8895. this.objects[ i ].object.visible = true;
  8896. } else {
  8897. break;
  8898. }
  8899. }
  8900. for( ; i < l; i ++ ) {
  8901. this.objects[ i ].object.visible = false;
  8902. }
  8903. }
  8904. };
  8905. }();
  8906. THREE.LOD.prototype.clone = function () {
  8907. // TODO
  8908. };
  8909. /**
  8910. * @author mikael emtinger / http://gomo.se/
  8911. * @author alteredq / http://alteredqualia.com/
  8912. */
  8913. THREE.Sprite = function ( material ) {
  8914. THREE.Object3D.call( this );
  8915. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  8916. };
  8917. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  8918. /*
  8919. * Custom update matrix
  8920. */
  8921. THREE.Sprite.prototype.updateMatrix = function () {
  8922. this.matrix.compose( this.position, this.quaternion, this.scale );
  8923. this.matrixWorldNeedsUpdate = true;
  8924. };
  8925. THREE.Sprite.prototype.clone = function ( object ) {
  8926. if ( object === undefined ) object = new THREE.Sprite( this.material );
  8927. THREE.Object3D.prototype.clone.call( this, object );
  8928. return object;
  8929. };
  8930. // Backwards compatibility
  8931. THREE.Particle = THREE.Sprite;
  8932. /**
  8933. * @author mrdoob / http://mrdoob.com/
  8934. */
  8935. THREE.Scene = function () {
  8936. THREE.Object3D.call( this );
  8937. this.fog = null;
  8938. this.overrideMaterial = null;
  8939. this.autoUpdate = true; // checked by the renderer
  8940. this.matrixAutoUpdate = false;
  8941. this.__lights = [];
  8942. this.__objectsAdded = [];
  8943. this.__objectsRemoved = [];
  8944. };
  8945. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  8946. THREE.Scene.prototype.__addObject = function ( object ) {
  8947. if ( object instanceof THREE.Light ) {
  8948. if ( this.__lights.indexOf( object ) === - 1 ) {
  8949. this.__lights.push( object );
  8950. }
  8951. if ( object.target && object.target.parent === undefined ) {
  8952. this.add( object.target );
  8953. }
  8954. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  8955. this.__objectsAdded.push( object );
  8956. // check if previously removed
  8957. var i = this.__objectsRemoved.indexOf( object );
  8958. if ( i !== -1 ) {
  8959. this.__objectsRemoved.splice( i, 1 );
  8960. }
  8961. }
  8962. this.dispatchEvent( { type: 'objectAdded', object: object } );
  8963. object.dispatchEvent( { type: 'addedToScene', scene: this } );
  8964. for ( var c = 0; c < object.children.length; c ++ ) {
  8965. this.__addObject( object.children[ c ] );
  8966. }
  8967. };
  8968. THREE.Scene.prototype.__removeObject = function ( object ) {
  8969. if ( object instanceof THREE.Light ) {
  8970. var i = this.__lights.indexOf( object );
  8971. if ( i !== -1 ) {
  8972. this.__lights.splice( i, 1 );
  8973. }
  8974. if ( object.shadowCascadeArray ) {
  8975. for ( var x = 0; x < object.shadowCascadeArray.length; x ++ ) {
  8976. this.__removeObject( object.shadowCascadeArray[ x ] );
  8977. }
  8978. }
  8979. } else if ( !( object instanceof THREE.Camera ) ) {
  8980. this.__objectsRemoved.push( object );
  8981. // check if previously added
  8982. var i = this.__objectsAdded.indexOf( object );
  8983. if ( i !== -1 ) {
  8984. this.__objectsAdded.splice( i, 1 );
  8985. }
  8986. }
  8987. this.dispatchEvent( { type: 'objectRemoved', object: object } );
  8988. object.dispatchEvent( { type: 'removedFromScene', scene: this } );
  8989. for ( var c = 0; c < object.children.length; c ++ ) {
  8990. this.__removeObject( object.children[ c ] );
  8991. }
  8992. };
  8993. THREE.Scene.prototype.clone = function ( object ) {
  8994. if ( object === undefined ) object = new THREE.Scene();
  8995. THREE.Object3D.prototype.clone.call(this, object);
  8996. if ( this.fog !== null ) object.fog = this.fog.clone();
  8997. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  8998. object.autoUpdate = this.autoUpdate;
  8999. object.matrixAutoUpdate = this.matrixAutoUpdate;
  9000. return object;
  9001. };
  9002. /**
  9003. * @author mrdoob / http://mrdoob.com/
  9004. * @author alteredq / http://alteredqualia.com/
  9005. */
  9006. THREE.Fog = function ( hex, near, far ) {
  9007. this.name = '';
  9008. this.color = new THREE.Color( hex );
  9009. this.near = ( near !== undefined ) ? near : 1;
  9010. this.far = ( far !== undefined ) ? far : 1000;
  9011. };
  9012. THREE.Fog.prototype.clone = function () {
  9013. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  9014. };
  9015. /**
  9016. * @author mrdoob / http://mrdoob.com/
  9017. * @author alteredq / http://alteredqualia.com/
  9018. */
  9019. THREE.FogExp2 = function ( hex, density ) {
  9020. this.name = '';
  9021. this.color = new THREE.Color( hex );
  9022. this.density = ( density !== undefined ) ? density : 0.00025;
  9023. };
  9024. THREE.FogExp2.prototype.clone = function () {
  9025. return new THREE.FogExp2( this.color.getHex(), this.density );
  9026. };
  9027. /**
  9028. * @author mrdoob / http://mrdoob.com/
  9029. */
  9030. THREE.CanvasRenderer = function ( parameters ) {
  9031. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  9032. var smoothstep = THREE.Math.smoothstep;
  9033. parameters = parameters || {};
  9034. var _this = this,
  9035. _renderData, _elements, _lights,
  9036. _projector = new THREE.Projector(),
  9037. _canvas = parameters.canvas !== undefined
  9038. ? parameters.canvas
  9039. : document.createElement( 'canvas' ),
  9040. _canvasWidth = _canvas.width,
  9041. _canvasHeight = _canvas.height,
  9042. _canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
  9043. _canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
  9044. _context = _canvas.getContext( '2d' ),
  9045. _clearColor = new THREE.Color( 0x000000 ),
  9046. _clearAlpha = 0,
  9047. _contextGlobalAlpha = 1,
  9048. _contextGlobalCompositeOperation = 0,
  9049. _contextStrokeStyle = null,
  9050. _contextFillStyle = null,
  9051. _contextLineWidth = null,
  9052. _contextLineCap = null,
  9053. _contextLineJoin = null,
  9054. _contextDashSize = null,
  9055. _contextGapSize = 0,
  9056. _camera,
  9057. _v1, _v2, _v3, _v4,
  9058. _v5 = new THREE.RenderableVertex(),
  9059. _v6 = new THREE.RenderableVertex(),
  9060. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  9061. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  9062. _color = new THREE.Color(),
  9063. _color1 = new THREE.Color(),
  9064. _color2 = new THREE.Color(),
  9065. _color3 = new THREE.Color(),
  9066. _color4 = new THREE.Color(),
  9067. _diffuseColor = new THREE.Color(),
  9068. _emissiveColor = new THREE.Color(),
  9069. _lightColor = new THREE.Color(),
  9070. _patterns = {}, _imagedatas = {},
  9071. _near, _far,
  9072. _image, _uvs,
  9073. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  9074. _clipBox = new THREE.Box2(),
  9075. _clearBox = new THREE.Box2(),
  9076. _elemBox = new THREE.Box2(),
  9077. _ambientLight = new THREE.Color(),
  9078. _directionalLights = new THREE.Color(),
  9079. _pointLights = new THREE.Color(),
  9080. _vector3 = new THREE.Vector3(), // Needed for PointLight
  9081. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  9082. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  9083. _pixelMap = document.createElement( 'canvas' );
  9084. _pixelMap.width = _pixelMap.height = 2;
  9085. _pixelMapContext = _pixelMap.getContext( '2d' );
  9086. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  9087. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  9088. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  9089. _pixelMapData = _pixelMapImage.data;
  9090. _gradientMap = document.createElement( 'canvas' );
  9091. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  9092. _gradientMapContext = _gradientMap.getContext( '2d' );
  9093. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  9094. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  9095. _gradientMapQuality --; // Fix UVs
  9096. // dash+gap fallbacks for Firefox and everything else
  9097. if ( _context.setLineDash === undefined ) {
  9098. if ( _context.mozDash !== undefined ) {
  9099. _context.setLineDash = function ( values ) {
  9100. _context.mozDash = values[ 0 ] !== null ? values : null;
  9101. }
  9102. } else {
  9103. _context.setLineDash = function () {}
  9104. }
  9105. }
  9106. this.domElement = _canvas;
  9107. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  9108. ? parameters.devicePixelRatio
  9109. : self.devicePixelRatio !== undefined
  9110. ? self.devicePixelRatio
  9111. : 1;
  9112. this.autoClear = true;
  9113. this.sortObjects = true;
  9114. this.sortElements = true;
  9115. this.info = {
  9116. render: {
  9117. vertices: 0,
  9118. faces: 0
  9119. }
  9120. }
  9121. // WebGLRenderer compatibility
  9122. this.supportsVertexTextures = function () {};
  9123. this.setFaceCulling = function () {};
  9124. this.setSize = function ( width, height, updateStyle ) {
  9125. _canvasWidth = width * this.devicePixelRatio;
  9126. _canvasHeight = height * this.devicePixelRatio;
  9127. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  9128. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  9129. _canvas.width = _canvasWidth;
  9130. _canvas.height = _canvasHeight;
  9131. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  9132. _canvas.style.width = width + 'px';
  9133. _canvas.style.height = height + 'px';
  9134. }
  9135. _clipBox.set(
  9136. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  9137. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  9138. );
  9139. _clearBox.set(
  9140. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  9141. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  9142. );
  9143. _contextGlobalAlpha = 1;
  9144. _contextGlobalCompositeOperation = 0;
  9145. _contextStrokeStyle = null;
  9146. _contextFillStyle = null;
  9147. _contextLineWidth = null;
  9148. _contextLineCap = null;
  9149. _contextLineJoin = null;
  9150. };
  9151. this.setClearColor = function ( color, alpha ) {
  9152. _clearColor.set( color );
  9153. _clearAlpha = alpha !== undefined ? alpha : 1;
  9154. _clearBox.set(
  9155. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  9156. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  9157. );
  9158. };
  9159. this.setClearColorHex = function ( hex, alpha ) {
  9160. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  9161. this.setClearColor( hex, alpha );
  9162. };
  9163. this.getMaxAnisotropy = function () {
  9164. return 0;
  9165. };
  9166. this.clear = function () {
  9167. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  9168. if ( _clearBox.empty() === false ) {
  9169. _clearBox.intersect( _clipBox );
  9170. _clearBox.expandByScalar( 2 );
  9171. if ( _clearAlpha < 1 ) {
  9172. _context.clearRect(
  9173. _clearBox.min.x | 0,
  9174. _clearBox.min.y | 0,
  9175. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9176. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9177. );
  9178. }
  9179. if ( _clearAlpha > 0 ) {
  9180. setBlending( THREE.NormalBlending );
  9181. setOpacity( 1 );
  9182. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  9183. _context.fillRect(
  9184. _clearBox.min.x | 0,
  9185. _clearBox.min.y | 0,
  9186. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9187. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9188. );
  9189. }
  9190. _clearBox.makeEmpty();
  9191. }
  9192. };
  9193. // compatibility
  9194. this.clearColor = function () {};
  9195. this.clearDepth = function () {};
  9196. this.clearStencil = function () {};
  9197. this.render = function ( scene, camera ) {
  9198. if ( camera instanceof THREE.Camera === false ) {
  9199. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  9200. return;
  9201. }
  9202. if ( this.autoClear === true ) this.clear();
  9203. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  9204. _this.info.render.vertices = 0;
  9205. _this.info.render.faces = 0;
  9206. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  9207. _elements = _renderData.elements;
  9208. _lights = _renderData.lights;
  9209. _camera = camera;
  9210. /* DEBUG
  9211. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  9212. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  9213. */
  9214. calculateLights();
  9215. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  9216. var element = _elements[ e ];
  9217. var material = element.material;
  9218. if ( material === undefined || material.visible === false ) continue;
  9219. _elemBox.makeEmpty();
  9220. if ( element instanceof THREE.RenderableSprite ) {
  9221. _v1 = element;
  9222. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  9223. renderSprite( _v1, element, material );
  9224. } else if ( element instanceof THREE.RenderableLine ) {
  9225. _v1 = element.v1; _v2 = element.v2;
  9226. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9227. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9228. _elemBox.setFromPoints( [
  9229. _v1.positionScreen,
  9230. _v2.positionScreen
  9231. ] );
  9232. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9233. renderLine( _v1, _v2, element, material );
  9234. }
  9235. } else if ( element instanceof THREE.RenderableFace3 ) {
  9236. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  9237. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  9238. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  9239. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  9240. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9241. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9242. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  9243. if ( material.overdraw > 0 ) {
  9244. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  9245. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  9246. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  9247. }
  9248. _elemBox.setFromPoints( [
  9249. _v1.positionScreen,
  9250. _v2.positionScreen,
  9251. _v3.positionScreen
  9252. ] );
  9253. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9254. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  9255. }
  9256. }
  9257. /* DEBUG
  9258. setLineWidth( 1 );
  9259. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  9260. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  9261. */
  9262. _clearBox.union( _elemBox );
  9263. }
  9264. /* DEBUG
  9265. setLineWidth( 1 );
  9266. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  9267. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  9268. */
  9269. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  9270. };
  9271. //
  9272. function calculateLights() {
  9273. _ambientLight.setRGB( 0, 0, 0 );
  9274. _directionalLights.setRGB( 0, 0, 0 );
  9275. _pointLights.setRGB( 0, 0, 0 );
  9276. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9277. var light = _lights[ l ];
  9278. var lightColor = light.color;
  9279. if ( light instanceof THREE.AmbientLight ) {
  9280. _ambientLight.add( lightColor );
  9281. } else if ( light instanceof THREE.DirectionalLight ) {
  9282. // for sprites
  9283. _directionalLights.add( lightColor );
  9284. } else if ( light instanceof THREE.PointLight ) {
  9285. // for sprites
  9286. _pointLights.add( lightColor );
  9287. }
  9288. }
  9289. }
  9290. function calculateLight( position, normal, color ) {
  9291. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9292. var light = _lights[ l ];
  9293. _lightColor.copy( light.color );
  9294. if ( light instanceof THREE.DirectionalLight ) {
  9295. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld ).normalize();
  9296. var amount = normal.dot( lightPosition );
  9297. if ( amount <= 0 ) continue;
  9298. amount *= light.intensity;
  9299. color.add( _lightColor.multiplyScalar( amount ) );
  9300. } else if ( light instanceof THREE.PointLight ) {
  9301. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld );
  9302. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  9303. if ( amount <= 0 ) continue;
  9304. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  9305. if ( amount == 0 ) continue;
  9306. amount *= light.intensity;
  9307. color.add( _lightColor.multiplyScalar( amount ) );
  9308. }
  9309. }
  9310. }
  9311. function renderSprite( v1, element, material ) {
  9312. setOpacity( material.opacity );
  9313. setBlending( material.blending );
  9314. var scaleX = element.scale.x * _canvasWidthHalf;
  9315. var scaleY = element.scale.y * _canvasHeightHalf;
  9316. var dist = 0.5 * Math.sqrt( scaleX * scaleX + scaleY * scaleY ); // allow for rotated sprite
  9317. _elemBox.min.set( v1.x - dist, v1.y - dist );
  9318. _elemBox.max.set( v1.x + dist, v1.y + dist );
  9319. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9320. _elemBox.makeEmpty();
  9321. return;
  9322. }
  9323. if ( material instanceof THREE.SpriteMaterial ||
  9324. material instanceof THREE.ParticleSystemMaterial ) { // Backwards compatibility
  9325. if ( material.map !== null ) {
  9326. var bitmap = material.map.image;
  9327. _context.save();
  9328. _context.translate( v1.x, v1.y );
  9329. _context.rotate( material.rotation );
  9330. _context.scale( scaleX, - scaleY );
  9331. _context.drawImage( bitmap, 0, 0, bitmap.width, bitmap.height, - 0.5, - 0.5, 1, 1 );
  9332. _context.restore();
  9333. } else {
  9334. setFillStyle( material.color.getStyle() );
  9335. _context.save();
  9336. _context.translate( v1.x, v1.y );
  9337. _context.rotate( material.rotation );
  9338. _context.scale( scaleX, - scaleY );
  9339. _context.fillRect( - 0.5, - 0.5, 1, 1 );
  9340. _context.restore();
  9341. }
  9342. } else if ( material instanceof THREE.SpriteCanvasMaterial ) {
  9343. setStrokeStyle( material.color.getStyle() );
  9344. setFillStyle( material.color.getStyle() );
  9345. _context.save();
  9346. _context.translate( v1.x, v1.y );
  9347. _context.rotate( - element.rotation );
  9348. _context.scale( scaleX, scaleY );
  9349. material.program( _context );
  9350. _context.restore();
  9351. }
  9352. /* DEBUG
  9353. setStrokeStyle( 'rgb(255,255,0)' );
  9354. _context.beginPath();
  9355. _context.moveTo( v1.x - 10, v1.y );
  9356. _context.lineTo( v1.x + 10, v1.y );
  9357. _context.moveTo( v1.x, v1.y - 10 );
  9358. _context.lineTo( v1.x, v1.y + 10 );
  9359. _context.stroke();
  9360. */
  9361. }
  9362. function renderLine( v1, v2, element, material ) {
  9363. setOpacity( material.opacity );
  9364. setBlending( material.blending );
  9365. _context.beginPath();
  9366. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  9367. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  9368. if ( material instanceof THREE.LineBasicMaterial ) {
  9369. setLineWidth( material.linewidth );
  9370. setLineCap( material.linecap );
  9371. setLineJoin( material.linejoin );
  9372. if ( material.vertexColors !== THREE.VertexColors ) {
  9373. setStrokeStyle( material.color.getStyle() );
  9374. } else {
  9375. var colorStyle1 = element.vertexColors[0].getStyle();
  9376. var colorStyle2 = element.vertexColors[1].getStyle();
  9377. if ( colorStyle1 === colorStyle2 ) {
  9378. setStrokeStyle( colorStyle1 );
  9379. } else {
  9380. try {
  9381. var grad = _context.createLinearGradient(
  9382. v1.positionScreen.x,
  9383. v1.positionScreen.y,
  9384. v2.positionScreen.x,
  9385. v2.positionScreen.y
  9386. );
  9387. grad.addColorStop( 0, colorStyle1 );
  9388. grad.addColorStop( 1, colorStyle2 );
  9389. } catch ( exception ) {
  9390. grad = colorStyle1;
  9391. }
  9392. setStrokeStyle( grad );
  9393. }
  9394. }
  9395. _context.stroke();
  9396. _elemBox.expandByScalar( material.linewidth * 2 );
  9397. } else if ( material instanceof THREE.LineDashedMaterial ) {
  9398. setLineWidth( material.linewidth );
  9399. setLineCap( material.linecap );
  9400. setLineJoin( material.linejoin );
  9401. setStrokeStyle( material.color.getStyle() );
  9402. setDashAndGap( material.dashSize, material.gapSize );
  9403. _context.stroke();
  9404. _elemBox.expandByScalar( material.linewidth * 2 );
  9405. setDashAndGap( null, null );
  9406. }
  9407. }
  9408. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  9409. _this.info.render.vertices += 3;
  9410. _this.info.render.faces ++;
  9411. setOpacity( material.opacity );
  9412. setBlending( material.blending );
  9413. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9414. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9415. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9416. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  9417. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  9418. _diffuseColor.copy( material.color );
  9419. _emissiveColor.copy( material.emissive );
  9420. if ( material.vertexColors === THREE.FaceColors ) {
  9421. _diffuseColor.multiply( element.color );
  9422. }
  9423. if ( material.wireframe === false && material.shading === THREE.SmoothShading && element.vertexNormalsLength === 3 ) {
  9424. _color1.copy( _ambientLight );
  9425. _color2.copy( _ambientLight );
  9426. _color3.copy( _ambientLight );
  9427. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  9428. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  9429. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  9430. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  9431. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  9432. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  9433. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9434. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9435. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9436. } else {
  9437. _color.copy( _ambientLight );
  9438. calculateLight( element.centroidModel, element.normalModel, _color );
  9439. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9440. material.wireframe === true
  9441. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9442. : fillPath( _color );
  9443. }
  9444. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9445. if ( material.map !== null ) {
  9446. if ( material.map.mapping instanceof THREE.UVMapping ) {
  9447. _uvs = element.uvs[ 0 ];
  9448. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uvs[ uv1 ].x, _uvs[ uv1 ].y, _uvs[ uv2 ].x, _uvs[ uv2 ].y, _uvs[ uv3 ].x, _uvs[ uv3 ].y, material.map );
  9449. }
  9450. } else if ( material.envMap !== null ) {
  9451. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  9452. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  9453. _uv1x = 0.5 * _vector3.x + 0.5;
  9454. _uv1y = 0.5 * _vector3.y + 0.5;
  9455. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  9456. _uv2x = 0.5 * _vector3.x + 0.5;
  9457. _uv2y = 0.5 * _vector3.y + 0.5;
  9458. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  9459. _uv3x = 0.5 * _vector3.x + 0.5;
  9460. _uv3y = 0.5 * _vector3.y + 0.5;
  9461. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9462. }/* else if ( material.envMap.mapping === THREE.SphericalRefractionMapping ) {
  9463. }*/
  9464. } else {
  9465. _color.copy( material.color );
  9466. if ( material.vertexColors === THREE.FaceColors ) {
  9467. _color.multiply( element.color );
  9468. }
  9469. material.wireframe === true
  9470. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9471. : fillPath( _color );
  9472. }
  9473. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9474. _near = _camera.near;
  9475. _far = _camera.far;
  9476. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  9477. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  9478. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  9479. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9480. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9481. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9482. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9483. var normal;
  9484. if ( material.shading === THREE.FlatShading ) {
  9485. normal = element.normalModelView;
  9486. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9487. material.wireframe === true
  9488. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9489. : fillPath( _color );
  9490. } else if ( material.shading === THREE.SmoothShading ) {
  9491. normal = element.vertexNormalsModelView[ uv1 ];
  9492. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9493. normal = element.vertexNormalsModelView[ uv2 ];
  9494. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9495. normal = element.vertexNormalsModelView[ uv3 ];
  9496. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9497. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9498. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9499. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9500. }
  9501. }
  9502. }
  9503. //
  9504. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  9505. _context.beginPath();
  9506. _context.moveTo( x0, y0 );
  9507. _context.lineTo( x1, y1 );
  9508. _context.lineTo( x2, y2 );
  9509. _context.closePath();
  9510. }
  9511. function strokePath( color, linewidth, linecap, linejoin ) {
  9512. setLineWidth( linewidth );
  9513. setLineCap( linecap );
  9514. setLineJoin( linejoin );
  9515. setStrokeStyle( color.getStyle() );
  9516. _context.stroke();
  9517. _elemBox.expandByScalar( linewidth * 2 );
  9518. }
  9519. function fillPath( color ) {
  9520. setFillStyle( color.getStyle() );
  9521. _context.fill();
  9522. }
  9523. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  9524. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width === 0 ) return;
  9525. if ( texture.needsUpdate === true ) {
  9526. var repeatX = texture.wrapS === THREE.RepeatWrapping;
  9527. var repeatY = texture.wrapT === THREE.RepeatWrapping;
  9528. _patterns[ texture.id ] = _context.createPattern(
  9529. texture.image, repeatX === true && repeatY === true
  9530. ? 'repeat'
  9531. : repeatX === true && repeatY === false
  9532. ? 'repeat-x'
  9533. : repeatX === false && repeatY === true
  9534. ? 'repeat-y'
  9535. : 'no-repeat'
  9536. );
  9537. texture.needsUpdate = false;
  9538. }
  9539. _patterns[ texture.id ] === undefined
  9540. ? setFillStyle( 'rgba(0,0,0,1)' )
  9541. : setFillStyle( _patterns[ texture.id ] );
  9542. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9543. var a, b, c, d, e, f, det, idet,
  9544. offsetX = texture.offset.x / texture.repeat.x,
  9545. offsetY = texture.offset.y / texture.repeat.y,
  9546. width = texture.image.width * texture.repeat.x,
  9547. height = texture.image.height * texture.repeat.y;
  9548. u0 = ( u0 + offsetX ) * width;
  9549. v0 = ( 1.0 - v0 + offsetY ) * height;
  9550. u1 = ( u1 + offsetX ) * width;
  9551. v1 = ( 1.0 - v1 + offsetY ) * height;
  9552. u2 = ( u2 + offsetX ) * width;
  9553. v2 = ( 1.0 - v2 + offsetY ) * height;
  9554. x1 -= x0; y1 -= y0;
  9555. x2 -= x0; y2 -= y0;
  9556. u1 -= u0; v1 -= v0;
  9557. u2 -= u0; v2 -= v0;
  9558. det = u1 * v2 - u2 * v1;
  9559. if ( det === 0 ) {
  9560. if ( _imagedatas[ texture.id ] === undefined ) {
  9561. var canvas = document.createElement( 'canvas' )
  9562. canvas.width = texture.image.width;
  9563. canvas.height = texture.image.height;
  9564. var context = canvas.getContext( '2d' );
  9565. context.drawImage( texture.image, 0, 0 );
  9566. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  9567. }
  9568. var data = _imagedatas[ texture.id ];
  9569. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  9570. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  9571. fillPath( _color );
  9572. return;
  9573. }
  9574. idet = 1 / det;
  9575. a = ( v2 * x1 - v1 * x2 ) * idet;
  9576. b = ( v2 * y1 - v1 * y2 ) * idet;
  9577. c = ( u1 * x2 - u2 * x1 ) * idet;
  9578. d = ( u1 * y2 - u2 * y1 ) * idet;
  9579. e = x0 - a * u0 - c * v0;
  9580. f = y0 - b * u0 - d * v0;
  9581. _context.save();
  9582. _context.transform( a, b, c, d, e, f );
  9583. _context.fill();
  9584. _context.restore();
  9585. }
  9586. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  9587. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9588. var a, b, c, d, e, f, det, idet,
  9589. width = image.width - 1,
  9590. height = image.height - 1;
  9591. u0 *= width; v0 *= height;
  9592. u1 *= width; v1 *= height;
  9593. u2 *= width; v2 *= height;
  9594. x1 -= x0; y1 -= y0;
  9595. x2 -= x0; y2 -= y0;
  9596. u1 -= u0; v1 -= v0;
  9597. u2 -= u0; v2 -= v0;
  9598. det = u1 * v2 - u2 * v1;
  9599. idet = 1 / det;
  9600. a = ( v2 * x1 - v1 * x2 ) * idet;
  9601. b = ( v2 * y1 - v1 * y2 ) * idet;
  9602. c = ( u1 * x2 - u2 * x1 ) * idet;
  9603. d = ( u1 * y2 - u2 * y1 ) * idet;
  9604. e = x0 - a * u0 - c * v0;
  9605. f = y0 - b * u0 - d * v0;
  9606. _context.save();
  9607. _context.transform( a, b, c, d, e, f );
  9608. _context.clip();
  9609. _context.drawImage( image, 0, 0 );
  9610. _context.restore();
  9611. }
  9612. function getGradientTexture( color1, color2, color3, color4 ) {
  9613. // http://mrdoob.com/blog/post/710
  9614. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  9615. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  9616. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  9617. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  9618. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  9619. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  9620. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  9621. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  9622. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  9623. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  9624. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  9625. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  9626. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  9627. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  9628. return _gradientMap;
  9629. }
  9630. // Hide anti-alias gaps
  9631. function expand( v1, v2, pixels ) {
  9632. var x = v2.x - v1.x, y = v2.y - v1.y,
  9633. det = x * x + y * y, idet;
  9634. if ( det === 0 ) return;
  9635. idet = pixels / Math.sqrt( det );
  9636. x *= idet; y *= idet;
  9637. v2.x += x; v2.y += y;
  9638. v1.x -= x; v1.y -= y;
  9639. }
  9640. // Context cached methods.
  9641. function setOpacity( value ) {
  9642. if ( _contextGlobalAlpha !== value ) {
  9643. _context.globalAlpha = value;
  9644. _contextGlobalAlpha = value;
  9645. }
  9646. }
  9647. function setBlending( value ) {
  9648. if ( _contextGlobalCompositeOperation !== value ) {
  9649. if ( value === THREE.NormalBlending ) {
  9650. _context.globalCompositeOperation = 'source-over';
  9651. } else if ( value === THREE.AdditiveBlending ) {
  9652. _context.globalCompositeOperation = 'lighter';
  9653. } else if ( value === THREE.SubtractiveBlending ) {
  9654. _context.globalCompositeOperation = 'darker';
  9655. }
  9656. _contextGlobalCompositeOperation = value;
  9657. }
  9658. }
  9659. function setLineWidth( value ) {
  9660. if ( _contextLineWidth !== value ) {
  9661. _context.lineWidth = value;
  9662. _contextLineWidth = value;
  9663. }
  9664. }
  9665. function setLineCap( value ) {
  9666. // "butt", "round", "square"
  9667. if ( _contextLineCap !== value ) {
  9668. _context.lineCap = value;
  9669. _contextLineCap = value;
  9670. }
  9671. }
  9672. function setLineJoin( value ) {
  9673. // "round", "bevel", "miter"
  9674. if ( _contextLineJoin !== value ) {
  9675. _context.lineJoin = value;
  9676. _contextLineJoin = value;
  9677. }
  9678. }
  9679. function setStrokeStyle( value ) {
  9680. if ( _contextStrokeStyle !== value ) {
  9681. _context.strokeStyle = value;
  9682. _contextStrokeStyle = value;
  9683. }
  9684. }
  9685. function setFillStyle( value ) {
  9686. if ( _contextFillStyle !== value ) {
  9687. _context.fillStyle = value;
  9688. _contextFillStyle = value;
  9689. }
  9690. }
  9691. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  9692. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  9693. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  9694. _contextDashSize = dashSizeValue;
  9695. _contextGapSize = gapSizeValue;
  9696. }
  9697. }
  9698. };
  9699. /**
  9700. * Shader chunks for WebLG Shader library
  9701. *
  9702. * @author alteredq / http://alteredqualia.com/
  9703. * @author mrdoob / http://mrdoob.com/
  9704. * @author mikael emtinger / http://gomo.se/
  9705. */
  9706. THREE.ShaderChunk = {
  9707. // FOG
  9708. fog_pars_fragment: [
  9709. "#ifdef USE_FOG",
  9710. "uniform vec3 fogColor;",
  9711. "#ifdef FOG_EXP2",
  9712. "uniform float fogDensity;",
  9713. "#else",
  9714. "uniform float fogNear;",
  9715. "uniform float fogFar;",
  9716. "#endif",
  9717. "#endif"
  9718. ].join("\n"),
  9719. fog_fragment: [
  9720. "#ifdef USE_FOG",
  9721. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9722. "#ifdef FOG_EXP2",
  9723. "const float LOG2 = 1.442695;",
  9724. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  9725. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  9726. "#else",
  9727. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  9728. "#endif",
  9729. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  9730. "#endif"
  9731. ].join("\n"),
  9732. // ENVIRONMENT MAP
  9733. envmap_pars_fragment: [
  9734. "#ifdef USE_ENVMAP",
  9735. "uniform float reflectivity;",
  9736. "uniform samplerCube envMap;",
  9737. "uniform float flipEnvMap;",
  9738. "uniform int combine;",
  9739. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9740. "uniform bool useRefract;",
  9741. "uniform float refractionRatio;",
  9742. "#else",
  9743. "varying vec3 vReflect;",
  9744. "#endif",
  9745. "#endif"
  9746. ].join("\n"),
  9747. envmap_fragment: [
  9748. "#ifdef USE_ENVMAP",
  9749. "vec3 reflectVec;",
  9750. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9751. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  9752. "if ( useRefract ) {",
  9753. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  9754. "} else { ",
  9755. "reflectVec = reflect( cameraToVertex, normal );",
  9756. "}",
  9757. "#else",
  9758. "reflectVec = vReflect;",
  9759. "#endif",
  9760. "#ifdef DOUBLE_SIDED",
  9761. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9762. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9763. "#else",
  9764. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9765. "#endif",
  9766. "#ifdef GAMMA_INPUT",
  9767. "cubeColor.xyz *= cubeColor.xyz;",
  9768. "#endif",
  9769. "if ( combine == 1 ) {",
  9770. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  9771. "} else if ( combine == 2 ) {",
  9772. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  9773. "} else {",
  9774. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  9775. "}",
  9776. "#endif"
  9777. ].join("\n"),
  9778. envmap_pars_vertex: [
  9779. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9780. "varying vec3 vReflect;",
  9781. "uniform float refractionRatio;",
  9782. "uniform bool useRefract;",
  9783. "#endif"
  9784. ].join("\n"),
  9785. worldpos_vertex : [
  9786. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  9787. "#ifdef USE_SKINNING",
  9788. "vec4 worldPosition = modelMatrix * skinned;",
  9789. "#endif",
  9790. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9791. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  9792. "#endif",
  9793. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9794. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  9795. "#endif",
  9796. "#endif"
  9797. ].join("\n"),
  9798. envmap_vertex : [
  9799. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9800. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  9801. "worldNormal = normalize( worldNormal );",
  9802. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  9803. "if ( useRefract ) {",
  9804. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  9805. "} else {",
  9806. "vReflect = reflect( cameraToVertex, worldNormal );",
  9807. "}",
  9808. "#endif"
  9809. ].join("\n"),
  9810. // COLOR MAP (particles)
  9811. map_particle_pars_fragment: [
  9812. "#ifdef USE_MAP",
  9813. "uniform sampler2D map;",
  9814. "#endif"
  9815. ].join("\n"),
  9816. map_particle_fragment: [
  9817. "#ifdef USE_MAP",
  9818. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  9819. "#endif"
  9820. ].join("\n"),
  9821. // COLOR MAP (triangles)
  9822. map_pars_vertex: [
  9823. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9824. "varying vec2 vUv;",
  9825. "uniform vec4 offsetRepeat;",
  9826. "#endif"
  9827. ].join("\n"),
  9828. map_pars_fragment: [
  9829. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9830. "varying vec2 vUv;",
  9831. "#endif",
  9832. "#ifdef USE_MAP",
  9833. "uniform sampler2D map;",
  9834. "#endif"
  9835. ].join("\n"),
  9836. map_vertex: [
  9837. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9838. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  9839. "#endif"
  9840. ].join("\n"),
  9841. map_fragment: [
  9842. "#ifdef USE_MAP",
  9843. "vec4 texelColor = texture2D( map, vUv );",
  9844. "#ifdef GAMMA_INPUT",
  9845. "texelColor.xyz *= texelColor.xyz;",
  9846. "#endif",
  9847. "gl_FragColor = gl_FragColor * texelColor;",
  9848. "#endif"
  9849. ].join("\n"),
  9850. // LIGHT MAP
  9851. lightmap_pars_fragment: [
  9852. "#ifdef USE_LIGHTMAP",
  9853. "varying vec2 vUv2;",
  9854. "uniform sampler2D lightMap;",
  9855. "#endif"
  9856. ].join("\n"),
  9857. lightmap_pars_vertex: [
  9858. "#ifdef USE_LIGHTMAP",
  9859. "varying vec2 vUv2;",
  9860. "#endif"
  9861. ].join("\n"),
  9862. lightmap_fragment: [
  9863. "#ifdef USE_LIGHTMAP",
  9864. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  9865. "#endif"
  9866. ].join("\n"),
  9867. lightmap_vertex: [
  9868. "#ifdef USE_LIGHTMAP",
  9869. "vUv2 = uv2;",
  9870. "#endif"
  9871. ].join("\n"),
  9872. // BUMP MAP
  9873. bumpmap_pars_fragment: [
  9874. "#ifdef USE_BUMPMAP",
  9875. "uniform sampler2D bumpMap;",
  9876. "uniform float bumpScale;",
  9877. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  9878. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  9879. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9880. "vec2 dHdxy_fwd() {",
  9881. "vec2 dSTdx = dFdx( vUv );",
  9882. "vec2 dSTdy = dFdy( vUv );",
  9883. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  9884. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  9885. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  9886. "return vec2( dBx, dBy );",
  9887. "}",
  9888. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  9889. "vec3 vSigmaX = dFdx( surf_pos );",
  9890. "vec3 vSigmaY = dFdy( surf_pos );",
  9891. "vec3 vN = surf_norm;", // normalized
  9892. "vec3 R1 = cross( vSigmaY, vN );",
  9893. "vec3 R2 = cross( vN, vSigmaX );",
  9894. "float fDet = dot( vSigmaX, R1 );",
  9895. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  9896. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  9897. "}",
  9898. "#endif"
  9899. ].join("\n"),
  9900. // NORMAL MAP
  9901. normalmap_pars_fragment: [
  9902. "#ifdef USE_NORMALMAP",
  9903. "uniform sampler2D normalMap;",
  9904. "uniform vec2 normalScale;",
  9905. // Per-Pixel Tangent Space Normal Mapping
  9906. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  9907. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  9908. "vec3 q0 = dFdx( eye_pos.xyz );",
  9909. "vec3 q1 = dFdy( eye_pos.xyz );",
  9910. "vec2 st0 = dFdx( vUv.st );",
  9911. "vec2 st1 = dFdy( vUv.st );",
  9912. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  9913. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  9914. "vec3 N = normalize( surf_norm );",
  9915. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  9916. "mapN.xy = normalScale * mapN.xy;",
  9917. "mat3 tsn = mat3( S, T, N );",
  9918. "return normalize( tsn * mapN );",
  9919. "}",
  9920. "#endif"
  9921. ].join("\n"),
  9922. // SPECULAR MAP
  9923. specularmap_pars_fragment: [
  9924. "#ifdef USE_SPECULARMAP",
  9925. "uniform sampler2D specularMap;",
  9926. "#endif"
  9927. ].join("\n"),
  9928. specularmap_fragment: [
  9929. "float specularStrength;",
  9930. "#ifdef USE_SPECULARMAP",
  9931. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  9932. "specularStrength = texelSpecular.r;",
  9933. "#else",
  9934. "specularStrength = 1.0;",
  9935. "#endif"
  9936. ].join("\n"),
  9937. // LIGHTS LAMBERT
  9938. lights_lambert_pars_vertex: [
  9939. "uniform vec3 ambient;",
  9940. "uniform vec3 diffuse;",
  9941. "uniform vec3 emissive;",
  9942. "uniform vec3 ambientLightColor;",
  9943. "#if MAX_DIR_LIGHTS > 0",
  9944. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9945. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9946. "#endif",
  9947. "#if MAX_HEMI_LIGHTS > 0",
  9948. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9949. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9950. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9951. "#endif",
  9952. "#if MAX_POINT_LIGHTS > 0",
  9953. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9954. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9955. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9956. "#endif",
  9957. "#if MAX_SPOT_LIGHTS > 0",
  9958. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9959. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9960. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9961. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9962. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9963. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9964. "#endif",
  9965. "#ifdef WRAP_AROUND",
  9966. "uniform vec3 wrapRGB;",
  9967. "#endif"
  9968. ].join("\n"),
  9969. lights_lambert_vertex: [
  9970. "vLightFront = vec3( 0.0 );",
  9971. "#ifdef DOUBLE_SIDED",
  9972. "vLightBack = vec3( 0.0 );",
  9973. "#endif",
  9974. "transformedNormal = normalize( transformedNormal );",
  9975. "#if MAX_DIR_LIGHTS > 0",
  9976. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9977. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9978. "vec3 dirVector = normalize( lDirection.xyz );",
  9979. "float dotProduct = dot( transformedNormal, dirVector );",
  9980. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9981. "#ifdef DOUBLE_SIDED",
  9982. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9983. "#ifdef WRAP_AROUND",
  9984. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9985. "#endif",
  9986. "#endif",
  9987. "#ifdef WRAP_AROUND",
  9988. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9989. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  9990. "#ifdef DOUBLE_SIDED",
  9991. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  9992. "#endif",
  9993. "#endif",
  9994. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  9995. "#ifdef DOUBLE_SIDED",
  9996. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  9997. "#endif",
  9998. "}",
  9999. "#endif",
  10000. "#if MAX_POINT_LIGHTS > 0",
  10001. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10002. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10003. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10004. "float lDistance = 1.0;",
  10005. "if ( pointLightDistance[ i ] > 0.0 )",
  10006. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10007. "lVector = normalize( lVector );",
  10008. "float dotProduct = dot( transformedNormal, lVector );",
  10009. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10010. "#ifdef DOUBLE_SIDED",
  10011. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10012. "#ifdef WRAP_AROUND",
  10013. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10014. "#endif",
  10015. "#endif",
  10016. "#ifdef WRAP_AROUND",
  10017. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10018. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  10019. "#ifdef DOUBLE_SIDED",
  10020. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  10021. "#endif",
  10022. "#endif",
  10023. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  10024. "#ifdef DOUBLE_SIDED",
  10025. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  10026. "#endif",
  10027. "}",
  10028. "#endif",
  10029. "#if MAX_SPOT_LIGHTS > 0",
  10030. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10031. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10032. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10033. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  10034. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10035. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10036. "float lDistance = 1.0;",
  10037. "if ( spotLightDistance[ i ] > 0.0 )",
  10038. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10039. "lVector = normalize( lVector );",
  10040. "float dotProduct = dot( transformedNormal, lVector );",
  10041. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10042. "#ifdef DOUBLE_SIDED",
  10043. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10044. "#ifdef WRAP_AROUND",
  10045. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10046. "#endif",
  10047. "#endif",
  10048. "#ifdef WRAP_AROUND",
  10049. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10050. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  10051. "#ifdef DOUBLE_SIDED",
  10052. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  10053. "#endif",
  10054. "#endif",
  10055. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  10056. "#ifdef DOUBLE_SIDED",
  10057. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  10058. "#endif",
  10059. "}",
  10060. "}",
  10061. "#endif",
  10062. "#if MAX_HEMI_LIGHTS > 0",
  10063. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10064. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10065. "vec3 lVector = normalize( lDirection.xyz );",
  10066. "float dotProduct = dot( transformedNormal, lVector );",
  10067. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10068. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  10069. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10070. "#ifdef DOUBLE_SIDED",
  10071. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  10072. "#endif",
  10073. "}",
  10074. "#endif",
  10075. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  10076. "#ifdef DOUBLE_SIDED",
  10077. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  10078. "#endif"
  10079. ].join("\n"),
  10080. // LIGHTS PHONG
  10081. lights_phong_pars_vertex: [
  10082. "#ifndef PHONG_PER_PIXEL",
  10083. "#if MAX_POINT_LIGHTS > 0",
  10084. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10085. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10086. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  10087. "#endif",
  10088. "#if MAX_SPOT_LIGHTS > 0",
  10089. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10090. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10091. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  10092. "#endif",
  10093. "#endif",
  10094. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10095. "varying vec3 vWorldPosition;",
  10096. "#endif"
  10097. ].join("\n"),
  10098. lights_phong_vertex: [
  10099. "#ifndef PHONG_PER_PIXEL",
  10100. "#if MAX_POINT_LIGHTS > 0",
  10101. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10102. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10103. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10104. "float lDistance = 1.0;",
  10105. "if ( pointLightDistance[ i ] > 0.0 )",
  10106. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10107. "vPointLight[ i ] = vec4( lVector, lDistance );",
  10108. "}",
  10109. "#endif",
  10110. "#if MAX_SPOT_LIGHTS > 0",
  10111. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10112. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10113. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10114. "float lDistance = 1.0;",
  10115. "if ( spotLightDistance[ i ] > 0.0 )",
  10116. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10117. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  10118. "}",
  10119. "#endif",
  10120. "#endif",
  10121. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10122. "vWorldPosition = worldPosition.xyz;",
  10123. "#endif"
  10124. ].join("\n"),
  10125. lights_phong_pars_fragment: [
  10126. "uniform vec3 ambientLightColor;",
  10127. "#if MAX_DIR_LIGHTS > 0",
  10128. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10129. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10130. "#endif",
  10131. "#if MAX_HEMI_LIGHTS > 0",
  10132. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10133. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10134. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10135. "#endif",
  10136. "#if MAX_POINT_LIGHTS > 0",
  10137. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10138. "#ifdef PHONG_PER_PIXEL",
  10139. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10140. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10141. "#else",
  10142. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  10143. "#endif",
  10144. "#endif",
  10145. "#if MAX_SPOT_LIGHTS > 0",
  10146. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10147. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10148. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10149. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10150. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10151. "#ifdef PHONG_PER_PIXEL",
  10152. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10153. "#else",
  10154. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  10155. "#endif",
  10156. "#endif",
  10157. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10158. "varying vec3 vWorldPosition;",
  10159. "#endif",
  10160. "#ifdef WRAP_AROUND",
  10161. "uniform vec3 wrapRGB;",
  10162. "#endif",
  10163. "varying vec3 vViewPosition;",
  10164. "varying vec3 vNormal;"
  10165. ].join("\n"),
  10166. lights_phong_fragment: [
  10167. "vec3 normal = normalize( vNormal );",
  10168. "vec3 viewPosition = normalize( vViewPosition );",
  10169. "#ifdef DOUBLE_SIDED",
  10170. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10171. "#endif",
  10172. "#ifdef USE_NORMALMAP",
  10173. "normal = perturbNormal2Arb( -vViewPosition, normal );",
  10174. "#elif defined( USE_BUMPMAP )",
  10175. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  10176. "#endif",
  10177. "#if MAX_POINT_LIGHTS > 0",
  10178. "vec3 pointDiffuse = vec3( 0.0 );",
  10179. "vec3 pointSpecular = vec3( 0.0 );",
  10180. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10181. "#ifdef PHONG_PER_PIXEL",
  10182. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10183. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10184. "float lDistance = 1.0;",
  10185. "if ( pointLightDistance[ i ] > 0.0 )",
  10186. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10187. "lVector = normalize( lVector );",
  10188. "#else",
  10189. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  10190. "float lDistance = vPointLight[ i ].w;",
  10191. "#endif",
  10192. // diffuse
  10193. "float dotProduct = dot( normal, lVector );",
  10194. "#ifdef WRAP_AROUND",
  10195. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  10196. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10197. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10198. "#else",
  10199. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  10200. "#endif",
  10201. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  10202. // specular
  10203. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  10204. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10205. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  10206. "#ifdef PHYSICALLY_BASED_SHADING",
  10207. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10208. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10209. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  10210. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  10211. "#else",
  10212. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  10213. "#endif",
  10214. "}",
  10215. "#endif",
  10216. "#if MAX_SPOT_LIGHTS > 0",
  10217. "vec3 spotDiffuse = vec3( 0.0 );",
  10218. "vec3 spotSpecular = vec3( 0.0 );",
  10219. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10220. "#ifdef PHONG_PER_PIXEL",
  10221. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10222. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10223. "float lDistance = 1.0;",
  10224. "if ( spotLightDistance[ i ] > 0.0 )",
  10225. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10226. "lVector = normalize( lVector );",
  10227. "#else",
  10228. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  10229. "float lDistance = vSpotLight[ i ].w;",
  10230. "#endif",
  10231. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10232. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10233. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10234. // diffuse
  10235. "float dotProduct = dot( normal, lVector );",
  10236. "#ifdef WRAP_AROUND",
  10237. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  10238. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10239. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10240. "#else",
  10241. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  10242. "#endif",
  10243. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  10244. // specular
  10245. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  10246. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10247. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  10248. "#ifdef PHYSICALLY_BASED_SHADING",
  10249. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10250. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10251. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  10252. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  10253. "#else",
  10254. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  10255. "#endif",
  10256. "}",
  10257. "}",
  10258. "#endif",
  10259. "#if MAX_DIR_LIGHTS > 0",
  10260. "vec3 dirDiffuse = vec3( 0.0 );",
  10261. "vec3 dirSpecular = vec3( 0.0 );" ,
  10262. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10263. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10264. "vec3 dirVector = normalize( lDirection.xyz );",
  10265. // diffuse
  10266. "float dotProduct = dot( normal, dirVector );",
  10267. "#ifdef WRAP_AROUND",
  10268. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  10269. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10270. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  10271. "#else",
  10272. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  10273. "#endif",
  10274. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  10275. // specular
  10276. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10277. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10278. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  10279. "#ifdef PHYSICALLY_BASED_SHADING",
  10280. /*
  10281. // fresnel term from skin shader
  10282. "const float F0 = 0.128;",
  10283. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  10284. "float exponential = pow( base, 5.0 );",
  10285. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  10286. */
  10287. /*
  10288. // fresnel term from fresnel shader
  10289. "const float mFresnelBias = 0.08;",
  10290. "const float mFresnelScale = 0.3;",
  10291. "const float mFresnelPower = 5.0;",
  10292. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  10293. */
  10294. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10295. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10296. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  10297. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10298. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10299. "#else",
  10300. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  10301. "#endif",
  10302. "}",
  10303. "#endif",
  10304. "#if MAX_HEMI_LIGHTS > 0",
  10305. "vec3 hemiDiffuse = vec3( 0.0 );",
  10306. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10307. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10308. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10309. "vec3 lVector = normalize( lDirection.xyz );",
  10310. // diffuse
  10311. "float dotProduct = dot( normal, lVector );",
  10312. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10313. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10314. "hemiDiffuse += diffuse * hemiColor;",
  10315. // specular (sky light)
  10316. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10317. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10318. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  10319. // specular (ground light)
  10320. "vec3 lVectorGround = -lVector;",
  10321. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10322. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10323. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  10324. "#ifdef PHYSICALLY_BASED_SHADING",
  10325. "float dotProductGround = dot( normal, lVectorGround );",
  10326. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10327. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10328. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10329. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10330. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10331. "#else",
  10332. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  10333. "#endif",
  10334. "}",
  10335. "#endif",
  10336. "vec3 totalDiffuse = vec3( 0.0 );",
  10337. "vec3 totalSpecular = vec3( 0.0 );",
  10338. "#if MAX_DIR_LIGHTS > 0",
  10339. "totalDiffuse += dirDiffuse;",
  10340. "totalSpecular += dirSpecular;",
  10341. "#endif",
  10342. "#if MAX_HEMI_LIGHTS > 0",
  10343. "totalDiffuse += hemiDiffuse;",
  10344. "totalSpecular += hemiSpecular;",
  10345. "#endif",
  10346. "#if MAX_POINT_LIGHTS > 0",
  10347. "totalDiffuse += pointDiffuse;",
  10348. "totalSpecular += pointSpecular;",
  10349. "#endif",
  10350. "#if MAX_SPOT_LIGHTS > 0",
  10351. "totalDiffuse += spotDiffuse;",
  10352. "totalSpecular += spotSpecular;",
  10353. "#endif",
  10354. "#ifdef METAL",
  10355. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  10356. "#else",
  10357. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  10358. "#endif"
  10359. ].join("\n"),
  10360. // VERTEX COLORS
  10361. color_pars_fragment: [
  10362. "#ifdef USE_COLOR",
  10363. "varying vec3 vColor;",
  10364. "#endif"
  10365. ].join("\n"),
  10366. color_fragment: [
  10367. "#ifdef USE_COLOR",
  10368. "gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );",
  10369. "#endif"
  10370. ].join("\n"),
  10371. color_pars_vertex: [
  10372. "#ifdef USE_COLOR",
  10373. "varying vec3 vColor;",
  10374. "#endif"
  10375. ].join("\n"),
  10376. color_vertex: [
  10377. "#ifdef USE_COLOR",
  10378. "#ifdef GAMMA_INPUT",
  10379. "vColor = color * color;",
  10380. "#else",
  10381. "vColor = color;",
  10382. "#endif",
  10383. "#endif"
  10384. ].join("\n"),
  10385. // SKINNING
  10386. skinning_pars_vertex: [
  10387. "#ifdef USE_SKINNING",
  10388. "#ifdef BONE_TEXTURE",
  10389. "uniform sampler2D boneTexture;",
  10390. "uniform int boneTextureWidth;",
  10391. "uniform int boneTextureHeight;",
  10392. "mat4 getBoneMatrix( const in float i ) {",
  10393. "float j = i * 4.0;",
  10394. "float x = mod( j, float( boneTextureWidth ) );",
  10395. "float y = floor( j / float( boneTextureWidth ) );",
  10396. "float dx = 1.0 / float( boneTextureWidth );",
  10397. "float dy = 1.0 / float( boneTextureHeight );",
  10398. "y = dy * ( y + 0.5 );",
  10399. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  10400. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  10401. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  10402. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  10403. "mat4 bone = mat4( v1, v2, v3, v4 );",
  10404. "return bone;",
  10405. "}",
  10406. "#else",
  10407. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  10408. "mat4 getBoneMatrix( const in float i ) {",
  10409. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  10410. "return bone;",
  10411. "}",
  10412. "#endif",
  10413. "#endif"
  10414. ].join("\n"),
  10415. skinbase_vertex: [
  10416. "#ifdef USE_SKINNING",
  10417. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  10418. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  10419. "#endif"
  10420. ].join("\n"),
  10421. skinning_vertex: [
  10422. "#ifdef USE_SKINNING",
  10423. "#ifdef USE_MORPHTARGETS",
  10424. "vec4 skinVertex = vec4( morphed, 1.0 );",
  10425. "#else",
  10426. "vec4 skinVertex = vec4( position, 1.0 );",
  10427. "#endif",
  10428. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10429. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10430. "#endif"
  10431. ].join("\n"),
  10432. // MORPHING
  10433. morphtarget_pars_vertex: [
  10434. "#ifdef USE_MORPHTARGETS",
  10435. "#ifndef USE_MORPHNORMALS",
  10436. "uniform float morphTargetInfluences[ 8 ];",
  10437. "#else",
  10438. "uniform float morphTargetInfluences[ 4 ];",
  10439. "#endif",
  10440. "#endif"
  10441. ].join("\n"),
  10442. morphtarget_vertex: [
  10443. "#ifdef USE_MORPHTARGETS",
  10444. "vec3 morphed = vec3( 0.0 );",
  10445. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  10446. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  10447. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  10448. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  10449. "#ifndef USE_MORPHNORMALS",
  10450. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  10451. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  10452. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  10453. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  10454. "#endif",
  10455. "morphed += position;",
  10456. "#endif"
  10457. ].join("\n"),
  10458. default_vertex : [
  10459. "vec4 mvPosition;",
  10460. "#ifdef USE_SKINNING",
  10461. "mvPosition = modelViewMatrix * skinned;",
  10462. "#endif",
  10463. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  10464. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  10465. "#endif",
  10466. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  10467. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10468. "#endif",
  10469. "gl_Position = projectionMatrix * mvPosition;"
  10470. ].join("\n"),
  10471. morphnormal_vertex: [
  10472. "#ifdef USE_MORPHNORMALS",
  10473. "vec3 morphedNormal = vec3( 0.0 );",
  10474. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  10475. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  10476. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  10477. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  10478. "morphedNormal += normal;",
  10479. "#endif"
  10480. ].join("\n"),
  10481. skinnormal_vertex: [
  10482. "#ifdef USE_SKINNING",
  10483. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  10484. "skinMatrix += skinWeight.y * boneMatY;",
  10485. "#ifdef USE_MORPHNORMALS",
  10486. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  10487. "#else",
  10488. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  10489. "#endif",
  10490. "#endif"
  10491. ].join("\n"),
  10492. defaultnormal_vertex: [
  10493. "vec3 objectNormal;",
  10494. "#ifdef USE_SKINNING",
  10495. "objectNormal = skinnedNormal.xyz;",
  10496. "#endif",
  10497. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  10498. "objectNormal = morphedNormal;",
  10499. "#endif",
  10500. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  10501. "objectNormal = normal;",
  10502. "#endif",
  10503. "#ifdef FLIP_SIDED",
  10504. "objectNormal = -objectNormal;",
  10505. "#endif",
  10506. "vec3 transformedNormal = normalMatrix * objectNormal;"
  10507. ].join("\n"),
  10508. // SHADOW MAP
  10509. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  10510. // http://spidergl.org/example.php?id=6
  10511. // http://fabiensanglard.net/shadowmapping
  10512. shadowmap_pars_fragment: [
  10513. "#ifdef USE_SHADOWMAP",
  10514. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  10515. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  10516. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  10517. "uniform float shadowBias[ MAX_SHADOWS ];",
  10518. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10519. "float unpackDepth( const in vec4 rgba_depth ) {",
  10520. "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 );",
  10521. "float depth = dot( rgba_depth, bit_shift );",
  10522. "return depth;",
  10523. "}",
  10524. "#endif"
  10525. ].join("\n"),
  10526. shadowmap_fragment: [
  10527. "#ifdef USE_SHADOWMAP",
  10528. "#ifdef SHADOWMAP_DEBUG",
  10529. "vec3 frustumColors[3];",
  10530. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  10531. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  10532. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  10533. "#endif",
  10534. "#ifdef SHADOWMAP_CASCADE",
  10535. "int inFrustumCount = 0;",
  10536. "#endif",
  10537. "float fDepth;",
  10538. "vec3 shadowColor = vec3( 1.0 );",
  10539. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10540. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  10541. // "if ( something && something )" breaks ATI OpenGL shader compiler
  10542. // "if ( all( something, something ) )" using this instead
  10543. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  10544. "bool inFrustum = all( inFrustumVec );",
  10545. // don't shadow pixels outside of light frustum
  10546. // use just first frustum (for cascades)
  10547. // don't shadow pixels behind far plane of light frustum
  10548. "#ifdef SHADOWMAP_CASCADE",
  10549. "inFrustumCount += int( inFrustum );",
  10550. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  10551. "#else",
  10552. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  10553. "#endif",
  10554. "bool frustumTest = all( frustumTestVec );",
  10555. "if ( frustumTest ) {",
  10556. "shadowCoord.z += shadowBias[ i ];",
  10557. "#if defined( SHADOWMAP_TYPE_PCF )",
  10558. // Percentage-close filtering
  10559. // (9 pixel kernel)
  10560. // http://fabiensanglard.net/shadowmappingPCF/
  10561. "float shadow = 0.0;",
  10562. /*
  10563. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  10564. // must enroll loop manually
  10565. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  10566. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  10567. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  10568. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  10569. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  10570. "float fDepth = unpackDepth( rgbaDepth );",
  10571. "if ( fDepth < shadowCoord.z )",
  10572. "shadow += 1.0;",
  10573. "}",
  10574. "shadow /= 9.0;",
  10575. */
  10576. "const float shadowDelta = 1.0 / 9.0;",
  10577. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10578. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10579. "float dx0 = -1.25 * xPixelOffset;",
  10580. "float dy0 = -1.25 * yPixelOffset;",
  10581. "float dx1 = 1.25 * xPixelOffset;",
  10582. "float dy1 = 1.25 * yPixelOffset;",
  10583. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10584. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10585. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10586. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10587. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10588. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10589. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10590. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10591. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10592. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10593. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10594. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10595. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10596. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10597. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10598. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10599. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10600. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10601. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10602. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  10603. // Percentage-close filtering
  10604. // (9 pixel kernel)
  10605. // http://fabiensanglard.net/shadowmappingPCF/
  10606. "float shadow = 0.0;",
  10607. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10608. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10609. "float dx0 = -1.0 * xPixelOffset;",
  10610. "float dy0 = -1.0 * yPixelOffset;",
  10611. "float dx1 = 1.0 * xPixelOffset;",
  10612. "float dy1 = 1.0 * yPixelOffset;",
  10613. "mat3 shadowKernel;",
  10614. "mat3 depthKernel;",
  10615. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10616. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10617. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10618. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10619. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10620. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10621. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10622. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10623. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10624. "vec3 shadowZ = vec3( shadowCoord.z );",
  10625. "shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  10626. "shadowKernel[0] *= vec3(0.25);",
  10627. "shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  10628. "shadowKernel[1] *= vec3(0.25);",
  10629. "shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  10630. "shadowKernel[2] *= vec3(0.25);",
  10631. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  10632. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  10633. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  10634. "vec4 shadowValues;",
  10635. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  10636. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  10637. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  10638. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  10639. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  10640. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10641. "#else",
  10642. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  10643. "float fDepth = unpackDepth( rgbaDepth );",
  10644. "if ( fDepth < shadowCoord.z )",
  10645. // spot with multiple shadows is darker
  10646. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  10647. // spot with multiple shadows has the same color as single shadow spot
  10648. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  10649. "#endif",
  10650. "}",
  10651. "#ifdef SHADOWMAP_DEBUG",
  10652. "#ifdef SHADOWMAP_CASCADE",
  10653. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  10654. "#else",
  10655. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  10656. "#endif",
  10657. "#endif",
  10658. "}",
  10659. "#ifdef GAMMA_OUTPUT",
  10660. "shadowColor *= shadowColor;",
  10661. "#endif",
  10662. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  10663. "#endif"
  10664. ].join("\n"),
  10665. shadowmap_pars_vertex: [
  10666. "#ifdef USE_SHADOWMAP",
  10667. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10668. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  10669. "#endif"
  10670. ].join("\n"),
  10671. shadowmap_vertex: [
  10672. "#ifdef USE_SHADOWMAP",
  10673. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10674. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10675. "}",
  10676. "#endif"
  10677. ].join("\n"),
  10678. // ALPHATEST
  10679. alphatest_fragment: [
  10680. "#ifdef ALPHATEST",
  10681. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  10682. "#endif"
  10683. ].join("\n"),
  10684. // LINEAR SPACE
  10685. linear_to_gamma_fragment: [
  10686. "#ifdef GAMMA_OUTPUT",
  10687. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  10688. "#endif"
  10689. ].join("\n")
  10690. };
  10691. /**
  10692. * Uniform Utilities
  10693. */
  10694. THREE.UniformsUtils = {
  10695. merge: function ( uniforms ) {
  10696. var u, p, tmp, merged = {};
  10697. for ( u = 0; u < uniforms.length; u ++ ) {
  10698. tmp = this.clone( uniforms[ u ] );
  10699. for ( p in tmp ) {
  10700. merged[ p ] = tmp[ p ];
  10701. }
  10702. }
  10703. return merged;
  10704. },
  10705. clone: function ( uniforms_src ) {
  10706. var u, p, parameter, parameter_src, uniforms_dst = {};
  10707. for ( u in uniforms_src ) {
  10708. uniforms_dst[ u ] = {};
  10709. for ( p in uniforms_src[ u ] ) {
  10710. parameter_src = uniforms_src[ u ][ p ];
  10711. if ( parameter_src instanceof THREE.Color ||
  10712. parameter_src instanceof THREE.Vector2 ||
  10713. parameter_src instanceof THREE.Vector3 ||
  10714. parameter_src instanceof THREE.Vector4 ||
  10715. parameter_src instanceof THREE.Matrix4 ||
  10716. parameter_src instanceof THREE.Texture ) {
  10717. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10718. } else if ( parameter_src instanceof Array ) {
  10719. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10720. } else {
  10721. uniforms_dst[ u ][ p ] = parameter_src;
  10722. }
  10723. }
  10724. }
  10725. return uniforms_dst;
  10726. }
  10727. };
  10728. /**
  10729. * Uniforms library for shared webgl shaders
  10730. */
  10731. THREE.UniformsLib = {
  10732. common: {
  10733. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10734. "opacity" : { type: "f", value: 1.0 },
  10735. "map" : { type: "t", value: null },
  10736. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10737. "lightMap" : { type: "t", value: null },
  10738. "specularMap" : { type: "t", value: null },
  10739. "envMap" : { type: "t", value: null },
  10740. "flipEnvMap" : { type: "f", value: -1 },
  10741. "useRefract" : { type: "i", value: 0 },
  10742. "reflectivity" : { type: "f", value: 1.0 },
  10743. "refractionRatio" : { type: "f", value: 0.98 },
  10744. "combine" : { type: "i", value: 0 },
  10745. "morphTargetInfluences" : { type: "f", value: 0 }
  10746. },
  10747. bump: {
  10748. "bumpMap" : { type: "t", value: null },
  10749. "bumpScale" : { type: "f", value: 1 }
  10750. },
  10751. normalmap: {
  10752. "normalMap" : { type: "t", value: null },
  10753. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10754. },
  10755. fog : {
  10756. "fogDensity" : { type: "f", value: 0.00025 },
  10757. "fogNear" : { type: "f", value: 1 },
  10758. "fogFar" : { type: "f", value: 2000 },
  10759. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10760. },
  10761. lights: {
  10762. "ambientLightColor" : { type: "fv", value: [] },
  10763. "directionalLightDirection" : { type: "fv", value: [] },
  10764. "directionalLightColor" : { type: "fv", value: [] },
  10765. "hemisphereLightDirection" : { type: "fv", value: [] },
  10766. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10767. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10768. "pointLightColor" : { type: "fv", value: [] },
  10769. "pointLightPosition" : { type: "fv", value: [] },
  10770. "pointLightDistance" : { type: "fv1", value: [] },
  10771. "spotLightColor" : { type: "fv", value: [] },
  10772. "spotLightPosition" : { type: "fv", value: [] },
  10773. "spotLightDirection" : { type: "fv", value: [] },
  10774. "spotLightDistance" : { type: "fv1", value: [] },
  10775. "spotLightAngleCos" : { type: "fv1", value: [] },
  10776. "spotLightExponent" : { type: "fv1", value: [] }
  10777. },
  10778. particle: {
  10779. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10780. "opacity" : { type: "f", value: 1.0 },
  10781. "size" : { type: "f", value: 1.0 },
  10782. "scale" : { type: "f", value: 1.0 },
  10783. "map" : { type: "t", value: null },
  10784. "fogDensity" : { type: "f", value: 0.00025 },
  10785. "fogNear" : { type: "f", value: 1 },
  10786. "fogFar" : { type: "f", value: 2000 },
  10787. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10788. },
  10789. shadowmap: {
  10790. "shadowMap": { type: "tv", value: [] },
  10791. "shadowMapSize": { type: "v2v", value: [] },
  10792. "shadowBias" : { type: "fv1", value: [] },
  10793. "shadowDarkness": { type: "fv1", value: [] },
  10794. "shadowMatrix" : { type: "m4v", value: [] }
  10795. }
  10796. };
  10797. /**
  10798. * Webgl Shader Library for three.js
  10799. *
  10800. * @author alteredq / http://alteredqualia.com/
  10801. * @author mrdoob / http://mrdoob.com/
  10802. * @author mikael emtinger / http://gomo.se/
  10803. */
  10804. THREE.ShaderLib = {
  10805. 'basic': {
  10806. uniforms: THREE.UniformsUtils.merge( [
  10807. THREE.UniformsLib[ "common" ],
  10808. THREE.UniformsLib[ "fog" ],
  10809. THREE.UniformsLib[ "shadowmap" ]
  10810. ] ),
  10811. vertexShader: [
  10812. THREE.ShaderChunk[ "map_pars_vertex" ],
  10813. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10814. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10815. THREE.ShaderChunk[ "color_pars_vertex" ],
  10816. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10817. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10818. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10819. "void main() {",
  10820. THREE.ShaderChunk[ "map_vertex" ],
  10821. THREE.ShaderChunk[ "lightmap_vertex" ],
  10822. THREE.ShaderChunk[ "color_vertex" ],
  10823. THREE.ShaderChunk[ "skinbase_vertex" ],
  10824. "#ifdef USE_ENVMAP",
  10825. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10826. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10827. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10828. "#endif",
  10829. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10830. THREE.ShaderChunk[ "skinning_vertex" ],
  10831. THREE.ShaderChunk[ "default_vertex" ],
  10832. THREE.ShaderChunk[ "worldpos_vertex" ],
  10833. THREE.ShaderChunk[ "envmap_vertex" ],
  10834. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10835. "}"
  10836. ].join("\n"),
  10837. fragmentShader: [
  10838. "uniform vec3 diffuse;",
  10839. "uniform float opacity;",
  10840. THREE.ShaderChunk[ "color_pars_fragment" ],
  10841. THREE.ShaderChunk[ "map_pars_fragment" ],
  10842. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10843. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10844. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10845. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10846. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10847. "void main() {",
  10848. "gl_FragColor = vec4( diffuse, opacity );",
  10849. THREE.ShaderChunk[ "map_fragment" ],
  10850. THREE.ShaderChunk[ "alphatest_fragment" ],
  10851. THREE.ShaderChunk[ "specularmap_fragment" ],
  10852. THREE.ShaderChunk[ "lightmap_fragment" ],
  10853. THREE.ShaderChunk[ "color_fragment" ],
  10854. THREE.ShaderChunk[ "envmap_fragment" ],
  10855. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10856. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10857. THREE.ShaderChunk[ "fog_fragment" ],
  10858. "}"
  10859. ].join("\n")
  10860. },
  10861. 'lambert': {
  10862. uniforms: THREE.UniformsUtils.merge( [
  10863. THREE.UniformsLib[ "common" ],
  10864. THREE.UniformsLib[ "fog" ],
  10865. THREE.UniformsLib[ "lights" ],
  10866. THREE.UniformsLib[ "shadowmap" ],
  10867. {
  10868. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10869. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10870. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10871. }
  10872. ] ),
  10873. vertexShader: [
  10874. "#define LAMBERT",
  10875. "varying vec3 vLightFront;",
  10876. "#ifdef DOUBLE_SIDED",
  10877. "varying vec3 vLightBack;",
  10878. "#endif",
  10879. THREE.ShaderChunk[ "map_pars_vertex" ],
  10880. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10881. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10882. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10883. THREE.ShaderChunk[ "color_pars_vertex" ],
  10884. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10885. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10886. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10887. "void main() {",
  10888. THREE.ShaderChunk[ "map_vertex" ],
  10889. THREE.ShaderChunk[ "lightmap_vertex" ],
  10890. THREE.ShaderChunk[ "color_vertex" ],
  10891. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10892. THREE.ShaderChunk[ "skinbase_vertex" ],
  10893. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10894. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10895. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10896. THREE.ShaderChunk[ "skinning_vertex" ],
  10897. THREE.ShaderChunk[ "default_vertex" ],
  10898. THREE.ShaderChunk[ "worldpos_vertex" ],
  10899. THREE.ShaderChunk[ "envmap_vertex" ],
  10900. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10901. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10902. "}"
  10903. ].join("\n"),
  10904. fragmentShader: [
  10905. "uniform float opacity;",
  10906. "varying vec3 vLightFront;",
  10907. "#ifdef DOUBLE_SIDED",
  10908. "varying vec3 vLightBack;",
  10909. "#endif",
  10910. THREE.ShaderChunk[ "color_pars_fragment" ],
  10911. THREE.ShaderChunk[ "map_pars_fragment" ],
  10912. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10913. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10914. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10915. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10916. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10917. "void main() {",
  10918. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10919. THREE.ShaderChunk[ "map_fragment" ],
  10920. THREE.ShaderChunk[ "alphatest_fragment" ],
  10921. THREE.ShaderChunk[ "specularmap_fragment" ],
  10922. "#ifdef DOUBLE_SIDED",
  10923. //"float isFront = float( gl_FrontFacing );",
  10924. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10925. "if ( gl_FrontFacing )",
  10926. "gl_FragColor.xyz *= vLightFront;",
  10927. "else",
  10928. "gl_FragColor.xyz *= vLightBack;",
  10929. "#else",
  10930. "gl_FragColor.xyz *= vLightFront;",
  10931. "#endif",
  10932. THREE.ShaderChunk[ "lightmap_fragment" ],
  10933. THREE.ShaderChunk[ "color_fragment" ],
  10934. THREE.ShaderChunk[ "envmap_fragment" ],
  10935. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10936. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10937. THREE.ShaderChunk[ "fog_fragment" ],
  10938. "}"
  10939. ].join("\n")
  10940. },
  10941. 'phong': {
  10942. uniforms: THREE.UniformsUtils.merge( [
  10943. THREE.UniformsLib[ "common" ],
  10944. THREE.UniformsLib[ "bump" ],
  10945. THREE.UniformsLib[ "normalmap" ],
  10946. THREE.UniformsLib[ "fog" ],
  10947. THREE.UniformsLib[ "lights" ],
  10948. THREE.UniformsLib[ "shadowmap" ],
  10949. {
  10950. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10951. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10952. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10953. "shininess": { type: "f", value: 30 },
  10954. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10955. }
  10956. ] ),
  10957. vertexShader: [
  10958. "#define PHONG",
  10959. "varying vec3 vViewPosition;",
  10960. "varying vec3 vNormal;",
  10961. THREE.ShaderChunk[ "map_pars_vertex" ],
  10962. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10963. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10964. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10965. THREE.ShaderChunk[ "color_pars_vertex" ],
  10966. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10967. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10968. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10969. "void main() {",
  10970. THREE.ShaderChunk[ "map_vertex" ],
  10971. THREE.ShaderChunk[ "lightmap_vertex" ],
  10972. THREE.ShaderChunk[ "color_vertex" ],
  10973. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10974. THREE.ShaderChunk[ "skinbase_vertex" ],
  10975. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10976. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10977. "vNormal = normalize( transformedNormal );",
  10978. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10979. THREE.ShaderChunk[ "skinning_vertex" ],
  10980. THREE.ShaderChunk[ "default_vertex" ],
  10981. "vViewPosition = -mvPosition.xyz;",
  10982. THREE.ShaderChunk[ "worldpos_vertex" ],
  10983. THREE.ShaderChunk[ "envmap_vertex" ],
  10984. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10985. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10986. "}"
  10987. ].join("\n"),
  10988. fragmentShader: [
  10989. "uniform vec3 diffuse;",
  10990. "uniform float opacity;",
  10991. "uniform vec3 ambient;",
  10992. "uniform vec3 emissive;",
  10993. "uniform vec3 specular;",
  10994. "uniform float shininess;",
  10995. THREE.ShaderChunk[ "color_pars_fragment" ],
  10996. THREE.ShaderChunk[ "map_pars_fragment" ],
  10997. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10998. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10999. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11000. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  11001. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11002. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  11003. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  11004. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11005. "void main() {",
  11006. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  11007. THREE.ShaderChunk[ "map_fragment" ],
  11008. THREE.ShaderChunk[ "alphatest_fragment" ],
  11009. THREE.ShaderChunk[ "specularmap_fragment" ],
  11010. THREE.ShaderChunk[ "lights_phong_fragment" ],
  11011. THREE.ShaderChunk[ "lightmap_fragment" ],
  11012. THREE.ShaderChunk[ "color_fragment" ],
  11013. THREE.ShaderChunk[ "envmap_fragment" ],
  11014. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11015. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11016. THREE.ShaderChunk[ "fog_fragment" ],
  11017. "}"
  11018. ].join("\n")
  11019. },
  11020. 'particle_basic': {
  11021. uniforms: THREE.UniformsUtils.merge( [
  11022. THREE.UniformsLib[ "particle" ],
  11023. THREE.UniformsLib[ "shadowmap" ]
  11024. ] ),
  11025. vertexShader: [
  11026. "uniform float size;",
  11027. "uniform float scale;",
  11028. THREE.ShaderChunk[ "color_pars_vertex" ],
  11029. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11030. "void main() {",
  11031. THREE.ShaderChunk[ "color_vertex" ],
  11032. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11033. "#ifdef USE_SIZEATTENUATION",
  11034. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  11035. "#else",
  11036. "gl_PointSize = size;",
  11037. "#endif",
  11038. "gl_Position = projectionMatrix * mvPosition;",
  11039. THREE.ShaderChunk[ "worldpos_vertex" ],
  11040. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11041. "}"
  11042. ].join("\n"),
  11043. fragmentShader: [
  11044. "uniform vec3 psColor;",
  11045. "uniform float opacity;",
  11046. THREE.ShaderChunk[ "color_pars_fragment" ],
  11047. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  11048. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11049. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11050. "void main() {",
  11051. "gl_FragColor = vec4( psColor, opacity );",
  11052. THREE.ShaderChunk[ "map_particle_fragment" ],
  11053. THREE.ShaderChunk[ "alphatest_fragment" ],
  11054. THREE.ShaderChunk[ "color_fragment" ],
  11055. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11056. THREE.ShaderChunk[ "fog_fragment" ],
  11057. "}"
  11058. ].join("\n")
  11059. },
  11060. 'dashed': {
  11061. uniforms: THREE.UniformsUtils.merge( [
  11062. THREE.UniformsLib[ "common" ],
  11063. THREE.UniformsLib[ "fog" ],
  11064. {
  11065. "scale": { type: "f", value: 1 },
  11066. "dashSize": { type: "f", value: 1 },
  11067. "totalSize": { type: "f", value: 2 }
  11068. }
  11069. ] ),
  11070. vertexShader: [
  11071. "uniform float scale;",
  11072. "attribute float lineDistance;",
  11073. "varying float vLineDistance;",
  11074. THREE.ShaderChunk[ "color_pars_vertex" ],
  11075. "void main() {",
  11076. THREE.ShaderChunk[ "color_vertex" ],
  11077. "vLineDistance = scale * lineDistance;",
  11078. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11079. "gl_Position = projectionMatrix * mvPosition;",
  11080. "}"
  11081. ].join("\n"),
  11082. fragmentShader: [
  11083. "uniform vec3 diffuse;",
  11084. "uniform float opacity;",
  11085. "uniform float dashSize;",
  11086. "uniform float totalSize;",
  11087. "varying float vLineDistance;",
  11088. THREE.ShaderChunk[ "color_pars_fragment" ],
  11089. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11090. "void main() {",
  11091. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  11092. "discard;",
  11093. "}",
  11094. "gl_FragColor = vec4( diffuse, opacity );",
  11095. THREE.ShaderChunk[ "color_fragment" ],
  11096. THREE.ShaderChunk[ "fog_fragment" ],
  11097. "}"
  11098. ].join("\n")
  11099. },
  11100. 'depth': {
  11101. uniforms: {
  11102. "mNear": { type: "f", value: 1.0 },
  11103. "mFar" : { type: "f", value: 2000.0 },
  11104. "opacity" : { type: "f", value: 1.0 }
  11105. },
  11106. vertexShader: [
  11107. "void main() {",
  11108. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11109. "}"
  11110. ].join("\n"),
  11111. fragmentShader: [
  11112. "uniform float mNear;",
  11113. "uniform float mFar;",
  11114. "uniform float opacity;",
  11115. "void main() {",
  11116. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  11117. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  11118. "gl_FragColor = vec4( vec3( color ), opacity );",
  11119. "}"
  11120. ].join("\n")
  11121. },
  11122. 'normal': {
  11123. uniforms: {
  11124. "opacity" : { type: "f", value: 1.0 }
  11125. },
  11126. vertexShader: [
  11127. "varying vec3 vNormal;",
  11128. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11129. "void main() {",
  11130. "vNormal = normalize( normalMatrix * normal );",
  11131. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11132. THREE.ShaderChunk[ "default_vertex" ],
  11133. "}"
  11134. ].join("\n"),
  11135. fragmentShader: [
  11136. "uniform float opacity;",
  11137. "varying vec3 vNormal;",
  11138. "void main() {",
  11139. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  11140. "}"
  11141. ].join("\n")
  11142. },
  11143. /* -------------------------------------------------------------------------
  11144. // Normal map shader
  11145. // - Blinn-Phong
  11146. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  11147. // - point and directional lights (use with "lights: true" material option)
  11148. ------------------------------------------------------------------------- */
  11149. 'normalmap' : {
  11150. uniforms: THREE.UniformsUtils.merge( [
  11151. THREE.UniformsLib[ "fog" ],
  11152. THREE.UniformsLib[ "lights" ],
  11153. THREE.UniformsLib[ "shadowmap" ],
  11154. {
  11155. "enableAO" : { type: "i", value: 0 },
  11156. "enableDiffuse" : { type: "i", value: 0 },
  11157. "enableSpecular" : { type: "i", value: 0 },
  11158. "enableReflection": { type: "i", value: 0 },
  11159. "enableDisplacement": { type: "i", value: 0 },
  11160. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  11161. "tDiffuse" : { type: "t", value: null },
  11162. "tCube" : { type: "t", value: null },
  11163. "tNormal" : { type: "t", value: null },
  11164. "tSpecular" : { type: "t", value: null },
  11165. "tAO" : { type: "t", value: null },
  11166. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11167. "uDisplacementBias": { type: "f", value: 0.0 },
  11168. "uDisplacementScale": { type: "f", value: 1.0 },
  11169. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11170. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  11171. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11172. "uShininess": { type: "f", value: 30 },
  11173. "uOpacity": { type: "f", value: 1 },
  11174. "useRefract": { type: "i", value: 0 },
  11175. "uRefractionRatio": { type: "f", value: 0.98 },
  11176. "uReflectivity": { type: "f", value: 0.5 },
  11177. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11178. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11179. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11180. }
  11181. ] ),
  11182. fragmentShader: [
  11183. "uniform vec3 uAmbientColor;",
  11184. "uniform vec3 uDiffuseColor;",
  11185. "uniform vec3 uSpecularColor;",
  11186. "uniform float uShininess;",
  11187. "uniform float uOpacity;",
  11188. "uniform bool enableDiffuse;",
  11189. "uniform bool enableSpecular;",
  11190. "uniform bool enableAO;",
  11191. "uniform bool enableReflection;",
  11192. "uniform sampler2D tDiffuse;",
  11193. "uniform sampler2D tNormal;",
  11194. "uniform sampler2D tSpecular;",
  11195. "uniform sampler2D tAO;",
  11196. "uniform samplerCube tCube;",
  11197. "uniform vec2 uNormalScale;",
  11198. "uniform bool useRefract;",
  11199. "uniform float uRefractionRatio;",
  11200. "uniform float uReflectivity;",
  11201. "varying vec3 vTangent;",
  11202. "varying vec3 vBinormal;",
  11203. "varying vec3 vNormal;",
  11204. "varying vec2 vUv;",
  11205. "uniform vec3 ambientLightColor;",
  11206. "#if MAX_DIR_LIGHTS > 0",
  11207. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11208. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11209. "#endif",
  11210. "#if MAX_HEMI_LIGHTS > 0",
  11211. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11212. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11213. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11214. "#endif",
  11215. "#if MAX_POINT_LIGHTS > 0",
  11216. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11217. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11218. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11219. "#endif",
  11220. "#if MAX_SPOT_LIGHTS > 0",
  11221. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11222. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11223. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11224. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11225. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11226. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11227. "#endif",
  11228. "#ifdef WRAP_AROUND",
  11229. "uniform vec3 wrapRGB;",
  11230. "#endif",
  11231. "varying vec3 vWorldPosition;",
  11232. "varying vec3 vViewPosition;",
  11233. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11234. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11235. "void main() {",
  11236. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  11237. "vec3 specularTex = vec3( 1.0 );",
  11238. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11239. "normalTex.xy *= uNormalScale;",
  11240. "normalTex = normalize( normalTex );",
  11241. "if( enableDiffuse ) {",
  11242. "#ifdef GAMMA_INPUT",
  11243. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  11244. "texelColor.xyz *= texelColor.xyz;",
  11245. "gl_FragColor = gl_FragColor * texelColor;",
  11246. "#else",
  11247. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11248. "#endif",
  11249. "}",
  11250. "if( enableAO ) {",
  11251. "#ifdef GAMMA_INPUT",
  11252. "vec4 aoColor = texture2D( tAO, vUv );",
  11253. "aoColor.xyz *= aoColor.xyz;",
  11254. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11255. "#else",
  11256. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11257. "#endif",
  11258. "}",
  11259. "if( enableSpecular )",
  11260. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  11261. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11262. "vec3 finalNormal = tsb * normalTex;",
  11263. "#ifdef FLIP_SIDED",
  11264. "finalNormal = -finalNormal;",
  11265. "#endif",
  11266. "vec3 normal = normalize( finalNormal );",
  11267. "vec3 viewPosition = normalize( vViewPosition );",
  11268. // point lights
  11269. "#if MAX_POINT_LIGHTS > 0",
  11270. "vec3 pointDiffuse = vec3( 0.0 );",
  11271. "vec3 pointSpecular = vec3( 0.0 );",
  11272. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11273. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11274. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  11275. "float pointDistance = 1.0;",
  11276. "if ( pointLightDistance[ i ] > 0.0 )",
  11277. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  11278. "pointVector = normalize( pointVector );",
  11279. // diffuse
  11280. "#ifdef WRAP_AROUND",
  11281. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11282. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11283. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11284. "#else",
  11285. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11286. "#endif",
  11287. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  11288. // specular
  11289. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11290. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11291. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  11292. "#ifdef PHYSICALLY_BASED_SHADING",
  11293. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11294. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11295. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11296. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11297. "#else",
  11298. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  11299. "#endif",
  11300. "}",
  11301. "#endif",
  11302. // spot lights
  11303. "#if MAX_SPOT_LIGHTS > 0",
  11304. "vec3 spotDiffuse = vec3( 0.0 );",
  11305. "vec3 spotSpecular = vec3( 0.0 );",
  11306. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11307. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11308. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  11309. "float spotDistance = 1.0;",
  11310. "if ( spotLightDistance[ i ] > 0.0 )",
  11311. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  11312. "spotVector = normalize( spotVector );",
  11313. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11314. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11315. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11316. // diffuse
  11317. "#ifdef WRAP_AROUND",
  11318. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  11319. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  11320. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11321. "#else",
  11322. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  11323. "#endif",
  11324. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  11325. // specular
  11326. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  11327. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11328. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  11329. "#ifdef PHYSICALLY_BASED_SHADING",
  11330. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11331. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11332. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  11333. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  11334. "#else",
  11335. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  11336. "#endif",
  11337. "}",
  11338. "}",
  11339. "#endif",
  11340. // directional lights
  11341. "#if MAX_DIR_LIGHTS > 0",
  11342. "vec3 dirDiffuse = vec3( 0.0 );",
  11343. "vec3 dirSpecular = vec3( 0.0 );",
  11344. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11345. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11346. "vec3 dirVector = normalize( lDirection.xyz );",
  11347. // diffuse
  11348. "#ifdef WRAP_AROUND",
  11349. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11350. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11351. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11352. "#else",
  11353. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11354. "#endif",
  11355. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  11356. // specular
  11357. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11358. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11359. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  11360. "#ifdef PHYSICALLY_BASED_SHADING",
  11361. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11362. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11363. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11364. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11365. "#else",
  11366. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  11367. "#endif",
  11368. "}",
  11369. "#endif",
  11370. // hemisphere lights
  11371. "#if MAX_HEMI_LIGHTS > 0",
  11372. "vec3 hemiDiffuse = vec3( 0.0 );",
  11373. "vec3 hemiSpecular = vec3( 0.0 );" ,
  11374. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11375. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11376. "vec3 lVector = normalize( lDirection.xyz );",
  11377. // diffuse
  11378. "float dotProduct = dot( normal, lVector );",
  11379. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11380. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11381. "hemiDiffuse += uDiffuseColor * hemiColor;",
  11382. // specular (sky light)
  11383. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11384. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11385. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  11386. // specular (ground light)
  11387. "vec3 lVectorGround = -lVector;",
  11388. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11389. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11390. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  11391. "#ifdef PHYSICALLY_BASED_SHADING",
  11392. "float dotProductGround = dot( normal, lVectorGround );",
  11393. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11394. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11395. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  11396. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  11397. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11398. "#else",
  11399. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  11400. "#endif",
  11401. "}",
  11402. "#endif",
  11403. // all lights contribution summation
  11404. "vec3 totalDiffuse = vec3( 0.0 );",
  11405. "vec3 totalSpecular = vec3( 0.0 );",
  11406. "#if MAX_DIR_LIGHTS > 0",
  11407. "totalDiffuse += dirDiffuse;",
  11408. "totalSpecular += dirSpecular;",
  11409. "#endif",
  11410. "#if MAX_HEMI_LIGHTS > 0",
  11411. "totalDiffuse += hemiDiffuse;",
  11412. "totalSpecular += hemiSpecular;",
  11413. "#endif",
  11414. "#if MAX_POINT_LIGHTS > 0",
  11415. "totalDiffuse += pointDiffuse;",
  11416. "totalSpecular += pointSpecular;",
  11417. "#endif",
  11418. "#if MAX_SPOT_LIGHTS > 0",
  11419. "totalDiffuse += spotDiffuse;",
  11420. "totalSpecular += spotSpecular;",
  11421. "#endif",
  11422. "#ifdef METAL",
  11423. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  11424. "#else",
  11425. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  11426. "#endif",
  11427. "if ( enableReflection ) {",
  11428. "vec3 vReflect;",
  11429. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  11430. "if ( useRefract ) {",
  11431. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  11432. "} else {",
  11433. "vReflect = reflect( cameraToVertex, normal );",
  11434. "}",
  11435. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11436. "#ifdef GAMMA_INPUT",
  11437. "cubeColor.xyz *= cubeColor.xyz;",
  11438. "#endif",
  11439. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  11440. "}",
  11441. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11442. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11443. THREE.ShaderChunk[ "fog_fragment" ],
  11444. "}"
  11445. ].join("\n"),
  11446. vertexShader: [
  11447. "attribute vec4 tangent;",
  11448. "uniform vec2 uOffset;",
  11449. "uniform vec2 uRepeat;",
  11450. "uniform bool enableDisplacement;",
  11451. "#ifdef VERTEX_TEXTURES",
  11452. "uniform sampler2D tDisplacement;",
  11453. "uniform float uDisplacementScale;",
  11454. "uniform float uDisplacementBias;",
  11455. "#endif",
  11456. "varying vec3 vTangent;",
  11457. "varying vec3 vBinormal;",
  11458. "varying vec3 vNormal;",
  11459. "varying vec2 vUv;",
  11460. "varying vec3 vWorldPosition;",
  11461. "varying vec3 vViewPosition;",
  11462. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11463. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11464. "void main() {",
  11465. THREE.ShaderChunk[ "skinbase_vertex" ],
  11466. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11467. // normal, tangent and binormal vectors
  11468. "#ifdef USE_SKINNING",
  11469. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  11470. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  11471. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  11472. "#else",
  11473. "vNormal = normalize( normalMatrix * normal );",
  11474. "vTangent = normalize( normalMatrix * tangent.xyz );",
  11475. "#endif",
  11476. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  11477. "vUv = uv * uRepeat + uOffset;",
  11478. // displacement mapping
  11479. "vec3 displacedPosition;",
  11480. "#ifdef VERTEX_TEXTURES",
  11481. "if ( enableDisplacement ) {",
  11482. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11483. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11484. "displacedPosition = position + normalize( normal ) * df;",
  11485. "} else {",
  11486. "#ifdef USE_SKINNING",
  11487. "vec4 skinVertex = vec4( position, 1.0 );",
  11488. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11489. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11490. "displacedPosition = skinned.xyz;",
  11491. "#else",
  11492. "displacedPosition = position;",
  11493. "#endif",
  11494. "}",
  11495. "#else",
  11496. "#ifdef USE_SKINNING",
  11497. "vec4 skinVertex = vec4( position, 1.0 );",
  11498. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11499. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11500. "displacedPosition = skinned.xyz;",
  11501. "#else",
  11502. "displacedPosition = position;",
  11503. "#endif",
  11504. "#endif",
  11505. //
  11506. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  11507. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  11508. "gl_Position = projectionMatrix * mvPosition;",
  11509. //
  11510. "vWorldPosition = worldPosition.xyz;",
  11511. "vViewPosition = -mvPosition.xyz;",
  11512. // shadows
  11513. "#ifdef USE_SHADOWMAP",
  11514. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11515. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11516. "}",
  11517. "#endif",
  11518. "}"
  11519. ].join("\n")
  11520. },
  11521. /* -------------------------------------------------------------------------
  11522. // Cube map shader
  11523. ------------------------------------------------------------------------- */
  11524. 'cube': {
  11525. uniforms: { "tCube": { type: "t", value: null },
  11526. "tFlip": { type: "f", value: -1 } },
  11527. vertexShader: [
  11528. "varying vec3 vWorldPosition;",
  11529. "void main() {",
  11530. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  11531. "vWorldPosition = worldPosition.xyz;",
  11532. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11533. "}"
  11534. ].join("\n"),
  11535. fragmentShader: [
  11536. "uniform samplerCube tCube;",
  11537. "uniform float tFlip;",
  11538. "varying vec3 vWorldPosition;",
  11539. "void main() {",
  11540. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11541. "}"
  11542. ].join("\n")
  11543. },
  11544. // Depth encoding into RGBA texture
  11545. // based on SpiderGL shadow map example
  11546. // http://spidergl.org/example.php?id=6
  11547. // originally from
  11548. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11549. // see also here:
  11550. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11551. 'depthRGBA': {
  11552. uniforms: {},
  11553. vertexShader: [
  11554. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11555. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11556. "void main() {",
  11557. THREE.ShaderChunk[ "skinbase_vertex" ],
  11558. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11559. THREE.ShaderChunk[ "skinning_vertex" ],
  11560. THREE.ShaderChunk[ "default_vertex" ],
  11561. "}"
  11562. ].join("\n"),
  11563. fragmentShader: [
  11564. "vec4 pack_depth( const in float depth ) {",
  11565. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11566. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11567. "vec4 res = fract( depth * bit_shift );",
  11568. "res -= res.xxyz * bit_mask;",
  11569. "return res;",
  11570. "}",
  11571. "void main() {",
  11572. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  11573. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  11574. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  11575. //"gl_FragData[ 0 ] = pack_depth( z );",
  11576. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  11577. "}"
  11578. ].join("\n")
  11579. }
  11580. };
  11581. /**
  11582. * @author supereggbert / http://www.paulbrunt.co.uk/
  11583. * @author mrdoob / http://mrdoob.com/
  11584. * @author alteredq / http://alteredqualia.com/
  11585. * @author szimek / https://github.com/szimek/
  11586. */
  11587. THREE.WebGLRenderer = function ( parameters ) {
  11588. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  11589. parameters = parameters || {};
  11590. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11591. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  11592. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11593. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11594. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11595. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11596. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  11597. _clearColor = new THREE.Color( 0x000000 ),
  11598. _clearAlpha = 0;
  11599. // public properties
  11600. this.domElement = _canvas;
  11601. this.context = null;
  11602. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  11603. ? parameters.devicePixelRatio
  11604. : self.devicePixelRatio !== undefined
  11605. ? self.devicePixelRatio
  11606. : 1;
  11607. // clearing
  11608. this.autoClear = true;
  11609. this.autoClearColor = true;
  11610. this.autoClearDepth = true;
  11611. this.autoClearStencil = true;
  11612. // scene graph
  11613. this.sortObjects = true;
  11614. this.autoUpdateObjects = true;
  11615. // physically based shading
  11616. this.gammaInput = false;
  11617. this.gammaOutput = false;
  11618. this.physicallyBasedShading = false;
  11619. // shadow map
  11620. this.shadowMapEnabled = false;
  11621. this.shadowMapAutoUpdate = true;
  11622. this.shadowMapType = THREE.PCFShadowMap;
  11623. this.shadowMapCullFace = THREE.CullFaceFront;
  11624. this.shadowMapDebug = false;
  11625. this.shadowMapCascade = false;
  11626. // morphs
  11627. this.maxMorphTargets = 8;
  11628. this.maxMorphNormals = 4;
  11629. // flags
  11630. this.autoScaleCubemaps = true;
  11631. // custom render plugins
  11632. this.renderPluginsPre = [];
  11633. this.renderPluginsPost = [];
  11634. // info
  11635. this.info = {
  11636. memory: {
  11637. programs: 0,
  11638. geometries: 0,
  11639. textures: 0
  11640. },
  11641. render: {
  11642. calls: 0,
  11643. vertices: 0,
  11644. faces: 0,
  11645. points: 0
  11646. }
  11647. };
  11648. // internal properties
  11649. var _this = this,
  11650. _programs = [],
  11651. _programs_counter = 0,
  11652. // internal state cache
  11653. _currentProgram = null,
  11654. _currentFramebuffer = null,
  11655. _currentMaterialId = -1,
  11656. _currentGeometryGroupHash = null,
  11657. _currentCamera = null,
  11658. _geometryGroupCounter = 0,
  11659. _usedTextureUnits = 0,
  11660. // GL state cache
  11661. _oldDoubleSided = -1,
  11662. _oldFlipSided = -1,
  11663. _oldBlending = -1,
  11664. _oldBlendEquation = -1,
  11665. _oldBlendSrc = -1,
  11666. _oldBlendDst = -1,
  11667. _oldDepthTest = -1,
  11668. _oldDepthWrite = -1,
  11669. _oldPolygonOffset = null,
  11670. _oldPolygonOffsetFactor = null,
  11671. _oldPolygonOffsetUnits = null,
  11672. _oldLineWidth = null,
  11673. _viewportX = 0,
  11674. _viewportY = 0,
  11675. _viewportWidth = _canvas.width,
  11676. _viewportHeight = _canvas.height,
  11677. _currentWidth = 0,
  11678. _currentHeight = 0,
  11679. _enabledAttributes = {},
  11680. // frustum
  11681. _frustum = new THREE.Frustum(),
  11682. // camera matrices cache
  11683. _projScreenMatrix = new THREE.Matrix4(),
  11684. _projScreenMatrixPS = new THREE.Matrix4(),
  11685. _vector3 = new THREE.Vector3(),
  11686. // light arrays cache
  11687. _direction = new THREE.Vector3(),
  11688. _lightsNeedUpdate = true,
  11689. _lights = {
  11690. ambient: [ 0, 0, 0 ],
  11691. directional: { length: 0, colors: new Array(), positions: new Array() },
  11692. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  11693. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  11694. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  11695. };
  11696. // initialize
  11697. var _gl;
  11698. var _glExtensionTextureFloat;
  11699. var _glExtensionTextureFloatLinear;
  11700. var _glExtensionStandardDerivatives;
  11701. var _glExtensionTextureFilterAnisotropic;
  11702. var _glExtensionCompressedTextureS3TC;
  11703. initGL();
  11704. setDefaultGLState();
  11705. this.context = _gl;
  11706. // GPU capabilities
  11707. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  11708. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11709. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  11710. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11711. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  11712. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  11713. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  11714. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  11715. //
  11716. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  11717. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  11718. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  11719. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  11720. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  11721. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  11722. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  11723. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  11724. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  11725. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  11726. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  11727. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  11728. // clamp precision to maximum available
  11729. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  11730. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  11731. if ( _precision === "highp" && ! highpAvailable ) {
  11732. if ( mediumpAvailable ) {
  11733. _precision = "mediump";
  11734. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  11735. } else {
  11736. _precision = "lowp";
  11737. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  11738. }
  11739. }
  11740. if ( _precision === "mediump" && ! mediumpAvailable ) {
  11741. _precision = "lowp";
  11742. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  11743. }
  11744. // API
  11745. this.getContext = function () {
  11746. return _gl;
  11747. };
  11748. this.supportsVertexTextures = function () {
  11749. return _supportsVertexTextures;
  11750. };
  11751. this.supportsFloatTextures = function () {
  11752. return _glExtensionTextureFloat;
  11753. };
  11754. this.supportsStandardDerivatives = function () {
  11755. return _glExtensionStandardDerivatives;
  11756. };
  11757. this.supportsCompressedTextureS3TC = function () {
  11758. return _glExtensionCompressedTextureS3TC;
  11759. };
  11760. this.getMaxAnisotropy = function () {
  11761. return _maxAnisotropy;
  11762. };
  11763. this.getPrecision = function () {
  11764. return _precision;
  11765. };
  11766. this.setSize = function ( width, height, updateStyle ) {
  11767. _canvas.width = width * this.devicePixelRatio;
  11768. _canvas.height = height * this.devicePixelRatio;
  11769. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  11770. _canvas.style.width = width + 'px';
  11771. _canvas.style.height = height + 'px';
  11772. }
  11773. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  11774. };
  11775. this.setViewport = function ( x, y, width, height ) {
  11776. _viewportX = x !== undefined ? x : 0;
  11777. _viewportY = y !== undefined ? y : 0;
  11778. _viewportWidth = width !== undefined ? width : _canvas.width;
  11779. _viewportHeight = height !== undefined ? height : _canvas.height;
  11780. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11781. };
  11782. this.setScissor = function ( x, y, width, height ) {
  11783. _gl.scissor( x, y, width, height );
  11784. };
  11785. this.enableScissorTest = function ( enable ) {
  11786. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  11787. };
  11788. // Clearing
  11789. this.setClearColor = function ( color, alpha ) {
  11790. _clearColor.set( color );
  11791. _clearAlpha = alpha !== undefined ? alpha : 1;
  11792. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11793. };
  11794. this.setClearColorHex = function ( hex, alpha ) {
  11795. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  11796. this.setClearColor( hex, alpha );
  11797. };
  11798. this.getClearColor = function () {
  11799. return _clearColor;
  11800. };
  11801. this.getClearAlpha = function () {
  11802. return _clearAlpha;
  11803. };
  11804. this.clear = function ( color, depth, stencil ) {
  11805. var bits = 0;
  11806. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11807. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11808. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11809. _gl.clear( bits );
  11810. };
  11811. this.clearColor = function () {
  11812. _gl.clear( _gl.COLOR_BUFFER_BIT );
  11813. };
  11814. this.clearDepth = function () {
  11815. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  11816. };
  11817. this.clearStencil = function () {
  11818. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  11819. };
  11820. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11821. this.setRenderTarget( renderTarget );
  11822. this.clear( color, depth, stencil );
  11823. };
  11824. // Plugins
  11825. this.addPostPlugin = function ( plugin ) {
  11826. plugin.init( this );
  11827. this.renderPluginsPost.push( plugin );
  11828. };
  11829. this.addPrePlugin = function ( plugin ) {
  11830. plugin.init( this );
  11831. this.renderPluginsPre.push( plugin );
  11832. };
  11833. // Rendering
  11834. this.updateShadowMap = function ( scene, camera ) {
  11835. _currentProgram = null;
  11836. _oldBlending = -1;
  11837. _oldDepthTest = -1;
  11838. _oldDepthWrite = -1;
  11839. _currentGeometryGroupHash = -1;
  11840. _currentMaterialId = -1;
  11841. _lightsNeedUpdate = true;
  11842. _oldDoubleSided = -1;
  11843. _oldFlipSided = -1;
  11844. this.shadowMapPlugin.update( scene, camera );
  11845. };
  11846. // Internal functions
  11847. // Buffer allocation
  11848. function createParticleBuffers ( geometry ) {
  11849. geometry.__webglVertexBuffer = _gl.createBuffer();
  11850. geometry.__webglColorBuffer = _gl.createBuffer();
  11851. _this.info.memory.geometries ++;
  11852. };
  11853. function createLineBuffers ( geometry ) {
  11854. geometry.__webglVertexBuffer = _gl.createBuffer();
  11855. geometry.__webglColorBuffer = _gl.createBuffer();
  11856. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  11857. _this.info.memory.geometries ++;
  11858. };
  11859. function createMeshBuffers ( geometryGroup ) {
  11860. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  11861. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  11862. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  11863. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  11864. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  11865. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  11866. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  11867. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  11868. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  11869. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  11870. var m, ml;
  11871. if ( geometryGroup.numMorphTargets ) {
  11872. geometryGroup.__webglMorphTargetsBuffers = [];
  11873. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11874. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  11875. }
  11876. }
  11877. if ( geometryGroup.numMorphNormals ) {
  11878. geometryGroup.__webglMorphNormalsBuffers = [];
  11879. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11880. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  11881. }
  11882. }
  11883. _this.info.memory.geometries ++;
  11884. };
  11885. // Events
  11886. var onGeometryDispose = function ( event ) {
  11887. var geometry = event.target;
  11888. geometry.removeEventListener( 'dispose', onGeometryDispose );
  11889. deallocateGeometry( geometry );
  11890. };
  11891. var onTextureDispose = function ( event ) {
  11892. var texture = event.target;
  11893. texture.removeEventListener( 'dispose', onTextureDispose );
  11894. deallocateTexture( texture );
  11895. _this.info.memory.textures --;
  11896. };
  11897. var onRenderTargetDispose = function ( event ) {
  11898. var renderTarget = event.target;
  11899. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11900. deallocateRenderTarget( renderTarget );
  11901. _this.info.memory.textures --;
  11902. };
  11903. var onMaterialDispose = function ( event ) {
  11904. var material = event.target;
  11905. material.removeEventListener( 'dispose', onMaterialDispose );
  11906. deallocateMaterial( material );
  11907. };
  11908. // Buffer deallocation
  11909. var deleteBuffers = function ( geometry ) {
  11910. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11911. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  11912. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  11913. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  11914. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  11915. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  11916. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  11917. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  11918. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  11919. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  11920. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  11921. // custom attributes
  11922. if ( geometry.__webglCustomAttributesList !== undefined ) {
  11923. for ( var id in geometry.__webglCustomAttributesList ) {
  11924. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  11925. }
  11926. }
  11927. _this.info.memory.geometries --;
  11928. };
  11929. var deallocateGeometry = function ( geometry ) {
  11930. geometry.__webglInit = undefined;
  11931. if ( geometry instanceof THREE.BufferGeometry ) {
  11932. var attributes = geometry.attributes;
  11933. for ( var key in attributes ) {
  11934. if ( attributes[ key ].buffer !== undefined ) {
  11935. _gl.deleteBuffer( attributes[ key ].buffer );
  11936. }
  11937. }
  11938. _this.info.memory.geometries --;
  11939. } else {
  11940. if ( geometry.geometryGroups !== undefined ) {
  11941. for ( var g in geometry.geometryGroups ) {
  11942. var geometryGroup = geometry.geometryGroups[ g ];
  11943. if ( geometryGroup.numMorphTargets !== undefined ) {
  11944. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11945. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11946. }
  11947. }
  11948. if ( geometryGroup.numMorphNormals !== undefined ) {
  11949. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11950. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11951. }
  11952. }
  11953. deleteBuffers( geometryGroup );
  11954. }
  11955. } else {
  11956. deleteBuffers( geometry );
  11957. }
  11958. }
  11959. };
  11960. var deallocateTexture = function ( texture ) {
  11961. if ( texture.image && texture.image.__webglTextureCube ) {
  11962. // cube texture
  11963. _gl.deleteTexture( texture.image.__webglTextureCube );
  11964. } else {
  11965. // 2D texture
  11966. if ( ! texture.__webglInit ) return;
  11967. texture.__webglInit = false;
  11968. _gl.deleteTexture( texture.__webglTexture );
  11969. }
  11970. };
  11971. var deallocateRenderTarget = function ( renderTarget ) {
  11972. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  11973. _gl.deleteTexture( renderTarget.__webglTexture );
  11974. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  11975. for ( var i = 0; i < 6; i ++ ) {
  11976. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  11977. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  11978. }
  11979. } else {
  11980. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  11981. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  11982. }
  11983. };
  11984. var deallocateMaterial = function ( material ) {
  11985. var program = material.program;
  11986. if ( program === undefined ) return;
  11987. material.program = undefined;
  11988. // only deallocate GL program if this was the last use of shared program
  11989. // assumed there is only single copy of any program in the _programs list
  11990. // (that's how it's constructed)
  11991. var i, il, programInfo;
  11992. var deleteProgram = false;
  11993. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11994. programInfo = _programs[ i ];
  11995. if ( programInfo.program === program ) {
  11996. programInfo.usedTimes --;
  11997. if ( programInfo.usedTimes === 0 ) {
  11998. deleteProgram = true;
  11999. }
  12000. break;
  12001. }
  12002. }
  12003. if ( deleteProgram === true ) {
  12004. // avoid using array.splice, this is costlier than creating new array from scratch
  12005. var newPrograms = [];
  12006. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12007. programInfo = _programs[ i ];
  12008. if ( programInfo.program !== program ) {
  12009. newPrograms.push( programInfo );
  12010. }
  12011. }
  12012. _programs = newPrograms;
  12013. _gl.deleteProgram( program );
  12014. _this.info.memory.programs --;
  12015. }
  12016. };
  12017. // Buffer initialization
  12018. function initCustomAttributes ( geometry, object ) {
  12019. var nvertices = geometry.vertices.length;
  12020. var material = object.material;
  12021. if ( material.attributes ) {
  12022. if ( geometry.__webglCustomAttributesList === undefined ) {
  12023. geometry.__webglCustomAttributesList = [];
  12024. }
  12025. for ( var a in material.attributes ) {
  12026. var attribute = material.attributes[ a ];
  12027. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12028. attribute.__webglInitialized = true;
  12029. var size = 1; // "f" and "i"
  12030. if ( attribute.type === "v2" ) size = 2;
  12031. else if ( attribute.type === "v3" ) size = 3;
  12032. else if ( attribute.type === "v4" ) size = 4;
  12033. else if ( attribute.type === "c" ) size = 3;
  12034. attribute.size = size;
  12035. attribute.array = new Float32Array( nvertices * size );
  12036. attribute.buffer = _gl.createBuffer();
  12037. attribute.buffer.belongsToAttribute = a;
  12038. attribute.needsUpdate = true;
  12039. }
  12040. geometry.__webglCustomAttributesList.push( attribute );
  12041. }
  12042. }
  12043. };
  12044. function initParticleBuffers ( geometry, object ) {
  12045. var nvertices = geometry.vertices.length;
  12046. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12047. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12048. geometry.__sortArray = [];
  12049. geometry.__webglParticleCount = nvertices;
  12050. initCustomAttributes ( geometry, object );
  12051. };
  12052. function initLineBuffers ( geometry, object ) {
  12053. var nvertices = geometry.vertices.length;
  12054. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12055. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12056. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  12057. geometry.__webglLineCount = nvertices;
  12058. initCustomAttributes ( geometry, object );
  12059. };
  12060. function initMeshBuffers ( geometryGroup, object ) {
  12061. var geometry = object.geometry,
  12062. faces3 = geometryGroup.faces3,
  12063. nvertices = faces3.length * 3,
  12064. ntris = faces3.length * 1,
  12065. nlines = faces3.length * 3,
  12066. material = getBufferMaterial( object, geometryGroup ),
  12067. uvType = bufferGuessUVType( material ),
  12068. normalType = bufferGuessNormalType( material ),
  12069. vertexColorType = bufferGuessVertexColorType( material );
  12070. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  12071. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  12072. if ( normalType ) {
  12073. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  12074. }
  12075. if ( geometry.hasTangents ) {
  12076. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  12077. }
  12078. if ( vertexColorType ) {
  12079. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  12080. }
  12081. if ( uvType ) {
  12082. if ( geometry.faceVertexUvs.length > 0 ) {
  12083. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  12084. }
  12085. if ( geometry.faceVertexUvs.length > 1 ) {
  12086. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  12087. }
  12088. }
  12089. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  12090. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  12091. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  12092. }
  12093. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  12094. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  12095. var m, ml;
  12096. if ( geometryGroup.numMorphTargets ) {
  12097. geometryGroup.__morphTargetsArrays = [];
  12098. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12099. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  12100. }
  12101. }
  12102. if ( geometryGroup.numMorphNormals ) {
  12103. geometryGroup.__morphNormalsArrays = [];
  12104. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12105. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  12106. }
  12107. }
  12108. geometryGroup.__webglFaceCount = ntris * 3;
  12109. geometryGroup.__webglLineCount = nlines * 2;
  12110. // custom attributes
  12111. if ( material.attributes ) {
  12112. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  12113. geometryGroup.__webglCustomAttributesList = [];
  12114. }
  12115. for ( var a in material.attributes ) {
  12116. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  12117. // attribute buffers which are correctly indexed in the setMeshBuffers function
  12118. var originalAttribute = material.attributes[ a ];
  12119. var attribute = {};
  12120. for ( var property in originalAttribute ) {
  12121. attribute[ property ] = originalAttribute[ property ];
  12122. }
  12123. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12124. attribute.__webglInitialized = true;
  12125. var size = 1; // "f" and "i"
  12126. if( attribute.type === "v2" ) size = 2;
  12127. else if( attribute.type === "v3" ) size = 3;
  12128. else if( attribute.type === "v4" ) size = 4;
  12129. else if( attribute.type === "c" ) size = 3;
  12130. attribute.size = size;
  12131. attribute.array = new Float32Array( nvertices * size );
  12132. attribute.buffer = _gl.createBuffer();
  12133. attribute.buffer.belongsToAttribute = a;
  12134. originalAttribute.needsUpdate = true;
  12135. attribute.__original = originalAttribute;
  12136. }
  12137. geometryGroup.__webglCustomAttributesList.push( attribute );
  12138. }
  12139. }
  12140. geometryGroup.__inittedArrays = true;
  12141. };
  12142. function getBufferMaterial( object, geometryGroup ) {
  12143. return object.material instanceof THREE.MeshFaceMaterial
  12144. ? object.material.materials[ geometryGroup.materialIndex ]
  12145. : object.material;
  12146. };
  12147. function materialNeedsSmoothNormals ( material ) {
  12148. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  12149. };
  12150. function bufferGuessNormalType ( material ) {
  12151. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  12152. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  12153. return false;
  12154. }
  12155. if ( materialNeedsSmoothNormals( material ) ) {
  12156. return THREE.SmoothShading;
  12157. } else {
  12158. return THREE.FlatShading;
  12159. }
  12160. };
  12161. function bufferGuessVertexColorType( material ) {
  12162. if ( material.vertexColors ) {
  12163. return material.vertexColors;
  12164. }
  12165. return false;
  12166. };
  12167. function bufferGuessUVType( material ) {
  12168. // material must use some texture to require uvs
  12169. if ( material.map ||
  12170. material.lightMap ||
  12171. material.bumpMap ||
  12172. material.normalMap ||
  12173. material.specularMap ||
  12174. material instanceof THREE.ShaderMaterial ) {
  12175. return true;
  12176. }
  12177. return false;
  12178. };
  12179. //
  12180. function initDirectBuffers( geometry ) {
  12181. var a, attribute, type;
  12182. for ( a in geometry.attributes ) {
  12183. if ( a === "index" ) {
  12184. type = _gl.ELEMENT_ARRAY_BUFFER;
  12185. } else {
  12186. type = _gl.ARRAY_BUFFER;
  12187. }
  12188. attribute = geometry.attributes[ a ];
  12189. if ( attribute.numItems === undefined ) {
  12190. attribute.numItems = attribute.array.length;
  12191. }
  12192. attribute.buffer = _gl.createBuffer();
  12193. _gl.bindBuffer( type, attribute.buffer );
  12194. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  12195. }
  12196. };
  12197. // Buffer setting
  12198. function setParticleBuffers ( geometry, hint, object ) {
  12199. var v, c, vertex, offset, index, color,
  12200. vertices = geometry.vertices,
  12201. vl = vertices.length,
  12202. colors = geometry.colors,
  12203. cl = colors.length,
  12204. vertexArray = geometry.__vertexArray,
  12205. colorArray = geometry.__colorArray,
  12206. sortArray = geometry.__sortArray,
  12207. dirtyVertices = geometry.verticesNeedUpdate,
  12208. dirtyElements = geometry.elementsNeedUpdate,
  12209. dirtyColors = geometry.colorsNeedUpdate,
  12210. customAttributes = geometry.__webglCustomAttributesList,
  12211. i, il,
  12212. a, ca, cal, value,
  12213. customAttribute;
  12214. if ( object.sortParticles ) {
  12215. _projScreenMatrixPS.copy( _projScreenMatrix );
  12216. _projScreenMatrixPS.multiply( object.matrixWorld );
  12217. for ( v = 0; v < vl; v ++ ) {
  12218. vertex = vertices[ v ];
  12219. _vector3.copy( vertex );
  12220. _vector3.applyProjection( _projScreenMatrixPS );
  12221. sortArray[ v ] = [ _vector3.z, v ];
  12222. }
  12223. sortArray.sort( numericalSort );
  12224. for ( v = 0; v < vl; v ++ ) {
  12225. vertex = vertices[ sortArray[v][1] ];
  12226. offset = v * 3;
  12227. vertexArray[ offset ] = vertex.x;
  12228. vertexArray[ offset + 1 ] = vertex.y;
  12229. vertexArray[ offset + 2 ] = vertex.z;
  12230. }
  12231. for ( c = 0; c < cl; c ++ ) {
  12232. offset = c * 3;
  12233. color = colors[ sortArray[c][1] ];
  12234. colorArray[ offset ] = color.r;
  12235. colorArray[ offset + 1 ] = color.g;
  12236. colorArray[ offset + 2 ] = color.b;
  12237. }
  12238. if ( customAttributes ) {
  12239. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12240. customAttribute = customAttributes[ i ];
  12241. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  12242. offset = 0;
  12243. cal = customAttribute.value.length;
  12244. if ( customAttribute.size === 1 ) {
  12245. for ( ca = 0; ca < cal; ca ++ ) {
  12246. index = sortArray[ ca ][ 1 ];
  12247. customAttribute.array[ ca ] = customAttribute.value[ index ];
  12248. }
  12249. } else if ( customAttribute.size === 2 ) {
  12250. for ( ca = 0; ca < cal; ca ++ ) {
  12251. index = sortArray[ ca ][ 1 ];
  12252. value = customAttribute.value[ index ];
  12253. customAttribute.array[ offset ] = value.x;
  12254. customAttribute.array[ offset + 1 ] = value.y;
  12255. offset += 2;
  12256. }
  12257. } else if ( customAttribute.size === 3 ) {
  12258. if ( customAttribute.type === "c" ) {
  12259. for ( ca = 0; ca < cal; ca ++ ) {
  12260. index = sortArray[ ca ][ 1 ];
  12261. value = customAttribute.value[ index ];
  12262. customAttribute.array[ offset ] = value.r;
  12263. customAttribute.array[ offset + 1 ] = value.g;
  12264. customAttribute.array[ offset + 2 ] = value.b;
  12265. offset += 3;
  12266. }
  12267. } else {
  12268. for ( ca = 0; ca < cal; ca ++ ) {
  12269. index = sortArray[ ca ][ 1 ];
  12270. value = customAttribute.value[ index ];
  12271. customAttribute.array[ offset ] = value.x;
  12272. customAttribute.array[ offset + 1 ] = value.y;
  12273. customAttribute.array[ offset + 2 ] = value.z;
  12274. offset += 3;
  12275. }
  12276. }
  12277. } else if ( customAttribute.size === 4 ) {
  12278. for ( ca = 0; ca < cal; ca ++ ) {
  12279. index = sortArray[ ca ][ 1 ];
  12280. value = customAttribute.value[ index ];
  12281. customAttribute.array[ offset ] = value.x;
  12282. customAttribute.array[ offset + 1 ] = value.y;
  12283. customAttribute.array[ offset + 2 ] = value.z;
  12284. customAttribute.array[ offset + 3 ] = value.w;
  12285. offset += 4;
  12286. }
  12287. }
  12288. }
  12289. }
  12290. } else {
  12291. if ( dirtyVertices ) {
  12292. for ( v = 0; v < vl; v ++ ) {
  12293. vertex = vertices[ v ];
  12294. offset = v * 3;
  12295. vertexArray[ offset ] = vertex.x;
  12296. vertexArray[ offset + 1 ] = vertex.y;
  12297. vertexArray[ offset + 2 ] = vertex.z;
  12298. }
  12299. }
  12300. if ( dirtyColors ) {
  12301. for ( c = 0; c < cl; c ++ ) {
  12302. color = colors[ c ];
  12303. offset = c * 3;
  12304. colorArray[ offset ] = color.r;
  12305. colorArray[ offset + 1 ] = color.g;
  12306. colorArray[ offset + 2 ] = color.b;
  12307. }
  12308. }
  12309. if ( customAttributes ) {
  12310. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12311. customAttribute = customAttributes[ i ];
  12312. if ( customAttribute.needsUpdate &&
  12313. ( customAttribute.boundTo === undefined ||
  12314. customAttribute.boundTo === "vertices") ) {
  12315. cal = customAttribute.value.length;
  12316. offset = 0;
  12317. if ( customAttribute.size === 1 ) {
  12318. for ( ca = 0; ca < cal; ca ++ ) {
  12319. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12320. }
  12321. } else if ( customAttribute.size === 2 ) {
  12322. for ( ca = 0; ca < cal; ca ++ ) {
  12323. value = customAttribute.value[ ca ];
  12324. customAttribute.array[ offset ] = value.x;
  12325. customAttribute.array[ offset + 1 ] = value.y;
  12326. offset += 2;
  12327. }
  12328. } else if ( customAttribute.size === 3 ) {
  12329. if ( customAttribute.type === "c" ) {
  12330. for ( ca = 0; ca < cal; ca ++ ) {
  12331. value = customAttribute.value[ ca ];
  12332. customAttribute.array[ offset ] = value.r;
  12333. customAttribute.array[ offset + 1 ] = value.g;
  12334. customAttribute.array[ offset + 2 ] = value.b;
  12335. offset += 3;
  12336. }
  12337. } else {
  12338. for ( ca = 0; ca < cal; ca ++ ) {
  12339. value = customAttribute.value[ ca ];
  12340. customAttribute.array[ offset ] = value.x;
  12341. customAttribute.array[ offset + 1 ] = value.y;
  12342. customAttribute.array[ offset + 2 ] = value.z;
  12343. offset += 3;
  12344. }
  12345. }
  12346. } else if ( customAttribute.size === 4 ) {
  12347. for ( ca = 0; ca < cal; ca ++ ) {
  12348. value = customAttribute.value[ ca ];
  12349. customAttribute.array[ offset ] = value.x;
  12350. customAttribute.array[ offset + 1 ] = value.y;
  12351. customAttribute.array[ offset + 2 ] = value.z;
  12352. customAttribute.array[ offset + 3 ] = value.w;
  12353. offset += 4;
  12354. }
  12355. }
  12356. }
  12357. }
  12358. }
  12359. }
  12360. if ( dirtyVertices || object.sortParticles ) {
  12361. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12362. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12363. }
  12364. if ( dirtyColors || object.sortParticles ) {
  12365. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12366. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12367. }
  12368. if ( customAttributes ) {
  12369. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12370. customAttribute = customAttributes[ i ];
  12371. if ( customAttribute.needsUpdate || object.sortParticles ) {
  12372. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12373. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12374. }
  12375. }
  12376. }
  12377. };
  12378. function setLineBuffers ( geometry, hint ) {
  12379. var v, c, d, vertex, offset, color,
  12380. vertices = geometry.vertices,
  12381. colors = geometry.colors,
  12382. lineDistances = geometry.lineDistances,
  12383. vl = vertices.length,
  12384. cl = colors.length,
  12385. dl = lineDistances.length,
  12386. vertexArray = geometry.__vertexArray,
  12387. colorArray = geometry.__colorArray,
  12388. lineDistanceArray = geometry.__lineDistanceArray,
  12389. dirtyVertices = geometry.verticesNeedUpdate,
  12390. dirtyColors = geometry.colorsNeedUpdate,
  12391. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  12392. customAttributes = geometry.__webglCustomAttributesList,
  12393. i, il,
  12394. a, ca, cal, value,
  12395. customAttribute;
  12396. if ( dirtyVertices ) {
  12397. for ( v = 0; v < vl; v ++ ) {
  12398. vertex = vertices[ v ];
  12399. offset = v * 3;
  12400. vertexArray[ offset ] = vertex.x;
  12401. vertexArray[ offset + 1 ] = vertex.y;
  12402. vertexArray[ offset + 2 ] = vertex.z;
  12403. }
  12404. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12405. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12406. }
  12407. if ( dirtyColors ) {
  12408. for ( c = 0; c < cl; c ++ ) {
  12409. color = colors[ c ];
  12410. offset = c * 3;
  12411. colorArray[ offset ] = color.r;
  12412. colorArray[ offset + 1 ] = color.g;
  12413. colorArray[ offset + 2 ] = color.b;
  12414. }
  12415. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12416. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12417. }
  12418. if ( dirtyLineDistances ) {
  12419. for ( d = 0; d < dl; d ++ ) {
  12420. lineDistanceArray[ d ] = lineDistances[ d ];
  12421. }
  12422. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  12423. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  12424. }
  12425. if ( customAttributes ) {
  12426. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12427. customAttribute = customAttributes[ i ];
  12428. if ( customAttribute.needsUpdate &&
  12429. ( customAttribute.boundTo === undefined ||
  12430. customAttribute.boundTo === "vertices" ) ) {
  12431. offset = 0;
  12432. cal = customAttribute.value.length;
  12433. if ( customAttribute.size === 1 ) {
  12434. for ( ca = 0; ca < cal; ca ++ ) {
  12435. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12436. }
  12437. } else if ( customAttribute.size === 2 ) {
  12438. for ( ca = 0; ca < cal; ca ++ ) {
  12439. value = customAttribute.value[ ca ];
  12440. customAttribute.array[ offset ] = value.x;
  12441. customAttribute.array[ offset + 1 ] = value.y;
  12442. offset += 2;
  12443. }
  12444. } else if ( customAttribute.size === 3 ) {
  12445. if ( customAttribute.type === "c" ) {
  12446. for ( ca = 0; ca < cal; ca ++ ) {
  12447. value = customAttribute.value[ ca ];
  12448. customAttribute.array[ offset ] = value.r;
  12449. customAttribute.array[ offset + 1 ] = value.g;
  12450. customAttribute.array[ offset + 2 ] = value.b;
  12451. offset += 3;
  12452. }
  12453. } else {
  12454. for ( ca = 0; ca < cal; ca ++ ) {
  12455. value = customAttribute.value[ ca ];
  12456. customAttribute.array[ offset ] = value.x;
  12457. customAttribute.array[ offset + 1 ] = value.y;
  12458. customAttribute.array[ offset + 2 ] = value.z;
  12459. offset += 3;
  12460. }
  12461. }
  12462. } else if ( customAttribute.size === 4 ) {
  12463. for ( ca = 0; ca < cal; ca ++ ) {
  12464. value = customAttribute.value[ ca ];
  12465. customAttribute.array[ offset ] = value.x;
  12466. customAttribute.array[ offset + 1 ] = value.y;
  12467. customAttribute.array[ offset + 2 ] = value.z;
  12468. customAttribute.array[ offset + 3 ] = value.w;
  12469. offset += 4;
  12470. }
  12471. }
  12472. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12473. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12474. }
  12475. }
  12476. }
  12477. };
  12478. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12479. if ( ! geometryGroup.__inittedArrays ) {
  12480. return;
  12481. }
  12482. var normalType = bufferGuessNormalType( material ),
  12483. vertexColorType = bufferGuessVertexColorType( material ),
  12484. uvType = bufferGuessUVType( material ),
  12485. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12486. var f, fl, fi, face,
  12487. vertexNormals, faceNormal, normal,
  12488. vertexColors, faceColor,
  12489. vertexTangents,
  12490. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12491. c1, c2, c3, c4,
  12492. sw1, sw2, sw3, sw4,
  12493. si1, si2, si3, si4,
  12494. sa1, sa2, sa3, sa4,
  12495. sb1, sb2, sb3, sb4,
  12496. m, ml, i, il,
  12497. vn, uvi, uv2i,
  12498. vk, vkl, vka,
  12499. nka, chf, faceVertexNormals,
  12500. a,
  12501. vertexIndex = 0,
  12502. offset = 0,
  12503. offset_uv = 0,
  12504. offset_uv2 = 0,
  12505. offset_face = 0,
  12506. offset_normal = 0,
  12507. offset_tangent = 0,
  12508. offset_line = 0,
  12509. offset_color = 0,
  12510. offset_skin = 0,
  12511. offset_morphTarget = 0,
  12512. offset_custom = 0,
  12513. offset_customSrc = 0,
  12514. value,
  12515. vertexArray = geometryGroup.__vertexArray,
  12516. uvArray = geometryGroup.__uvArray,
  12517. uv2Array = geometryGroup.__uv2Array,
  12518. normalArray = geometryGroup.__normalArray,
  12519. tangentArray = geometryGroup.__tangentArray,
  12520. colorArray = geometryGroup.__colorArray,
  12521. skinIndexArray = geometryGroup.__skinIndexArray,
  12522. skinWeightArray = geometryGroup.__skinWeightArray,
  12523. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12524. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12525. customAttributes = geometryGroup.__webglCustomAttributesList,
  12526. customAttribute,
  12527. faceArray = geometryGroup.__faceArray,
  12528. lineArray = geometryGroup.__lineArray,
  12529. geometry = object.geometry, // this is shared for all chunks
  12530. dirtyVertices = geometry.verticesNeedUpdate,
  12531. dirtyElements = geometry.elementsNeedUpdate,
  12532. dirtyUvs = geometry.uvsNeedUpdate,
  12533. dirtyNormals = geometry.normalsNeedUpdate,
  12534. dirtyTangents = geometry.tangentsNeedUpdate,
  12535. dirtyColors = geometry.colorsNeedUpdate,
  12536. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12537. vertices = geometry.vertices,
  12538. chunk_faces3 = geometryGroup.faces3,
  12539. obj_faces = geometry.faces,
  12540. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12541. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12542. obj_colors = geometry.colors,
  12543. obj_skinIndices = geometry.skinIndices,
  12544. obj_skinWeights = geometry.skinWeights,
  12545. morphTargets = geometry.morphTargets,
  12546. morphNormals = geometry.morphNormals;
  12547. if ( dirtyVertices ) {
  12548. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12549. face = obj_faces[ chunk_faces3[ f ] ];
  12550. v1 = vertices[ face.a ];
  12551. v2 = vertices[ face.b ];
  12552. v3 = vertices[ face.c ];
  12553. vertexArray[ offset ] = v1.x;
  12554. vertexArray[ offset + 1 ] = v1.y;
  12555. vertexArray[ offset + 2 ] = v1.z;
  12556. vertexArray[ offset + 3 ] = v2.x;
  12557. vertexArray[ offset + 4 ] = v2.y;
  12558. vertexArray[ offset + 5 ] = v2.z;
  12559. vertexArray[ offset + 6 ] = v3.x;
  12560. vertexArray[ offset + 7 ] = v3.y;
  12561. vertexArray[ offset + 8 ] = v3.z;
  12562. offset += 9;
  12563. }
  12564. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12565. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12566. }
  12567. if ( dirtyMorphTargets ) {
  12568. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  12569. offset_morphTarget = 0;
  12570. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12571. chf = chunk_faces3[ f ];
  12572. face = obj_faces[ chf ];
  12573. // morph positions
  12574. v1 = morphTargets[ vk ].vertices[ face.a ];
  12575. v2 = morphTargets[ vk ].vertices[ face.b ];
  12576. v3 = morphTargets[ vk ].vertices[ face.c ];
  12577. vka = morphTargetsArrays[ vk ];
  12578. vka[ offset_morphTarget ] = v1.x;
  12579. vka[ offset_morphTarget + 1 ] = v1.y;
  12580. vka[ offset_morphTarget + 2 ] = v1.z;
  12581. vka[ offset_morphTarget + 3 ] = v2.x;
  12582. vka[ offset_morphTarget + 4 ] = v2.y;
  12583. vka[ offset_morphTarget + 5 ] = v2.z;
  12584. vka[ offset_morphTarget + 6 ] = v3.x;
  12585. vka[ offset_morphTarget + 7 ] = v3.y;
  12586. vka[ offset_morphTarget + 8 ] = v3.z;
  12587. // morph normals
  12588. if ( material.morphNormals ) {
  12589. if ( needsSmoothNormals ) {
  12590. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12591. n1 = faceVertexNormals.a;
  12592. n2 = faceVertexNormals.b;
  12593. n3 = faceVertexNormals.c;
  12594. } else {
  12595. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12596. n2 = n1;
  12597. n3 = n1;
  12598. }
  12599. nka = morphNormalsArrays[ vk ];
  12600. nka[ offset_morphTarget ] = n1.x;
  12601. nka[ offset_morphTarget + 1 ] = n1.y;
  12602. nka[ offset_morphTarget + 2 ] = n1.z;
  12603. nka[ offset_morphTarget + 3 ] = n2.x;
  12604. nka[ offset_morphTarget + 4 ] = n2.y;
  12605. nka[ offset_morphTarget + 5 ] = n2.z;
  12606. nka[ offset_morphTarget + 6 ] = n3.x;
  12607. nka[ offset_morphTarget + 7 ] = n3.y;
  12608. nka[ offset_morphTarget + 8 ] = n3.z;
  12609. }
  12610. //
  12611. offset_morphTarget += 9;
  12612. }
  12613. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  12614. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  12615. if ( material.morphNormals ) {
  12616. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  12617. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  12618. }
  12619. }
  12620. }
  12621. if ( obj_skinWeights.length ) {
  12622. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12623. face = obj_faces[ chunk_faces3[ f ] ];
  12624. // weights
  12625. sw1 = obj_skinWeights[ face.a ];
  12626. sw2 = obj_skinWeights[ face.b ];
  12627. sw3 = obj_skinWeights[ face.c ];
  12628. skinWeightArray[ offset_skin ] = sw1.x;
  12629. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12630. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12631. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12632. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12633. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12634. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12635. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12636. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12637. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12638. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12639. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12640. // indices
  12641. si1 = obj_skinIndices[ face.a ];
  12642. si2 = obj_skinIndices[ face.b ];
  12643. si3 = obj_skinIndices[ face.c ];
  12644. skinIndexArray[ offset_skin ] = si1.x;
  12645. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12646. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12647. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12648. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12649. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12650. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12651. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12652. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12653. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12654. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12655. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12656. offset_skin += 12;
  12657. }
  12658. if ( offset_skin > 0 ) {
  12659. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12660. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  12661. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12662. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  12663. }
  12664. }
  12665. if ( dirtyColors && vertexColorType ) {
  12666. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12667. face = obj_faces[ chunk_faces3[ f ] ];
  12668. vertexColors = face.vertexColors;
  12669. faceColor = face.color;
  12670. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  12671. c1 = vertexColors[ 0 ];
  12672. c2 = vertexColors[ 1 ];
  12673. c3 = vertexColors[ 2 ];
  12674. } else {
  12675. c1 = faceColor;
  12676. c2 = faceColor;
  12677. c3 = faceColor;
  12678. }
  12679. colorArray[ offset_color ] = c1.r;
  12680. colorArray[ offset_color + 1 ] = c1.g;
  12681. colorArray[ offset_color + 2 ] = c1.b;
  12682. colorArray[ offset_color + 3 ] = c2.r;
  12683. colorArray[ offset_color + 4 ] = c2.g;
  12684. colorArray[ offset_color + 5 ] = c2.b;
  12685. colorArray[ offset_color + 6 ] = c3.r;
  12686. colorArray[ offset_color + 7 ] = c3.g;
  12687. colorArray[ offset_color + 8 ] = c3.b;
  12688. offset_color += 9;
  12689. }
  12690. if ( offset_color > 0 ) {
  12691. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12692. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12693. }
  12694. }
  12695. if ( dirtyTangents && geometry.hasTangents ) {
  12696. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12697. face = obj_faces[ chunk_faces3[ f ] ];
  12698. vertexTangents = face.vertexTangents;
  12699. t1 = vertexTangents[ 0 ];
  12700. t2 = vertexTangents[ 1 ];
  12701. t3 = vertexTangents[ 2 ];
  12702. tangentArray[ offset_tangent ] = t1.x;
  12703. tangentArray[ offset_tangent + 1 ] = t1.y;
  12704. tangentArray[ offset_tangent + 2 ] = t1.z;
  12705. tangentArray[ offset_tangent + 3 ] = t1.w;
  12706. tangentArray[ offset_tangent + 4 ] = t2.x;
  12707. tangentArray[ offset_tangent + 5 ] = t2.y;
  12708. tangentArray[ offset_tangent + 6 ] = t2.z;
  12709. tangentArray[ offset_tangent + 7 ] = t2.w;
  12710. tangentArray[ offset_tangent + 8 ] = t3.x;
  12711. tangentArray[ offset_tangent + 9 ] = t3.y;
  12712. tangentArray[ offset_tangent + 10 ] = t3.z;
  12713. tangentArray[ offset_tangent + 11 ] = t3.w;
  12714. offset_tangent += 12;
  12715. }
  12716. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12717. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  12718. }
  12719. if ( dirtyNormals && normalType ) {
  12720. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12721. face = obj_faces[ chunk_faces3[ f ] ];
  12722. vertexNormals = face.vertexNormals;
  12723. faceNormal = face.normal;
  12724. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  12725. for ( i = 0; i < 3; i ++ ) {
  12726. vn = vertexNormals[ i ];
  12727. normalArray[ offset_normal ] = vn.x;
  12728. normalArray[ offset_normal + 1 ] = vn.y;
  12729. normalArray[ offset_normal + 2 ] = vn.z;
  12730. offset_normal += 3;
  12731. }
  12732. } else {
  12733. for ( i = 0; i < 3; i ++ ) {
  12734. normalArray[ offset_normal ] = faceNormal.x;
  12735. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12736. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12737. offset_normal += 3;
  12738. }
  12739. }
  12740. }
  12741. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12742. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12743. }
  12744. if ( dirtyUvs && obj_uvs && uvType ) {
  12745. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12746. fi = chunk_faces3[ f ];
  12747. uv = obj_uvs[ fi ];
  12748. if ( uv === undefined ) continue;
  12749. for ( i = 0; i < 3; i ++ ) {
  12750. uvi = uv[ i ];
  12751. uvArray[ offset_uv ] = uvi.x;
  12752. uvArray[ offset_uv + 1 ] = uvi.y;
  12753. offset_uv += 2;
  12754. }
  12755. }
  12756. if ( offset_uv > 0 ) {
  12757. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12758. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  12759. }
  12760. }
  12761. if ( dirtyUvs && obj_uvs2 && uvType ) {
  12762. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12763. fi = chunk_faces3[ f ];
  12764. uv2 = obj_uvs2[ fi ];
  12765. if ( uv2 === undefined ) continue;
  12766. for ( i = 0; i < 3; i ++ ) {
  12767. uv2i = uv2[ i ];
  12768. uv2Array[ offset_uv2 ] = uv2i.x;
  12769. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12770. offset_uv2 += 2;
  12771. }
  12772. }
  12773. if ( offset_uv2 > 0 ) {
  12774. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12775. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  12776. }
  12777. }
  12778. if ( dirtyElements ) {
  12779. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12780. faceArray[ offset_face ] = vertexIndex;
  12781. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12782. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  12783. offset_face += 3;
  12784. lineArray[ offset_line ] = vertexIndex;
  12785. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12786. lineArray[ offset_line + 2 ] = vertexIndex;
  12787. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  12788. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12789. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12790. offset_line += 6;
  12791. vertexIndex += 3;
  12792. }
  12793. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12794. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  12795. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12796. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  12797. }
  12798. if ( customAttributes ) {
  12799. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12800. customAttribute = customAttributes[ i ];
  12801. if ( ! customAttribute.__original.needsUpdate ) continue;
  12802. offset_custom = 0;
  12803. offset_customSrc = 0;
  12804. if ( customAttribute.size === 1 ) {
  12805. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12806. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12807. face = obj_faces[ chunk_faces3[ f ] ];
  12808. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12809. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12810. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12811. offset_custom += 3;
  12812. }
  12813. } else if ( customAttribute.boundTo === "faces" ) {
  12814. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12815. value = customAttribute.value[ chunk_faces3[ f ] ];
  12816. customAttribute.array[ offset_custom ] = value;
  12817. customAttribute.array[ offset_custom + 1 ] = value;
  12818. customAttribute.array[ offset_custom + 2 ] = value;
  12819. offset_custom += 3;
  12820. }
  12821. }
  12822. } else if ( customAttribute.size === 2 ) {
  12823. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12824. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12825. face = obj_faces[ chunk_faces3[ f ] ];
  12826. v1 = customAttribute.value[ face.a ];
  12827. v2 = customAttribute.value[ face.b ];
  12828. v3 = customAttribute.value[ face.c ];
  12829. customAttribute.array[ offset_custom ] = v1.x;
  12830. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12831. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12832. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12833. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12834. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12835. offset_custom += 6;
  12836. }
  12837. } else if ( customAttribute.boundTo === "faces" ) {
  12838. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12839. value = customAttribute.value[ chunk_faces3[ f ] ];
  12840. v1 = value;
  12841. v2 = value;
  12842. v3 = value;
  12843. customAttribute.array[ offset_custom ] = v1.x;
  12844. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12845. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12846. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12847. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12848. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12849. offset_custom += 6;
  12850. }
  12851. }
  12852. } else if ( customAttribute.size === 3 ) {
  12853. var pp;
  12854. if ( customAttribute.type === "c" ) {
  12855. pp = [ "r", "g", "b" ];
  12856. } else {
  12857. pp = [ "x", "y", "z" ];
  12858. }
  12859. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12860. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12861. face = obj_faces[ chunk_faces3[ f ] ];
  12862. v1 = customAttribute.value[ face.a ];
  12863. v2 = customAttribute.value[ face.b ];
  12864. v3 = customAttribute.value[ face.c ];
  12865. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12866. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12867. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12868. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12869. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12870. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12871. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12872. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12873. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12874. offset_custom += 9;
  12875. }
  12876. } else if ( customAttribute.boundTo === "faces" ) {
  12877. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12878. value = customAttribute.value[ chunk_faces3[ f ] ];
  12879. v1 = value;
  12880. v2 = value;
  12881. v3 = value;
  12882. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12883. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12884. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12885. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12886. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12887. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12888. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12889. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12890. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12891. offset_custom += 9;
  12892. }
  12893. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12894. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12895. value = customAttribute.value[ chunk_faces3[ f ] ];
  12896. v1 = value[ 0 ];
  12897. v2 = value[ 1 ];
  12898. v3 = value[ 2 ];
  12899. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12900. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12901. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12902. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12903. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12904. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12905. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12906. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12907. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12908. offset_custom += 9;
  12909. }
  12910. }
  12911. } else if ( customAttribute.size === 4 ) {
  12912. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12913. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12914. face = obj_faces[ chunk_faces3[ f ] ];
  12915. v1 = customAttribute.value[ face.a ];
  12916. v2 = customAttribute.value[ face.b ];
  12917. v3 = customAttribute.value[ face.c ];
  12918. customAttribute.array[ offset_custom ] = v1.x;
  12919. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12920. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12921. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12922. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12923. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12924. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12925. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12926. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12927. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12928. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12929. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12930. offset_custom += 12;
  12931. }
  12932. } else if ( customAttribute.boundTo === "faces" ) {
  12933. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12934. value = customAttribute.value[ chunk_faces3[ f ] ];
  12935. v1 = value;
  12936. v2 = value;
  12937. v3 = value;
  12938. customAttribute.array[ offset_custom ] = v1.x;
  12939. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12940. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12941. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12942. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12943. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12944. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12945. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12946. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12947. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12948. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12949. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12950. offset_custom += 12;
  12951. }
  12952. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12953. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12954. value = customAttribute.value[ chunk_faces3[ f ] ];
  12955. v1 = value[ 0 ];
  12956. v2 = value[ 1 ];
  12957. v3 = value[ 2 ];
  12958. customAttribute.array[ offset_custom ] = v1.x;
  12959. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12960. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12961. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12962. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12963. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12964. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12965. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12966. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12967. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12968. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12969. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12970. offset_custom += 12;
  12971. }
  12972. }
  12973. }
  12974. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12975. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12976. }
  12977. }
  12978. if ( dispose ) {
  12979. delete geometryGroup.__inittedArrays;
  12980. delete geometryGroup.__colorArray;
  12981. delete geometryGroup.__normalArray;
  12982. delete geometryGroup.__tangentArray;
  12983. delete geometryGroup.__uvArray;
  12984. delete geometryGroup.__uv2Array;
  12985. delete geometryGroup.__faceArray;
  12986. delete geometryGroup.__vertexArray;
  12987. delete geometryGroup.__lineArray;
  12988. delete geometryGroup.__skinIndexArray;
  12989. delete geometryGroup.__skinWeightArray;
  12990. }
  12991. };
  12992. function setDirectBuffers ( geometry, hint, dispose ) {
  12993. var attributes = geometry.attributes;
  12994. var attributeName, attributeItem;
  12995. for ( attributeName in attributes ) {
  12996. attributeItem = attributes[ attributeName ];
  12997. if ( attributeItem.needsUpdate ) {
  12998. if ( attributeName === 'index' ) {
  12999. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  13000. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  13001. } else {
  13002. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13003. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  13004. }
  13005. attributeItem.needsUpdate = false;
  13006. }
  13007. if ( dispose && ! attributeItem.dynamic ) {
  13008. attributeItem.array = null;
  13009. }
  13010. }
  13011. };
  13012. // Buffer rendering
  13013. this.renderBufferImmediate = function ( object, program, material ) {
  13014. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  13015. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  13016. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  13017. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  13018. if ( object.hasPositions ) {
  13019. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  13020. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  13021. _gl.enableVertexAttribArray( program.attributes.position );
  13022. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13023. }
  13024. if ( object.hasNormals ) {
  13025. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  13026. if ( material.shading === THREE.FlatShading ) {
  13027. var nx, ny, nz,
  13028. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  13029. normalArray,
  13030. i, il = object.count * 3;
  13031. for( i = 0; i < il; i += 9 ) {
  13032. normalArray = object.normalArray;
  13033. nax = normalArray[ i ];
  13034. nay = normalArray[ i + 1 ];
  13035. naz = normalArray[ i + 2 ];
  13036. nbx = normalArray[ i + 3 ];
  13037. nby = normalArray[ i + 4 ];
  13038. nbz = normalArray[ i + 5 ];
  13039. ncx = normalArray[ i + 6 ];
  13040. ncy = normalArray[ i + 7 ];
  13041. ncz = normalArray[ i + 8 ];
  13042. nx = ( nax + nbx + ncx ) / 3;
  13043. ny = ( nay + nby + ncy ) / 3;
  13044. nz = ( naz + nbz + ncz ) / 3;
  13045. normalArray[ i ] = nx;
  13046. normalArray[ i + 1 ] = ny;
  13047. normalArray[ i + 2 ] = nz;
  13048. normalArray[ i + 3 ] = nx;
  13049. normalArray[ i + 4 ] = ny;
  13050. normalArray[ i + 5 ] = nz;
  13051. normalArray[ i + 6 ] = nx;
  13052. normalArray[ i + 7 ] = ny;
  13053. normalArray[ i + 8 ] = nz;
  13054. }
  13055. }
  13056. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13057. _gl.enableVertexAttribArray( program.attributes.normal );
  13058. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13059. }
  13060. if ( object.hasUvs && material.map ) {
  13061. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13062. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13063. _gl.enableVertexAttribArray( program.attributes.uv );
  13064. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13065. }
  13066. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13067. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13068. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13069. _gl.enableVertexAttribArray( program.attributes.color );
  13070. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13071. }
  13072. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13073. object.count = 0;
  13074. };
  13075. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13076. if ( material.visible === false ) return;
  13077. var linewidth, a, attribute;
  13078. var attributeItem, attributeName, attributePointer, attributeSize;
  13079. var program = setProgram( camera, lights, fog, material, object );
  13080. var programAttributes = program.attributes;
  13081. var geometryAttributes = geometry.attributes;
  13082. var updateBuffers = false,
  13083. wireframeBit = material.wireframe ? 1 : 0,
  13084. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13085. if ( geometryHash !== _currentGeometryGroupHash ) {
  13086. _currentGeometryGroupHash = geometryHash;
  13087. updateBuffers = true;
  13088. }
  13089. if ( updateBuffers ) {
  13090. disableAttributes();
  13091. }
  13092. // render mesh
  13093. if ( object instanceof THREE.Mesh ) {
  13094. var index = geometryAttributes[ "index" ];
  13095. // indexed triangles
  13096. if ( index ) {
  13097. var offsets = geometry.offsets;
  13098. // if there is more than 1 chunk
  13099. // must set attribute pointers to use new offsets for each chunk
  13100. // even if geometry and materials didn't change
  13101. if ( offsets.length > 1 ) updateBuffers = true;
  13102. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13103. var startIndex = offsets[ i ].index;
  13104. if ( updateBuffers ) {
  13105. for ( attributeName in programAttributes ) {
  13106. attributePointer = programAttributes[ attributeName ];
  13107. attributeItem = geometryAttributes[ attributeName ];
  13108. if ( attributePointer >= 0 ) {
  13109. if ( attributeItem ) {
  13110. attributeSize = attributeItem.itemSize;
  13111. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13112. enableAttribute( attributePointer );
  13113. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13114. } else if ( material.defaultAttributeValues ) {
  13115. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13116. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13117. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13118. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13119. }
  13120. }
  13121. }
  13122. }
  13123. // indices
  13124. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13125. }
  13126. // render indexed triangles
  13127. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  13128. _this.info.render.calls ++;
  13129. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13130. _this.info.render.faces += offsets[ i ].count / 3;
  13131. }
  13132. // non-indexed triangles
  13133. } else {
  13134. if ( updateBuffers ) {
  13135. for ( attributeName in programAttributes ) {
  13136. if ( attributeName === 'index') continue;
  13137. attributePointer = programAttributes[ attributeName ];
  13138. attributeItem = geometryAttributes[ attributeName ];
  13139. if ( attributePointer >= 0 ) {
  13140. if ( attributeItem ) {
  13141. attributeSize = attributeItem.itemSize;
  13142. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13143. enableAttribute( attributePointer );
  13144. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13145. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13146. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13147. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13148. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13149. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13150. }
  13151. }
  13152. }
  13153. }
  13154. }
  13155. var position = geometry.attributes[ "position" ];
  13156. // render non-indexed triangles
  13157. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  13158. _this.info.render.calls ++;
  13159. _this.info.render.vertices += position.numItems / 3;
  13160. _this.info.render.faces += position.numItems / 3 / 3;
  13161. }
  13162. // render particles
  13163. } else if ( object instanceof THREE.ParticleSystem ) {
  13164. if ( updateBuffers ) {
  13165. for ( attributeName in programAttributes ) {
  13166. attributePointer = programAttributes[ attributeName ];
  13167. attributeItem = geometryAttributes[ attributeName ];
  13168. if ( attributePointer >= 0 ) {
  13169. if ( attributeItem ) {
  13170. attributeSize = attributeItem.itemSize;
  13171. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13172. enableAttribute( attributePointer );
  13173. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13174. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13175. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13176. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13177. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13178. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13179. }
  13180. }
  13181. }
  13182. }
  13183. var position = geometryAttributes[ "position" ];
  13184. // render particles
  13185. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  13186. _this.info.render.calls ++;
  13187. _this.info.render.points += position.numItems / 3;
  13188. }
  13189. } else if ( object instanceof THREE.Line ) {
  13190. if ( updateBuffers ) {
  13191. for ( attributeName in programAttributes ) {
  13192. attributePointer = programAttributes[ attributeName ];
  13193. attributeItem = geometryAttributes[ attributeName ];
  13194. if ( attributePointer >= 0 ) {
  13195. if ( attributeItem ) {
  13196. attributeSize = attributeItem.itemSize;
  13197. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13198. enableAttribute( attributePointer );
  13199. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13200. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13201. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13202. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13203. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13204. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13205. }
  13206. }
  13207. }
  13208. }
  13209. // render lines
  13210. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13211. setLineWidth( material.linewidth );
  13212. var position = geometryAttributes[ "position" ];
  13213. _gl.drawArrays( primitives, 0, position.numItems / 3 );
  13214. _this.info.render.calls ++;
  13215. _this.info.render.points += position.numItems;
  13216. }
  13217. }
  13218. };
  13219. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13220. if ( material.visible === false ) return;
  13221. var linewidth, a, attribute, i, il;
  13222. var program = setProgram( camera, lights, fog, material, object );
  13223. var attributes = program.attributes;
  13224. var updateBuffers = false,
  13225. wireframeBit = material.wireframe ? 1 : 0,
  13226. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13227. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13228. _currentGeometryGroupHash = geometryGroupHash;
  13229. updateBuffers = true;
  13230. }
  13231. if ( updateBuffers ) {
  13232. disableAttributes();
  13233. }
  13234. // vertices
  13235. if ( !material.morphTargets && attributes.position >= 0 ) {
  13236. if ( updateBuffers ) {
  13237. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13238. enableAttribute( attributes.position );
  13239. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13240. }
  13241. } else {
  13242. if ( object.morphTargetBase ) {
  13243. setupMorphTargets( material, geometryGroup, object );
  13244. }
  13245. }
  13246. if ( updateBuffers ) {
  13247. // custom attributes
  13248. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13249. if ( geometryGroup.__webglCustomAttributesList ) {
  13250. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13251. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13252. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13253. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13254. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13255. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13256. }
  13257. }
  13258. }
  13259. // colors
  13260. if ( attributes.color >= 0 ) {
  13261. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  13262. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13263. enableAttribute( attributes.color );
  13264. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13265. } else if ( material.defaultAttributeValues ) {
  13266. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  13267. }
  13268. }
  13269. // normals
  13270. if ( attributes.normal >= 0 ) {
  13271. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13272. enableAttribute( attributes.normal );
  13273. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13274. }
  13275. // tangents
  13276. if ( attributes.tangent >= 0 ) {
  13277. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13278. enableAttribute( attributes.tangent );
  13279. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13280. }
  13281. // uvs
  13282. if ( attributes.uv >= 0 ) {
  13283. if ( object.geometry.faceVertexUvs[0] ) {
  13284. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13285. enableAttribute( attributes.uv );
  13286. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13287. } else if ( material.defaultAttributeValues ) {
  13288. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  13289. }
  13290. }
  13291. if ( attributes.uv2 >= 0 ) {
  13292. if ( object.geometry.faceVertexUvs[1] ) {
  13293. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13294. enableAttribute( attributes.uv2 );
  13295. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13296. } else if ( material.defaultAttributeValues ) {
  13297. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  13298. }
  13299. }
  13300. if ( material.skinning &&
  13301. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13302. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13303. enableAttribute( attributes.skinIndex );
  13304. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13305. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13306. enableAttribute( attributes.skinWeight );
  13307. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13308. }
  13309. // line distances
  13310. if ( attributes.lineDistance >= 0 ) {
  13311. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13312. enableAttribute( attributes.lineDistance );
  13313. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13314. }
  13315. }
  13316. // render mesh
  13317. if ( object instanceof THREE.Mesh ) {
  13318. // wireframe
  13319. if ( material.wireframe ) {
  13320. setLineWidth( material.wireframeLinewidth );
  13321. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13322. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  13323. // triangles
  13324. } else {
  13325. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13326. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  13327. }
  13328. _this.info.render.calls ++;
  13329. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13330. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13331. // render lines
  13332. } else if ( object instanceof THREE.Line ) {
  13333. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13334. setLineWidth( material.linewidth );
  13335. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  13336. _this.info.render.calls ++;
  13337. // render particles
  13338. } else if ( object instanceof THREE.ParticleSystem ) {
  13339. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13340. _this.info.render.calls ++;
  13341. _this.info.render.points += geometryGroup.__webglParticleCount;
  13342. }
  13343. };
  13344. function enableAttribute( attribute ) {
  13345. if ( ! _enabledAttributes[ attribute ] ) {
  13346. _gl.enableVertexAttribArray( attribute );
  13347. _enabledAttributes[ attribute ] = true;
  13348. }
  13349. };
  13350. function disableAttributes() {
  13351. for ( var attribute in _enabledAttributes ) {
  13352. if ( _enabledAttributes[ attribute ] ) {
  13353. _gl.disableVertexAttribArray( attribute );
  13354. _enabledAttributes[ attribute ] = false;
  13355. }
  13356. }
  13357. };
  13358. function setupMorphTargets ( material, geometryGroup, object ) {
  13359. // set base
  13360. var attributes = material.program.attributes;
  13361. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13362. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13363. enableAttribute( attributes.position );
  13364. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13365. } else if ( attributes.position >= 0 ) {
  13366. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13367. enableAttribute( attributes.position );
  13368. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13369. }
  13370. if ( object.morphTargetForcedOrder.length ) {
  13371. // set forced order
  13372. var m = 0;
  13373. var order = object.morphTargetForcedOrder;
  13374. var influences = object.morphTargetInfluences;
  13375. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13376. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13377. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13378. enableAttribute( attributes[ "morphTarget" + m ] );
  13379. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13380. }
  13381. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13382. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13383. enableAttribute( attributes[ "morphNormal" + m ] );
  13384. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13385. }
  13386. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13387. m ++;
  13388. }
  13389. } else {
  13390. // find the most influencing
  13391. var influence, activeInfluenceIndices = [];
  13392. var influences = object.morphTargetInfluences;
  13393. var i, il = influences.length;
  13394. for ( i = 0; i < il; i ++ ) {
  13395. influence = influences[ i ];
  13396. if ( influence > 0 ) {
  13397. activeInfluenceIndices.push( [ influence, i ] );
  13398. }
  13399. }
  13400. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13401. activeInfluenceIndices.sort( numericalSort );
  13402. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13403. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13404. activeInfluenceIndices.sort( numericalSort );
  13405. } else if ( activeInfluenceIndices.length === 0 ) {
  13406. activeInfluenceIndices.push( [ 0, 0 ] );
  13407. };
  13408. var influenceIndex, m = 0;
  13409. while ( m < material.numSupportedMorphTargets ) {
  13410. if ( activeInfluenceIndices[ m ] ) {
  13411. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13412. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13413. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13414. enableAttribute( attributes[ "morphTarget" + m ] );
  13415. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13416. }
  13417. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13418. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13419. enableAttribute( attributes[ "morphNormal" + m ] );
  13420. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13421. }
  13422. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13423. } else {
  13424. /*
  13425. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13426. if ( material.morphNormals ) {
  13427. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13428. }
  13429. */
  13430. object.__webglMorphTargetInfluences[ m ] = 0;
  13431. }
  13432. m ++;
  13433. }
  13434. }
  13435. // load updated influences uniform
  13436. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13437. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13438. }
  13439. };
  13440. // Sorting
  13441. function painterSortStable ( a, b ) {
  13442. if ( a.z !== b.z ) {
  13443. return b.z - a.z;
  13444. } else {
  13445. return a.id - b.id;
  13446. }
  13447. };
  13448. function numericalSort ( a, b ) {
  13449. return b[ 0 ] - a[ 0 ];
  13450. };
  13451. // Rendering
  13452. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13453. if ( camera instanceof THREE.Camera === false ) {
  13454. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13455. return;
  13456. }
  13457. var i, il,
  13458. webglObject, object,
  13459. renderList,
  13460. lights = scene.__lights,
  13461. fog = scene.fog;
  13462. // reset caching for this frame
  13463. _currentMaterialId = -1;
  13464. _lightsNeedUpdate = true;
  13465. // update scene graph
  13466. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13467. // update camera matrices and frustum
  13468. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13469. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13470. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13471. _frustum.setFromMatrix( _projScreenMatrix );
  13472. // update WebGL objects
  13473. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13474. // custom render plugins (pre pass)
  13475. renderPlugins( this.renderPluginsPre, scene, camera );
  13476. //
  13477. _this.info.render.calls = 0;
  13478. _this.info.render.vertices = 0;
  13479. _this.info.render.faces = 0;
  13480. _this.info.render.points = 0;
  13481. this.setRenderTarget( renderTarget );
  13482. if ( this.autoClear || forceClear ) {
  13483. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13484. }
  13485. // set matrices for regular objects (frustum culled)
  13486. renderList = scene.__webglObjects;
  13487. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13488. webglObject = renderList[ i ];
  13489. object = webglObject.object;
  13490. webglObject.id = i;
  13491. webglObject.render = false;
  13492. if ( object.visible ) {
  13493. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  13494. setupMatrices( object, camera );
  13495. unrollBufferMaterial( webglObject );
  13496. webglObject.render = true;
  13497. if ( this.sortObjects === true ) {
  13498. if ( object.renderDepth !== null ) {
  13499. webglObject.z = object.renderDepth;
  13500. } else {
  13501. _vector3.setFromMatrixPosition( object.matrixWorld );
  13502. _vector3.applyProjection( _projScreenMatrix );
  13503. webglObject.z = _vector3.z;
  13504. }
  13505. }
  13506. }
  13507. }
  13508. }
  13509. if ( this.sortObjects ) {
  13510. renderList.sort( painterSortStable );
  13511. }
  13512. // set matrices for immediate objects
  13513. renderList = scene.__webglObjectsImmediate;
  13514. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13515. webglObject = renderList[ i ];
  13516. object = webglObject.object;
  13517. if ( object.visible ) {
  13518. setupMatrices( object, camera );
  13519. unrollImmediateBufferMaterial( webglObject );
  13520. }
  13521. }
  13522. if ( scene.overrideMaterial ) {
  13523. var material = scene.overrideMaterial;
  13524. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13525. this.setDepthTest( material.depthTest );
  13526. this.setDepthWrite( material.depthWrite );
  13527. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13528. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13529. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13530. } else {
  13531. var material = null;
  13532. // opaque pass (front-to-back order)
  13533. this.setBlending( THREE.NoBlending );
  13534. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13535. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13536. // transparent pass (back-to-front order)
  13537. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13538. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13539. }
  13540. // custom render plugins (post pass)
  13541. renderPlugins( this.renderPluginsPost, scene, camera );
  13542. // Generate mipmap if we're using any kind of mipmap filtering
  13543. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13544. updateRenderTargetMipmap( renderTarget );
  13545. }
  13546. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13547. this.setDepthTest( true );
  13548. this.setDepthWrite( true );
  13549. // _gl.finish();
  13550. };
  13551. function renderPlugins( plugins, scene, camera ) {
  13552. if ( ! plugins.length ) return;
  13553. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13554. // reset state for plugin (to start from clean slate)
  13555. _currentProgram = null;
  13556. _currentCamera = null;
  13557. _oldBlending = -1;
  13558. _oldDepthTest = -1;
  13559. _oldDepthWrite = -1;
  13560. _oldDoubleSided = -1;
  13561. _oldFlipSided = -1;
  13562. _currentGeometryGroupHash = -1;
  13563. _currentMaterialId = -1;
  13564. _lightsNeedUpdate = true;
  13565. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13566. // reset state after plugin (anything could have changed)
  13567. _currentProgram = null;
  13568. _currentCamera = null;
  13569. _oldBlending = -1;
  13570. _oldDepthTest = -1;
  13571. _oldDepthWrite = -1;
  13572. _oldDoubleSided = -1;
  13573. _oldFlipSided = -1;
  13574. _currentGeometryGroupHash = -1;
  13575. _currentMaterialId = -1;
  13576. _lightsNeedUpdate = true;
  13577. }
  13578. };
  13579. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13580. var webglObject, object, buffer, material, start, end, delta;
  13581. if ( reverse ) {
  13582. start = renderList.length - 1;
  13583. end = -1;
  13584. delta = -1;
  13585. } else {
  13586. start = 0;
  13587. end = renderList.length;
  13588. delta = 1;
  13589. }
  13590. for ( var i = start; i !== end; i += delta ) {
  13591. webglObject = renderList[ i ];
  13592. if ( webglObject.render ) {
  13593. object = webglObject.object;
  13594. buffer = webglObject.buffer;
  13595. if ( overrideMaterial ) {
  13596. material = overrideMaterial;
  13597. } else {
  13598. material = webglObject[ materialType ];
  13599. if ( ! material ) continue;
  13600. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13601. _this.setDepthTest( material.depthTest );
  13602. _this.setDepthWrite( material.depthWrite );
  13603. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13604. }
  13605. _this.setMaterialFaces( material );
  13606. if ( buffer instanceof THREE.BufferGeometry ) {
  13607. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  13608. } else {
  13609. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  13610. }
  13611. }
  13612. }
  13613. };
  13614. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13615. var webglObject, object, material, program;
  13616. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13617. webglObject = renderList[ i ];
  13618. object = webglObject.object;
  13619. if ( object.visible ) {
  13620. if ( overrideMaterial ) {
  13621. material = overrideMaterial;
  13622. } else {
  13623. material = webglObject[ materialType ];
  13624. if ( ! material ) continue;
  13625. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13626. _this.setDepthTest( material.depthTest );
  13627. _this.setDepthWrite( material.depthWrite );
  13628. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13629. }
  13630. _this.renderImmediateObject( camera, lights, fog, material, object );
  13631. }
  13632. }
  13633. };
  13634. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13635. var program = setProgram( camera, lights, fog, material, object );
  13636. _currentGeometryGroupHash = -1;
  13637. _this.setMaterialFaces( material );
  13638. if ( object.immediateRenderCallback ) {
  13639. object.immediateRenderCallback( program, _gl, _frustum );
  13640. } else {
  13641. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13642. }
  13643. };
  13644. function unrollImmediateBufferMaterial ( globject ) {
  13645. var object = globject.object,
  13646. material = object.material;
  13647. if ( material.transparent ) {
  13648. globject.transparent = material;
  13649. globject.opaque = null;
  13650. } else {
  13651. globject.opaque = material;
  13652. globject.transparent = null;
  13653. }
  13654. };
  13655. function unrollBufferMaterial ( globject ) {
  13656. var object = globject.object,
  13657. buffer = globject.buffer,
  13658. material, materialIndex, meshMaterial;
  13659. meshMaterial = object.material;
  13660. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  13661. materialIndex = buffer.materialIndex;
  13662. material = meshMaterial.materials[ materialIndex ];
  13663. if ( material.transparent ) {
  13664. globject.transparent = material;
  13665. globject.opaque = null;
  13666. } else {
  13667. globject.opaque = material;
  13668. globject.transparent = null;
  13669. }
  13670. } else {
  13671. material = meshMaterial;
  13672. if ( material ) {
  13673. if ( material.transparent ) {
  13674. globject.transparent = material;
  13675. globject.opaque = null;
  13676. } else {
  13677. globject.opaque = material;
  13678. globject.transparent = null;
  13679. }
  13680. }
  13681. }
  13682. };
  13683. // Geometry splitting
  13684. function sortFacesByMaterial ( geometry, material ) {
  13685. var f, fl, face, materialIndex, vertices,
  13686. groupHash, hash_map = {};
  13687. var numMorphTargets = geometry.morphTargets.length;
  13688. var numMorphNormals = geometry.morphNormals.length;
  13689. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  13690. geometry.geometryGroups = {};
  13691. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  13692. face = geometry.faces[ f ];
  13693. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  13694. if ( hash_map[ materialIndex ] === undefined ) {
  13695. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  13696. }
  13697. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13698. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13699. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13700. }
  13701. vertices = 3;
  13702. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  13703. hash_map[ materialIndex ].counter += 1;
  13704. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13705. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13706. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13707. }
  13708. }
  13709. geometry.geometryGroups[ groupHash ].faces3.push( f );
  13710. geometry.geometryGroups[ groupHash ].vertices += vertices;
  13711. }
  13712. geometry.geometryGroupsList = [];
  13713. for ( var g in geometry.geometryGroups ) {
  13714. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  13715. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  13716. }
  13717. };
  13718. // Objects refresh
  13719. this.initWebGLObjects = function ( scene ) {
  13720. if ( !scene.__webglObjects ) {
  13721. scene.__webglObjects = [];
  13722. scene.__webglObjectsImmediate = [];
  13723. scene.__webglSprites = [];
  13724. scene.__webglFlares = [];
  13725. }
  13726. while ( scene.__objectsAdded.length ) {
  13727. addObject( scene.__objectsAdded[ 0 ], scene );
  13728. scene.__objectsAdded.splice( 0, 1 );
  13729. }
  13730. while ( scene.__objectsRemoved.length ) {
  13731. removeObject( scene.__objectsRemoved[ 0 ], scene );
  13732. scene.__objectsRemoved.splice( 0, 1 );
  13733. }
  13734. // update must be called after objects adding / removal
  13735. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  13736. var object = scene.__webglObjects[ o ].object;
  13737. // TODO: Remove this hack (WebGLRenderer refactoring)
  13738. if ( object.__webglInit === undefined ) {
  13739. if ( object.__webglActive !== undefined ) {
  13740. removeObject( object, scene );
  13741. }
  13742. addObject( object, scene );
  13743. }
  13744. updateObject( object );
  13745. }
  13746. };
  13747. // Objects adding
  13748. function addObject( object, scene ) {
  13749. var g, geometry, material, geometryGroup;
  13750. if ( object.__webglInit === undefined ) {
  13751. object.__webglInit = true;
  13752. object._modelViewMatrix = new THREE.Matrix4();
  13753. object._normalMatrix = new THREE.Matrix3();
  13754. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  13755. object.geometry.__webglInit = true;
  13756. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  13757. }
  13758. geometry = object.geometry;
  13759. if ( geometry === undefined ) {
  13760. // fail silently for now
  13761. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13762. initDirectBuffers( geometry );
  13763. } else if ( object instanceof THREE.Mesh ) {
  13764. material = object.material;
  13765. if ( geometry.geometryGroups === undefined ) {
  13766. sortFacesByMaterial( geometry, material );
  13767. }
  13768. // create separate VBOs per geometry chunk
  13769. for ( g in geometry.geometryGroups ) {
  13770. geometryGroup = geometry.geometryGroups[ g ];
  13771. // initialise VBO on the first access
  13772. if ( ! geometryGroup.__webglVertexBuffer ) {
  13773. createMeshBuffers( geometryGroup );
  13774. initMeshBuffers( geometryGroup, object );
  13775. geometry.verticesNeedUpdate = true;
  13776. geometry.morphTargetsNeedUpdate = true;
  13777. geometry.elementsNeedUpdate = true;
  13778. geometry.uvsNeedUpdate = true;
  13779. geometry.normalsNeedUpdate = true;
  13780. geometry.tangentsNeedUpdate = true;
  13781. geometry.colorsNeedUpdate = true;
  13782. }
  13783. }
  13784. } else if ( object instanceof THREE.Line ) {
  13785. if ( ! geometry.__webglVertexBuffer ) {
  13786. createLineBuffers( geometry );
  13787. initLineBuffers( geometry, object );
  13788. geometry.verticesNeedUpdate = true;
  13789. geometry.colorsNeedUpdate = true;
  13790. geometry.lineDistancesNeedUpdate = true;
  13791. }
  13792. } else if ( object instanceof THREE.ParticleSystem ) {
  13793. if ( ! geometry.__webglVertexBuffer ) {
  13794. createParticleBuffers( geometry );
  13795. initParticleBuffers( geometry, object );
  13796. geometry.verticesNeedUpdate = true;
  13797. geometry.colorsNeedUpdate = true;
  13798. }
  13799. }
  13800. }
  13801. if ( object.__webglActive === undefined ) {
  13802. if ( object instanceof THREE.Mesh ) {
  13803. geometry = object.geometry;
  13804. if ( geometry instanceof THREE.BufferGeometry ) {
  13805. addBuffer( scene.__webglObjects, geometry, object );
  13806. } else if ( geometry instanceof THREE.Geometry ) {
  13807. for ( g in geometry.geometryGroups ) {
  13808. geometryGroup = geometry.geometryGroups[ g ];
  13809. addBuffer( scene.__webglObjects, geometryGroup, object );
  13810. }
  13811. }
  13812. } else if ( object instanceof THREE.Line ||
  13813. object instanceof THREE.ParticleSystem ) {
  13814. geometry = object.geometry;
  13815. addBuffer( scene.__webglObjects, geometry, object );
  13816. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13817. addBufferImmediate( scene.__webglObjectsImmediate, object );
  13818. } else if ( object instanceof THREE.Sprite ) {
  13819. scene.__webglSprites.push( object );
  13820. } else if ( object instanceof THREE.LensFlare ) {
  13821. scene.__webglFlares.push( object );
  13822. }
  13823. object.__webglActive = true;
  13824. }
  13825. };
  13826. function addBuffer( objlist, buffer, object ) {
  13827. objlist.push(
  13828. {
  13829. id: null,
  13830. buffer: buffer,
  13831. object: object,
  13832. opaque: null,
  13833. transparent: null,
  13834. z: 0
  13835. }
  13836. );
  13837. };
  13838. function addBufferImmediate( objlist, object ) {
  13839. objlist.push(
  13840. {
  13841. id: null,
  13842. object: object,
  13843. opaque: null,
  13844. transparent: null,
  13845. z: 0
  13846. }
  13847. );
  13848. };
  13849. // Objects updates
  13850. function updateObject( object ) {
  13851. var geometry = object.geometry,
  13852. geometryGroup, customAttributesDirty, material;
  13853. if ( geometry instanceof THREE.BufferGeometry ) {
  13854. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13855. } else if ( object instanceof THREE.Mesh ) {
  13856. // check all geometry groups
  13857. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  13858. geometryGroup = geometry.geometryGroupsList[ i ];
  13859. material = getBufferMaterial( object, geometryGroup );
  13860. if ( geometry.buffersNeedUpdate ) {
  13861. initMeshBuffers( geometryGroup, object );
  13862. }
  13863. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13864. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  13865. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13866. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  13867. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  13868. }
  13869. }
  13870. geometry.verticesNeedUpdate = false;
  13871. geometry.morphTargetsNeedUpdate = false;
  13872. geometry.elementsNeedUpdate = false;
  13873. geometry.uvsNeedUpdate = false;
  13874. geometry.normalsNeedUpdate = false;
  13875. geometry.colorsNeedUpdate = false;
  13876. geometry.tangentsNeedUpdate = false;
  13877. geometry.buffersNeedUpdate = false;
  13878. material.attributes && clearCustomAttributes( material );
  13879. } else if ( object instanceof THREE.Line ) {
  13880. material = getBufferMaterial( object, geometry );
  13881. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13882. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  13883. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  13884. }
  13885. geometry.verticesNeedUpdate = false;
  13886. geometry.colorsNeedUpdate = false;
  13887. geometry.lineDistancesNeedUpdate = false;
  13888. material.attributes && clearCustomAttributes( material );
  13889. } else if ( object instanceof THREE.ParticleSystem ) {
  13890. material = getBufferMaterial( object, geometry );
  13891. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13892. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  13893. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  13894. }
  13895. geometry.verticesNeedUpdate = false;
  13896. geometry.colorsNeedUpdate = false;
  13897. material.attributes && clearCustomAttributes( material );
  13898. }
  13899. };
  13900. // Objects updates - custom attributes check
  13901. function areCustomAttributesDirty( material ) {
  13902. for ( var a in material.attributes ) {
  13903. if ( material.attributes[ a ].needsUpdate ) return true;
  13904. }
  13905. return false;
  13906. };
  13907. function clearCustomAttributes( material ) {
  13908. for ( var a in material.attributes ) {
  13909. material.attributes[ a ].needsUpdate = false;
  13910. }
  13911. };
  13912. // Objects removal
  13913. function removeObject( object, scene ) {
  13914. if ( object instanceof THREE.Mesh ||
  13915. object instanceof THREE.ParticleSystem ||
  13916. object instanceof THREE.Line ) {
  13917. removeInstances( scene.__webglObjects, object );
  13918. } else if ( object instanceof THREE.Sprite ) {
  13919. removeInstancesDirect( scene.__webglSprites, object );
  13920. } else if ( object instanceof THREE.LensFlare ) {
  13921. removeInstancesDirect( scene.__webglFlares, object );
  13922. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13923. removeInstances( scene.__webglObjectsImmediate, object );
  13924. }
  13925. delete object.__webglActive;
  13926. };
  13927. function removeInstances( objlist, object ) {
  13928. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13929. if ( objlist[ o ].object === object ) {
  13930. objlist.splice( o, 1 );
  13931. }
  13932. }
  13933. };
  13934. function removeInstancesDirect( objlist, object ) {
  13935. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13936. if ( objlist[ o ] === object ) {
  13937. objlist.splice( o, 1 );
  13938. }
  13939. }
  13940. };
  13941. // Materials
  13942. this.initMaterial = function ( material, lights, fog, object ) {
  13943. material.addEventListener( 'dispose', onMaterialDispose );
  13944. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  13945. if ( material instanceof THREE.MeshDepthMaterial ) {
  13946. shaderID = 'depth';
  13947. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13948. shaderID = 'normal';
  13949. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  13950. shaderID = 'basic';
  13951. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13952. shaderID = 'lambert';
  13953. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13954. shaderID = 'phong';
  13955. } else if ( material instanceof THREE.LineBasicMaterial ) {
  13956. shaderID = 'basic';
  13957. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13958. shaderID = 'dashed';
  13959. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  13960. shaderID = 'particle_basic';
  13961. }
  13962. if ( shaderID ) {
  13963. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  13964. }
  13965. // heuristics to create shader parameters according to lights in the scene
  13966. // (not to blow over maxLights budget)
  13967. maxLightCount = allocateLights( lights );
  13968. maxShadows = allocateShadows( lights );
  13969. maxBones = allocateBones( object );
  13970. parameters = {
  13971. map: !!material.map,
  13972. envMap: !!material.envMap,
  13973. lightMap: !!material.lightMap,
  13974. bumpMap: !!material.bumpMap,
  13975. normalMap: !!material.normalMap,
  13976. specularMap: !!material.specularMap,
  13977. vertexColors: material.vertexColors,
  13978. fog: fog,
  13979. useFog: material.fog,
  13980. fogExp: fog instanceof THREE.FogExp2,
  13981. sizeAttenuation: material.sizeAttenuation,
  13982. skinning: material.skinning,
  13983. maxBones: maxBones,
  13984. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  13985. morphTargets: material.morphTargets,
  13986. morphNormals: material.morphNormals,
  13987. maxMorphTargets: this.maxMorphTargets,
  13988. maxMorphNormals: this.maxMorphNormals,
  13989. maxDirLights: maxLightCount.directional,
  13990. maxPointLights: maxLightCount.point,
  13991. maxSpotLights: maxLightCount.spot,
  13992. maxHemiLights: maxLightCount.hemi,
  13993. maxShadows: maxShadows,
  13994. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  13995. shadowMapType: this.shadowMapType,
  13996. shadowMapDebug: this.shadowMapDebug,
  13997. shadowMapCascade: this.shadowMapCascade,
  13998. alphaTest: material.alphaTest,
  13999. metal: material.metal,
  14000. perPixel: material.perPixel,
  14001. wrapAround: material.wrapAround,
  14002. doubleSided: material.side === THREE.DoubleSide,
  14003. flipSided: material.side === THREE.BackSide
  14004. };
  14005. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters, material.index0AttributeName );
  14006. var attributes = material.program.attributes;
  14007. if ( material.morphTargets ) {
  14008. material.numSupportedMorphTargets = 0;
  14009. var id, base = "morphTarget";
  14010. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  14011. id = base + i;
  14012. if ( attributes[ id ] >= 0 ) {
  14013. material.numSupportedMorphTargets ++;
  14014. }
  14015. }
  14016. }
  14017. if ( material.morphNormals ) {
  14018. material.numSupportedMorphNormals = 0;
  14019. var id, base = "morphNormal";
  14020. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  14021. id = base + i;
  14022. if ( attributes[ id ] >= 0 ) {
  14023. material.numSupportedMorphNormals ++;
  14024. }
  14025. }
  14026. }
  14027. material.uniformsList = [];
  14028. for ( u in material.uniforms ) {
  14029. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14030. }
  14031. };
  14032. function setMaterialShaders( material, shaders ) {
  14033. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14034. material.vertexShader = shaders.vertexShader;
  14035. material.fragmentShader = shaders.fragmentShader;
  14036. };
  14037. function setProgram( camera, lights, fog, material, object ) {
  14038. _usedTextureUnits = 0;
  14039. if ( material.needsUpdate ) {
  14040. if ( material.program ) deallocateMaterial( material );
  14041. _this.initMaterial( material, lights, fog, object );
  14042. material.needsUpdate = false;
  14043. }
  14044. if ( material.morphTargets ) {
  14045. if ( ! object.__webglMorphTargetInfluences ) {
  14046. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14047. }
  14048. }
  14049. var refreshMaterial = false;
  14050. var program = material.program,
  14051. p_uniforms = program.uniforms,
  14052. m_uniforms = material.uniforms;
  14053. if ( program !== _currentProgram ) {
  14054. _gl.useProgram( program );
  14055. _currentProgram = program;
  14056. refreshMaterial = true;
  14057. }
  14058. if ( material.id !== _currentMaterialId ) {
  14059. _currentMaterialId = material.id;
  14060. refreshMaterial = true;
  14061. }
  14062. if ( refreshMaterial || camera !== _currentCamera ) {
  14063. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14064. if ( camera !== _currentCamera ) _currentCamera = camera;
  14065. }
  14066. // skinning uniforms must be set even if material didn't change
  14067. // auto-setting of texture unit for bone texture must go before other textures
  14068. // not sure why, but otherwise weird things happen
  14069. if ( material.skinning ) {
  14070. if ( _supportsBoneTextures && object.useVertexTexture ) {
  14071. if ( p_uniforms.boneTexture !== null ) {
  14072. var textureUnit = getTextureUnit();
  14073. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14074. _this.setTexture( object.boneTexture, textureUnit );
  14075. }
  14076. if ( p_uniforms.boneTextureWidth !== null ) {
  14077. _gl.uniform1i( p_uniforms.boneTextureWidth, object.boneTextureWidth );
  14078. }
  14079. if ( p_uniforms.boneTextureHeight !== null ) {
  14080. _gl.uniform1i( p_uniforms.boneTextureHeight, object.boneTextureHeight );
  14081. }
  14082. } else {
  14083. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14084. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  14085. }
  14086. }
  14087. }
  14088. if ( refreshMaterial ) {
  14089. // refresh uniforms common to several materials
  14090. if ( fog && material.fog ) {
  14091. refreshUniformsFog( m_uniforms, fog );
  14092. }
  14093. if ( material instanceof THREE.MeshPhongMaterial ||
  14094. material instanceof THREE.MeshLambertMaterial ||
  14095. material.lights ) {
  14096. if ( _lightsNeedUpdate ) {
  14097. setupLights( program, lights );
  14098. _lightsNeedUpdate = false;
  14099. }
  14100. refreshUniformsLights( m_uniforms, _lights );
  14101. }
  14102. if ( material instanceof THREE.MeshBasicMaterial ||
  14103. material instanceof THREE.MeshLambertMaterial ||
  14104. material instanceof THREE.MeshPhongMaterial ) {
  14105. refreshUniformsCommon( m_uniforms, material );
  14106. }
  14107. // refresh single material specific uniforms
  14108. if ( material instanceof THREE.LineBasicMaterial ) {
  14109. refreshUniformsLine( m_uniforms, material );
  14110. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14111. refreshUniformsLine( m_uniforms, material );
  14112. refreshUniformsDash( m_uniforms, material );
  14113. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  14114. refreshUniformsParticle( m_uniforms, material );
  14115. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14116. refreshUniformsPhong( m_uniforms, material );
  14117. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14118. refreshUniformsLambert( m_uniforms, material );
  14119. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14120. m_uniforms.mNear.value = camera.near;
  14121. m_uniforms.mFar.value = camera.far;
  14122. m_uniforms.opacity.value = material.opacity;
  14123. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14124. m_uniforms.opacity.value = material.opacity;
  14125. }
  14126. if ( object.receiveShadow && ! material._shadowPass ) {
  14127. refreshUniformsShadow( m_uniforms, lights );
  14128. }
  14129. // load common uniforms
  14130. loadUniformsGeneric( program, material.uniformsList );
  14131. // load material specific uniforms
  14132. // (shader material also gets them for the sake of genericity)
  14133. if ( material instanceof THREE.ShaderMaterial ||
  14134. material instanceof THREE.MeshPhongMaterial ||
  14135. material.envMap ) {
  14136. if ( p_uniforms.cameraPosition !== null ) {
  14137. _vector3.setFromMatrixPosition( camera.matrixWorld );
  14138. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14139. }
  14140. }
  14141. if ( material instanceof THREE.MeshPhongMaterial ||
  14142. material instanceof THREE.MeshLambertMaterial ||
  14143. material instanceof THREE.ShaderMaterial ||
  14144. material.skinning ) {
  14145. if ( p_uniforms.viewMatrix !== null ) {
  14146. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14147. }
  14148. }
  14149. }
  14150. loadUniformsMatrices( p_uniforms, object );
  14151. if ( p_uniforms.modelMatrix !== null ) {
  14152. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14153. }
  14154. return program;
  14155. };
  14156. // Uniforms (refresh uniforms objects)
  14157. function refreshUniformsCommon ( uniforms, material ) {
  14158. uniforms.opacity.value = material.opacity;
  14159. if ( _this.gammaInput ) {
  14160. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14161. } else {
  14162. uniforms.diffuse.value = material.color;
  14163. }
  14164. uniforms.map.value = material.map;
  14165. uniforms.lightMap.value = material.lightMap;
  14166. uniforms.specularMap.value = material.specularMap;
  14167. if ( material.bumpMap ) {
  14168. uniforms.bumpMap.value = material.bumpMap;
  14169. uniforms.bumpScale.value = material.bumpScale;
  14170. }
  14171. if ( material.normalMap ) {
  14172. uniforms.normalMap.value = material.normalMap;
  14173. uniforms.normalScale.value.copy( material.normalScale );
  14174. }
  14175. // uv repeat and offset setting priorities
  14176. // 1. color map
  14177. // 2. specular map
  14178. // 3. normal map
  14179. // 4. bump map
  14180. var uvScaleMap;
  14181. if ( material.map ) {
  14182. uvScaleMap = material.map;
  14183. } else if ( material.specularMap ) {
  14184. uvScaleMap = material.specularMap;
  14185. } else if ( material.normalMap ) {
  14186. uvScaleMap = material.normalMap;
  14187. } else if ( material.bumpMap ) {
  14188. uvScaleMap = material.bumpMap;
  14189. }
  14190. if ( uvScaleMap !== undefined ) {
  14191. var offset = uvScaleMap.offset;
  14192. var repeat = uvScaleMap.repeat;
  14193. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14194. }
  14195. uniforms.envMap.value = material.envMap;
  14196. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14197. if ( _this.gammaInput ) {
  14198. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14199. uniforms.reflectivity.value = material.reflectivity;
  14200. } else {
  14201. uniforms.reflectivity.value = material.reflectivity;
  14202. }
  14203. uniforms.refractionRatio.value = material.refractionRatio;
  14204. uniforms.combine.value = material.combine;
  14205. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14206. };
  14207. function refreshUniformsLine ( uniforms, material ) {
  14208. uniforms.diffuse.value = material.color;
  14209. uniforms.opacity.value = material.opacity;
  14210. };
  14211. function refreshUniformsDash ( uniforms, material ) {
  14212. uniforms.dashSize.value = material.dashSize;
  14213. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14214. uniforms.scale.value = material.scale;
  14215. };
  14216. function refreshUniformsParticle ( uniforms, material ) {
  14217. uniforms.psColor.value = material.color;
  14218. uniforms.opacity.value = material.opacity;
  14219. uniforms.size.value = material.size;
  14220. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14221. uniforms.map.value = material.map;
  14222. };
  14223. function refreshUniformsFog ( uniforms, fog ) {
  14224. uniforms.fogColor.value = fog.color;
  14225. if ( fog instanceof THREE.Fog ) {
  14226. uniforms.fogNear.value = fog.near;
  14227. uniforms.fogFar.value = fog.far;
  14228. } else if ( fog instanceof THREE.FogExp2 ) {
  14229. uniforms.fogDensity.value = fog.density;
  14230. }
  14231. };
  14232. function refreshUniformsPhong ( uniforms, material ) {
  14233. uniforms.shininess.value = material.shininess;
  14234. if ( _this.gammaInput ) {
  14235. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14236. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14237. uniforms.specular.value.copyGammaToLinear( material.specular );
  14238. } else {
  14239. uniforms.ambient.value = material.ambient;
  14240. uniforms.emissive.value = material.emissive;
  14241. uniforms.specular.value = material.specular;
  14242. }
  14243. if ( material.wrapAround ) {
  14244. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14245. }
  14246. };
  14247. function refreshUniformsLambert ( uniforms, material ) {
  14248. if ( _this.gammaInput ) {
  14249. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14250. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14251. } else {
  14252. uniforms.ambient.value = material.ambient;
  14253. uniforms.emissive.value = material.emissive;
  14254. }
  14255. if ( material.wrapAround ) {
  14256. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14257. }
  14258. };
  14259. function refreshUniformsLights ( uniforms, lights ) {
  14260. uniforms.ambientLightColor.value = lights.ambient;
  14261. uniforms.directionalLightColor.value = lights.directional.colors;
  14262. uniforms.directionalLightDirection.value = lights.directional.positions;
  14263. uniforms.pointLightColor.value = lights.point.colors;
  14264. uniforms.pointLightPosition.value = lights.point.positions;
  14265. uniforms.pointLightDistance.value = lights.point.distances;
  14266. uniforms.spotLightColor.value = lights.spot.colors;
  14267. uniforms.spotLightPosition.value = lights.spot.positions;
  14268. uniforms.spotLightDistance.value = lights.spot.distances;
  14269. uniforms.spotLightDirection.value = lights.spot.directions;
  14270. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14271. uniforms.spotLightExponent.value = lights.spot.exponents;
  14272. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14273. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14274. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14275. };
  14276. function refreshUniformsShadow ( uniforms, lights ) {
  14277. if ( uniforms.shadowMatrix ) {
  14278. var j = 0;
  14279. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14280. var light = lights[ i ];
  14281. if ( ! light.castShadow ) continue;
  14282. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14283. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14284. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14285. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14286. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14287. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14288. j ++;
  14289. }
  14290. }
  14291. }
  14292. };
  14293. // Uniforms (load to GPU)
  14294. function loadUniformsMatrices ( uniforms, object ) {
  14295. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14296. if ( uniforms.normalMatrix ) {
  14297. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14298. }
  14299. };
  14300. function getTextureUnit() {
  14301. var textureUnit = _usedTextureUnits;
  14302. if ( textureUnit >= _maxTextures ) {
  14303. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14304. }
  14305. _usedTextureUnits += 1;
  14306. return textureUnit;
  14307. };
  14308. function loadUniformsGeneric ( program, uniforms ) {
  14309. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14310. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14311. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14312. if ( !location ) continue;
  14313. uniform = uniforms[ j ][ 0 ];
  14314. type = uniform.type;
  14315. value = uniform.value;
  14316. if ( type === "i" ) { // single integer
  14317. _gl.uniform1i( location, value );
  14318. } else if ( type === "f" ) { // single float
  14319. _gl.uniform1f( location, value );
  14320. } else if ( type === "v2" ) { // single THREE.Vector2
  14321. _gl.uniform2f( location, value.x, value.y );
  14322. } else if ( type === "v3" ) { // single THREE.Vector3
  14323. _gl.uniform3f( location, value.x, value.y, value.z );
  14324. } else if ( type === "v4" ) { // single THREE.Vector4
  14325. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14326. } else if ( type === "c" ) { // single THREE.Color
  14327. _gl.uniform3f( location, value.r, value.g, value.b );
  14328. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14329. _gl.uniform1iv( location, value );
  14330. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14331. _gl.uniform3iv( location, value );
  14332. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14333. _gl.uniform1fv( location, value );
  14334. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14335. _gl.uniform3fv( location, value );
  14336. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14337. if ( uniform._array === undefined ) {
  14338. uniform._array = new Float32Array( 2 * value.length );
  14339. }
  14340. for ( i = 0, il = value.length; i < il; i ++ ) {
  14341. offset = i * 2;
  14342. uniform._array[ offset ] = value[ i ].x;
  14343. uniform._array[ offset + 1 ] = value[ i ].y;
  14344. }
  14345. _gl.uniform2fv( location, uniform._array );
  14346. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14347. if ( uniform._array === undefined ) {
  14348. uniform._array = new Float32Array( 3 * value.length );
  14349. }
  14350. for ( i = 0, il = value.length; i < il; i ++ ) {
  14351. offset = i * 3;
  14352. uniform._array[ offset ] = value[ i ].x;
  14353. uniform._array[ offset + 1 ] = value[ i ].y;
  14354. uniform._array[ offset + 2 ] = value[ i ].z;
  14355. }
  14356. _gl.uniform3fv( location, uniform._array );
  14357. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14358. if ( uniform._array === undefined ) {
  14359. uniform._array = new Float32Array( 4 * value.length );
  14360. }
  14361. for ( i = 0, il = value.length; i < il; i ++ ) {
  14362. offset = i * 4;
  14363. uniform._array[ offset ] = value[ i ].x;
  14364. uniform._array[ offset + 1 ] = value[ i ].y;
  14365. uniform._array[ offset + 2 ] = value[ i ].z;
  14366. uniform._array[ offset + 3 ] = value[ i ].w;
  14367. }
  14368. _gl.uniform4fv( location, uniform._array );
  14369. } else if ( type === "m4") { // single THREE.Matrix4
  14370. if ( uniform._array === undefined ) {
  14371. uniform._array = new Float32Array( 16 );
  14372. }
  14373. value.flattenToArray( uniform._array );
  14374. _gl.uniformMatrix4fv( location, false, uniform._array );
  14375. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14376. if ( uniform._array === undefined ) {
  14377. uniform._array = new Float32Array( 16 * value.length );
  14378. }
  14379. for ( i = 0, il = value.length; i < il; i ++ ) {
  14380. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14381. }
  14382. _gl.uniformMatrix4fv( location, false, uniform._array );
  14383. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14384. texture = value;
  14385. textureUnit = getTextureUnit();
  14386. _gl.uniform1i( location, textureUnit );
  14387. if ( !texture ) continue;
  14388. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14389. setCubeTexture( texture, textureUnit );
  14390. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14391. setCubeTextureDynamic( texture, textureUnit );
  14392. } else {
  14393. _this.setTexture( texture, textureUnit );
  14394. }
  14395. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14396. if ( uniform._array === undefined ) {
  14397. uniform._array = [];
  14398. }
  14399. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14400. uniform._array[ i ] = getTextureUnit();
  14401. }
  14402. _gl.uniform1iv( location, uniform._array );
  14403. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14404. texture = uniform.value[ i ];
  14405. textureUnit = uniform._array[ i ];
  14406. if ( !texture ) continue;
  14407. _this.setTexture( texture, textureUnit );
  14408. }
  14409. } else {
  14410. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  14411. }
  14412. }
  14413. };
  14414. function setupMatrices ( object, camera ) {
  14415. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14416. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14417. };
  14418. //
  14419. function setColorGamma( array, offset, color, intensitySq ) {
  14420. array[ offset ] = color.r * color.r * intensitySq;
  14421. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14422. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14423. };
  14424. function setColorLinear( array, offset, color, intensity ) {
  14425. array[ offset ] = color.r * intensity;
  14426. array[ offset + 1 ] = color.g * intensity;
  14427. array[ offset + 2 ] = color.b * intensity;
  14428. };
  14429. function setupLights ( program, lights ) {
  14430. var l, ll, light, n,
  14431. r = 0, g = 0, b = 0,
  14432. color, skyColor, groundColor,
  14433. intensity, intensitySq,
  14434. position,
  14435. distance,
  14436. zlights = _lights,
  14437. dirColors = zlights.directional.colors,
  14438. dirPositions = zlights.directional.positions,
  14439. pointColors = zlights.point.colors,
  14440. pointPositions = zlights.point.positions,
  14441. pointDistances = zlights.point.distances,
  14442. spotColors = zlights.spot.colors,
  14443. spotPositions = zlights.spot.positions,
  14444. spotDistances = zlights.spot.distances,
  14445. spotDirections = zlights.spot.directions,
  14446. spotAnglesCos = zlights.spot.anglesCos,
  14447. spotExponents = zlights.spot.exponents,
  14448. hemiSkyColors = zlights.hemi.skyColors,
  14449. hemiGroundColors = zlights.hemi.groundColors,
  14450. hemiPositions = zlights.hemi.positions,
  14451. dirLength = 0,
  14452. pointLength = 0,
  14453. spotLength = 0,
  14454. hemiLength = 0,
  14455. dirCount = 0,
  14456. pointCount = 0,
  14457. spotCount = 0,
  14458. hemiCount = 0,
  14459. dirOffset = 0,
  14460. pointOffset = 0,
  14461. spotOffset = 0,
  14462. hemiOffset = 0;
  14463. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14464. light = lights[ l ];
  14465. if ( light.onlyShadow ) continue;
  14466. color = light.color;
  14467. intensity = light.intensity;
  14468. distance = light.distance;
  14469. if ( light instanceof THREE.AmbientLight ) {
  14470. if ( ! light.visible ) continue;
  14471. if ( _this.gammaInput ) {
  14472. r += color.r * color.r;
  14473. g += color.g * color.g;
  14474. b += color.b * color.b;
  14475. } else {
  14476. r += color.r;
  14477. g += color.g;
  14478. b += color.b;
  14479. }
  14480. } else if ( light instanceof THREE.DirectionalLight ) {
  14481. dirCount += 1;
  14482. if ( ! light.visible ) continue;
  14483. _direction.setFromMatrixPosition( light.matrixWorld );
  14484. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14485. _direction.sub( _vector3 );
  14486. _direction.normalize();
  14487. // skip lights with undefined direction
  14488. // these create troubles in OpenGL (making pixel black)
  14489. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14490. dirOffset = dirLength * 3;
  14491. dirPositions[ dirOffset ] = _direction.x;
  14492. dirPositions[ dirOffset + 1 ] = _direction.y;
  14493. dirPositions[ dirOffset + 2 ] = _direction.z;
  14494. if ( _this.gammaInput ) {
  14495. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14496. } else {
  14497. setColorLinear( dirColors, dirOffset, color, intensity );
  14498. }
  14499. dirLength += 1;
  14500. } else if ( light instanceof THREE.PointLight ) {
  14501. pointCount += 1;
  14502. if ( ! light.visible ) continue;
  14503. pointOffset = pointLength * 3;
  14504. if ( _this.gammaInput ) {
  14505. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14506. } else {
  14507. setColorLinear( pointColors, pointOffset, color, intensity );
  14508. }
  14509. _vector3.setFromMatrixPosition( light.matrixWorld );
  14510. pointPositions[ pointOffset ] = _vector3.x;
  14511. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14512. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14513. pointDistances[ pointLength ] = distance;
  14514. pointLength += 1;
  14515. } else if ( light instanceof THREE.SpotLight ) {
  14516. spotCount += 1;
  14517. if ( ! light.visible ) continue;
  14518. spotOffset = spotLength * 3;
  14519. if ( _this.gammaInput ) {
  14520. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14521. } else {
  14522. setColorLinear( spotColors, spotOffset, color, intensity );
  14523. }
  14524. _vector3.setFromMatrixPosition( light.matrixWorld );
  14525. spotPositions[ spotOffset ] = _vector3.x;
  14526. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14527. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14528. spotDistances[ spotLength ] = distance;
  14529. _direction.copy( _vector3 );
  14530. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14531. _direction.sub( _vector3 );
  14532. _direction.normalize();
  14533. spotDirections[ spotOffset ] = _direction.x;
  14534. spotDirections[ spotOffset + 1 ] = _direction.y;
  14535. spotDirections[ spotOffset + 2 ] = _direction.z;
  14536. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14537. spotExponents[ spotLength ] = light.exponent;
  14538. spotLength += 1;
  14539. } else if ( light instanceof THREE.HemisphereLight ) {
  14540. hemiCount += 1;
  14541. if ( ! light.visible ) continue;
  14542. _direction.setFromMatrixPosition( light.matrixWorld );
  14543. _direction.normalize();
  14544. // skip lights with undefined direction
  14545. // these create troubles in OpenGL (making pixel black)
  14546. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14547. hemiOffset = hemiLength * 3;
  14548. hemiPositions[ hemiOffset ] = _direction.x;
  14549. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14550. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14551. skyColor = light.color;
  14552. groundColor = light.groundColor;
  14553. if ( _this.gammaInput ) {
  14554. intensitySq = intensity * intensity;
  14555. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14556. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14557. } else {
  14558. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14559. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14560. }
  14561. hemiLength += 1;
  14562. }
  14563. }
  14564. // null eventual remains from removed lights
  14565. // (this is to avoid if in shader)
  14566. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14567. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14568. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14569. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14570. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14571. zlights.directional.length = dirLength;
  14572. zlights.point.length = pointLength;
  14573. zlights.spot.length = spotLength;
  14574. zlights.hemi.length = hemiLength;
  14575. zlights.ambient[ 0 ] = r;
  14576. zlights.ambient[ 1 ] = g;
  14577. zlights.ambient[ 2 ] = b;
  14578. };
  14579. // GL state setting
  14580. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14581. if ( cullFace === THREE.CullFaceNone ) {
  14582. _gl.disable( _gl.CULL_FACE );
  14583. } else {
  14584. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14585. _gl.frontFace( _gl.CW );
  14586. } else {
  14587. _gl.frontFace( _gl.CCW );
  14588. }
  14589. if ( cullFace === THREE.CullFaceBack ) {
  14590. _gl.cullFace( _gl.BACK );
  14591. } else if ( cullFace === THREE.CullFaceFront ) {
  14592. _gl.cullFace( _gl.FRONT );
  14593. } else {
  14594. _gl.cullFace( _gl.FRONT_AND_BACK );
  14595. }
  14596. _gl.enable( _gl.CULL_FACE );
  14597. }
  14598. };
  14599. this.setMaterialFaces = function ( material ) {
  14600. var doubleSided = material.side === THREE.DoubleSide;
  14601. var flipSided = material.side === THREE.BackSide;
  14602. if ( _oldDoubleSided !== doubleSided ) {
  14603. if ( doubleSided ) {
  14604. _gl.disable( _gl.CULL_FACE );
  14605. } else {
  14606. _gl.enable( _gl.CULL_FACE );
  14607. }
  14608. _oldDoubleSided = doubleSided;
  14609. }
  14610. if ( _oldFlipSided !== flipSided ) {
  14611. if ( flipSided ) {
  14612. _gl.frontFace( _gl.CW );
  14613. } else {
  14614. _gl.frontFace( _gl.CCW );
  14615. }
  14616. _oldFlipSided = flipSided;
  14617. }
  14618. };
  14619. this.setDepthTest = function ( depthTest ) {
  14620. if ( _oldDepthTest !== depthTest ) {
  14621. if ( depthTest ) {
  14622. _gl.enable( _gl.DEPTH_TEST );
  14623. } else {
  14624. _gl.disable( _gl.DEPTH_TEST );
  14625. }
  14626. _oldDepthTest = depthTest;
  14627. }
  14628. };
  14629. this.setDepthWrite = function ( depthWrite ) {
  14630. if ( _oldDepthWrite !== depthWrite ) {
  14631. _gl.depthMask( depthWrite );
  14632. _oldDepthWrite = depthWrite;
  14633. }
  14634. };
  14635. function setLineWidth ( width ) {
  14636. if ( width !== _oldLineWidth ) {
  14637. _gl.lineWidth( width );
  14638. _oldLineWidth = width;
  14639. }
  14640. };
  14641. function setPolygonOffset ( polygonoffset, factor, units ) {
  14642. if ( _oldPolygonOffset !== polygonoffset ) {
  14643. if ( polygonoffset ) {
  14644. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  14645. } else {
  14646. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  14647. }
  14648. _oldPolygonOffset = polygonoffset;
  14649. }
  14650. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  14651. _gl.polygonOffset( factor, units );
  14652. _oldPolygonOffsetFactor = factor;
  14653. _oldPolygonOffsetUnits = units;
  14654. }
  14655. };
  14656. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  14657. if ( blending !== _oldBlending ) {
  14658. if ( blending === THREE.NoBlending ) {
  14659. _gl.disable( _gl.BLEND );
  14660. } else if ( blending === THREE.AdditiveBlending ) {
  14661. _gl.enable( _gl.BLEND );
  14662. _gl.blendEquation( _gl.FUNC_ADD );
  14663. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  14664. } else if ( blending === THREE.SubtractiveBlending ) {
  14665. // TODO: Find blendFuncSeparate() combination
  14666. _gl.enable( _gl.BLEND );
  14667. _gl.blendEquation( _gl.FUNC_ADD );
  14668. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  14669. } else if ( blending === THREE.MultiplyBlending ) {
  14670. // TODO: Find blendFuncSeparate() combination
  14671. _gl.enable( _gl.BLEND );
  14672. _gl.blendEquation( _gl.FUNC_ADD );
  14673. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  14674. } else if ( blending === THREE.CustomBlending ) {
  14675. _gl.enable( _gl.BLEND );
  14676. } else {
  14677. _gl.enable( _gl.BLEND );
  14678. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  14679. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  14680. }
  14681. _oldBlending = blending;
  14682. }
  14683. if ( blending === THREE.CustomBlending ) {
  14684. if ( blendEquation !== _oldBlendEquation ) {
  14685. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  14686. _oldBlendEquation = blendEquation;
  14687. }
  14688. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  14689. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  14690. _oldBlendSrc = blendSrc;
  14691. _oldBlendDst = blendDst;
  14692. }
  14693. } else {
  14694. _oldBlendEquation = null;
  14695. _oldBlendSrc = null;
  14696. _oldBlendDst = null;
  14697. }
  14698. };
  14699. // Defines
  14700. function generateDefines ( defines ) {
  14701. var value, chunk, chunks = [];
  14702. for ( var d in defines ) {
  14703. value = defines[ d ];
  14704. if ( value === false ) continue;
  14705. chunk = "#define " + d + " " + value;
  14706. chunks.push( chunk );
  14707. }
  14708. return chunks.join( "\n" );
  14709. };
  14710. // Shaders
  14711. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters, index0AttributeName ) {
  14712. var p, pl, d, program, code;
  14713. var chunks = [];
  14714. // Generate code
  14715. if ( shaderID ) {
  14716. chunks.push( shaderID );
  14717. } else {
  14718. chunks.push( fragmentShader );
  14719. chunks.push( vertexShader );
  14720. }
  14721. for ( d in defines ) {
  14722. chunks.push( d );
  14723. chunks.push( defines[ d ] );
  14724. }
  14725. for ( p in parameters ) {
  14726. chunks.push( p );
  14727. chunks.push( parameters[ p ] );
  14728. }
  14729. code = chunks.join();
  14730. // Check if code has been already compiled
  14731. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  14732. var programInfo = _programs[ p ];
  14733. if ( programInfo.code === code ) {
  14734. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  14735. programInfo.usedTimes ++;
  14736. return programInfo.program;
  14737. }
  14738. }
  14739. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  14740. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  14741. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  14742. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  14743. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  14744. }
  14745. // console.log( "building new program " );
  14746. //
  14747. var customDefines = generateDefines( defines );
  14748. //
  14749. program = _gl.createProgram();
  14750. var prefix_vertex = [
  14751. "precision " + _precision + " float;",
  14752. "precision " + _precision + " int;",
  14753. customDefines,
  14754. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  14755. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14756. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14757. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14758. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14759. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14760. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14761. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14762. "#define MAX_SHADOWS " + parameters.maxShadows,
  14763. "#define MAX_BONES " + parameters.maxBones,
  14764. parameters.map ? "#define USE_MAP" : "",
  14765. parameters.envMap ? "#define USE_ENVMAP" : "",
  14766. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14767. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14768. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14769. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14770. parameters.vertexColors ? "#define USE_COLOR" : "",
  14771. parameters.skinning ? "#define USE_SKINNING" : "",
  14772. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  14773. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  14774. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  14775. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14776. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14777. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14778. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14779. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14780. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14781. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14782. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14783. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  14784. "uniform mat4 modelMatrix;",
  14785. "uniform mat4 modelViewMatrix;",
  14786. "uniform mat4 projectionMatrix;",
  14787. "uniform mat4 viewMatrix;",
  14788. "uniform mat3 normalMatrix;",
  14789. "uniform vec3 cameraPosition;",
  14790. "attribute vec3 position;",
  14791. "attribute vec3 normal;",
  14792. "attribute vec2 uv;",
  14793. "attribute vec2 uv2;",
  14794. "#ifdef USE_COLOR",
  14795. "attribute vec3 color;",
  14796. "#endif",
  14797. "#ifdef USE_MORPHTARGETS",
  14798. "attribute vec3 morphTarget0;",
  14799. "attribute vec3 morphTarget1;",
  14800. "attribute vec3 morphTarget2;",
  14801. "attribute vec3 morphTarget3;",
  14802. "#ifdef USE_MORPHNORMALS",
  14803. "attribute vec3 morphNormal0;",
  14804. "attribute vec3 morphNormal1;",
  14805. "attribute vec3 morphNormal2;",
  14806. "attribute vec3 morphNormal3;",
  14807. "#else",
  14808. "attribute vec3 morphTarget4;",
  14809. "attribute vec3 morphTarget5;",
  14810. "attribute vec3 morphTarget6;",
  14811. "attribute vec3 morphTarget7;",
  14812. "#endif",
  14813. "#endif",
  14814. "#ifdef USE_SKINNING",
  14815. "attribute vec4 skinIndex;",
  14816. "attribute vec4 skinWeight;",
  14817. "#endif",
  14818. ""
  14819. ].join("\n");
  14820. var prefix_fragment = [
  14821. "precision " + _precision + " float;",
  14822. "precision " + _precision + " int;",
  14823. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  14824. customDefines,
  14825. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14826. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14827. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14828. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14829. "#define MAX_SHADOWS " + parameters.maxShadows,
  14830. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  14831. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14832. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14833. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14834. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  14835. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  14836. parameters.map ? "#define USE_MAP" : "",
  14837. parameters.envMap ? "#define USE_ENVMAP" : "",
  14838. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14839. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14840. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14841. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14842. parameters.vertexColors ? "#define USE_COLOR" : "",
  14843. parameters.metal ? "#define METAL" : "",
  14844. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14845. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14846. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14847. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14848. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14849. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14850. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14851. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14852. "uniform mat4 viewMatrix;",
  14853. "uniform vec3 cameraPosition;",
  14854. ""
  14855. ].join("\n");
  14856. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  14857. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  14858. _gl.attachShader( program, glVertexShader );
  14859. _gl.attachShader( program, glFragmentShader );
  14860. //Force a particular attribute to index 0.
  14861. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  14862. //And, color, for example is often automatically bound to index 0 so disabling it
  14863. if ( index0AttributeName ) {
  14864. _gl.bindAttribLocation( program, 0, index0AttributeName );
  14865. }
  14866. _gl.linkProgram( program );
  14867. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  14868. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  14869. console.error( "Program Info Log: " + _gl.getProgramInfoLog( program ) );
  14870. }
  14871. // clean up
  14872. _gl.deleteShader( glFragmentShader );
  14873. _gl.deleteShader( glVertexShader );
  14874. // console.log( prefix_fragment + fragmentShader );
  14875. // console.log( prefix_vertex + vertexShader );
  14876. program.uniforms = {};
  14877. program.attributes = {};
  14878. var identifiers, u, a, i;
  14879. // cache uniform locations
  14880. identifiers = [
  14881. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  14882. 'morphTargetInfluences'
  14883. ];
  14884. if ( parameters.useVertexTexture ) {
  14885. identifiers.push( 'boneTexture' );
  14886. identifiers.push( 'boneTextureWidth' );
  14887. identifiers.push( 'boneTextureHeight' );
  14888. } else {
  14889. identifiers.push( 'boneGlobalMatrices' );
  14890. }
  14891. for ( u in uniforms ) {
  14892. identifiers.push( u );
  14893. }
  14894. cacheUniformLocations( program, identifiers );
  14895. // cache attributes locations
  14896. identifiers = [
  14897. "position", "normal", "uv", "uv2", "tangent", "color",
  14898. "skinIndex", "skinWeight", "lineDistance"
  14899. ];
  14900. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  14901. identifiers.push( "morphTarget" + i );
  14902. }
  14903. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  14904. identifiers.push( "morphNormal" + i );
  14905. }
  14906. for ( a in attributes ) {
  14907. identifiers.push( a );
  14908. }
  14909. cacheAttributeLocations( program, identifiers );
  14910. program.id = _programs_counter ++;
  14911. _programs.push( { program: program, code: code, usedTimes: 1 } );
  14912. _this.info.memory.programs = _programs.length;
  14913. return program;
  14914. };
  14915. // Shader parameters cache
  14916. function cacheUniformLocations ( program, identifiers ) {
  14917. var i, l, id;
  14918. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14919. id = identifiers[ i ];
  14920. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  14921. }
  14922. };
  14923. function cacheAttributeLocations ( program, identifiers ) {
  14924. var i, l, id;
  14925. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14926. id = identifiers[ i ];
  14927. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  14928. }
  14929. };
  14930. function addLineNumbers ( string ) {
  14931. var chunks = string.split( "\n" );
  14932. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  14933. // Chrome reports shader errors on lines
  14934. // starting counting from 1
  14935. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  14936. }
  14937. return chunks.join( "\n" );
  14938. };
  14939. function getShader ( type, string ) {
  14940. var shader;
  14941. if ( type === "fragment" ) {
  14942. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  14943. } else if ( type === "vertex" ) {
  14944. shader = _gl.createShader( _gl.VERTEX_SHADER );
  14945. }
  14946. _gl.shaderSource( shader, string );
  14947. _gl.compileShader( shader );
  14948. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  14949. console.error( _gl.getShaderInfoLog( shader ) );
  14950. console.error( addLineNumbers( string ) );
  14951. return null;
  14952. }
  14953. return shader;
  14954. };
  14955. // Textures
  14956. function isPowerOfTwo ( value ) {
  14957. return ( value & ( value - 1 ) ) === 0;
  14958. };
  14959. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14960. if ( isImagePowerOfTwo ) {
  14961. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14962. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14963. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14964. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14965. } else {
  14966. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14967. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14968. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14969. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14970. }
  14971. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  14972. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  14973. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  14974. texture.__oldAnisotropy = texture.anisotropy;
  14975. }
  14976. }
  14977. };
  14978. this.setTexture = function ( texture, slot ) {
  14979. if ( texture.needsUpdate ) {
  14980. if ( ! texture.__webglInit ) {
  14981. texture.__webglInit = true;
  14982. texture.addEventListener( 'dispose', onTextureDispose );
  14983. texture.__webglTexture = _gl.createTexture();
  14984. _this.info.memory.textures ++;
  14985. }
  14986. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14987. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14988. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14989. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14990. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14991. var image = texture.image,
  14992. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14993. glFormat = paramThreeToGL( texture.format ),
  14994. glType = paramThreeToGL( texture.type );
  14995. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  14996. var mipmap, mipmaps = texture.mipmaps;
  14997. if ( texture instanceof THREE.DataTexture ) {
  14998. // use manually created mipmaps if available
  14999. // if there are no manual mipmaps
  15000. // set 0 level mipmap and then use GL to generate other mipmap levels
  15001. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15002. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15003. mipmap = mipmaps[ i ];
  15004. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15005. }
  15006. texture.generateMipmaps = false;
  15007. } else {
  15008. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15009. }
  15010. } else if ( texture instanceof THREE.CompressedTexture ) {
  15011. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15012. mipmap = mipmaps[ i ];
  15013. if ( texture.format!==THREE.RGBAFormat ) {
  15014. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15015. } else {
  15016. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15017. }
  15018. }
  15019. } else { // regular Texture (image, video, canvas)
  15020. // use manually created mipmaps if available
  15021. // if there are no manual mipmaps
  15022. // set 0 level mipmap and then use GL to generate other mipmap levels
  15023. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15024. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15025. mipmap = mipmaps[ i ];
  15026. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15027. }
  15028. texture.generateMipmaps = false;
  15029. } else {
  15030. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  15031. }
  15032. }
  15033. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15034. texture.needsUpdate = false;
  15035. if ( texture.onUpdate ) texture.onUpdate();
  15036. } else {
  15037. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15038. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15039. }
  15040. };
  15041. function clampToMaxSize ( image, maxSize ) {
  15042. if ( image.width <= maxSize && image.height <= maxSize ) {
  15043. return image;
  15044. }
  15045. // Warning: Scaling through the canvas will only work with images that use
  15046. // premultiplied alpha.
  15047. var maxDimension = Math.max( image.width, image.height );
  15048. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15049. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15050. var canvas = document.createElement( 'canvas' );
  15051. canvas.width = newWidth;
  15052. canvas.height = newHeight;
  15053. var ctx = canvas.getContext( "2d" );
  15054. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15055. return canvas;
  15056. }
  15057. function setCubeTexture ( texture, slot ) {
  15058. if ( texture.image.length === 6 ) {
  15059. if ( texture.needsUpdate ) {
  15060. if ( ! texture.image.__webglTextureCube ) {
  15061. texture.addEventListener( 'dispose', onTextureDispose );
  15062. texture.image.__webglTextureCube = _gl.createTexture();
  15063. _this.info.memory.textures ++;
  15064. }
  15065. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15066. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15067. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15068. var isCompressed = texture instanceof THREE.CompressedTexture;
  15069. var cubeImage = [];
  15070. for ( var i = 0; i < 6; i ++ ) {
  15071. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15072. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15073. } else {
  15074. cubeImage[ i ] = texture.image[ i ];
  15075. }
  15076. }
  15077. var image = cubeImage[ 0 ],
  15078. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  15079. glFormat = paramThreeToGL( texture.format ),
  15080. glType = paramThreeToGL( texture.type );
  15081. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15082. for ( var i = 0; i < 6; i ++ ) {
  15083. if( !isCompressed ) {
  15084. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15085. } else {
  15086. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15087. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15088. mipmap = mipmaps[ j ];
  15089. if ( texture.format!==THREE.RGBAFormat ) {
  15090. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15091. } else {
  15092. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15093. }
  15094. }
  15095. }
  15096. }
  15097. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15098. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15099. }
  15100. texture.needsUpdate = false;
  15101. if ( texture.onUpdate ) texture.onUpdate();
  15102. } else {
  15103. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15104. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15105. }
  15106. }
  15107. };
  15108. function setCubeTextureDynamic ( texture, slot ) {
  15109. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15110. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15111. };
  15112. // Render targets
  15113. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15114. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15115. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15116. };
  15117. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15118. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15119. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15120. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15121. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15122. /* For some reason this is not working. Defaulting to RGBA4.
  15123. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15124. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15125. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15126. */
  15127. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15128. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15129. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15130. } else {
  15131. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15132. }
  15133. };
  15134. this.setRenderTarget = function ( renderTarget ) {
  15135. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15136. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15137. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15138. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15139. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15140. renderTarget.__webglTexture = _gl.createTexture();
  15141. _this.info.memory.textures ++;
  15142. // Setup texture, create render and frame buffers
  15143. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  15144. glFormat = paramThreeToGL( renderTarget.format ),
  15145. glType = paramThreeToGL( renderTarget.type );
  15146. if ( isCube ) {
  15147. renderTarget.__webglFramebuffer = [];
  15148. renderTarget.__webglRenderbuffer = [];
  15149. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15150. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15151. for ( var i = 0; i < 6; i ++ ) {
  15152. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15153. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15154. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15155. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15156. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15157. }
  15158. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15159. } else {
  15160. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15161. if ( renderTarget.shareDepthFrom ) {
  15162. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15163. } else {
  15164. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15165. }
  15166. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15167. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15168. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15169. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15170. if ( renderTarget.shareDepthFrom ) {
  15171. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15172. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15173. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15174. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15175. }
  15176. } else {
  15177. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15178. }
  15179. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15180. }
  15181. // Release everything
  15182. if ( isCube ) {
  15183. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15184. } else {
  15185. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15186. }
  15187. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15188. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15189. }
  15190. var framebuffer, width, height, vx, vy;
  15191. if ( renderTarget ) {
  15192. if ( isCube ) {
  15193. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15194. } else {
  15195. framebuffer = renderTarget.__webglFramebuffer;
  15196. }
  15197. width = renderTarget.width;
  15198. height = renderTarget.height;
  15199. vx = 0;
  15200. vy = 0;
  15201. } else {
  15202. framebuffer = null;
  15203. width = _viewportWidth;
  15204. height = _viewportHeight;
  15205. vx = _viewportX;
  15206. vy = _viewportY;
  15207. }
  15208. if ( framebuffer !== _currentFramebuffer ) {
  15209. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15210. _gl.viewport( vx, vy, width, height );
  15211. _currentFramebuffer = framebuffer;
  15212. }
  15213. _currentWidth = width;
  15214. _currentHeight = height;
  15215. };
  15216. function updateRenderTargetMipmap ( renderTarget ) {
  15217. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15218. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15219. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15220. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15221. } else {
  15222. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15223. _gl.generateMipmap( _gl.TEXTURE_2D );
  15224. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15225. }
  15226. };
  15227. // Fallback filters for non-power-of-2 textures
  15228. function filterFallback ( f ) {
  15229. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15230. return _gl.NEAREST;
  15231. }
  15232. return _gl.LINEAR;
  15233. };
  15234. // Map three.js constants to WebGL constants
  15235. function paramThreeToGL ( p ) {
  15236. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15237. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15238. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15239. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15240. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15241. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15242. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15243. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15244. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15245. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15246. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15247. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15248. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15249. if ( p === THREE.ByteType ) return _gl.BYTE;
  15250. if ( p === THREE.ShortType ) return _gl.SHORT;
  15251. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15252. if ( p === THREE.IntType ) return _gl.INT;
  15253. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15254. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15255. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15256. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15257. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15258. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15259. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15260. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15261. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15262. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15263. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15264. if ( p === THREE.OneFactor ) return _gl.ONE;
  15265. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15266. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15267. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15268. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15269. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15270. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15271. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15272. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15273. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15274. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15275. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15276. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15277. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15278. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15279. }
  15280. return 0;
  15281. };
  15282. // Allocations
  15283. function allocateBones ( object ) {
  15284. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15285. return 1024;
  15286. } else {
  15287. // default for when object is not specified
  15288. // ( for example when prebuilding shader
  15289. // to be used with multiple objects )
  15290. //
  15291. // - leave some extra space for other uniforms
  15292. // - limit here is ANGLE's 254 max uniform vectors
  15293. // (up to 54 should be safe)
  15294. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15295. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15296. var maxBones = nVertexMatrices;
  15297. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15298. maxBones = Math.min( object.bones.length, maxBones );
  15299. if ( maxBones < object.bones.length ) {
  15300. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15301. }
  15302. }
  15303. return maxBones;
  15304. }
  15305. };
  15306. function allocateLights( lights ) {
  15307. var dirLights = 0;
  15308. var pointLights = 0;
  15309. var spotLights = 0;
  15310. var hemiLights = 0;
  15311. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15312. var light = lights[ l ];
  15313. if ( light.onlyShadow ) continue;
  15314. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15315. if ( light instanceof THREE.PointLight ) pointLights ++;
  15316. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15317. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15318. }
  15319. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15320. };
  15321. function allocateShadows( lights ) {
  15322. var maxShadows = 0;
  15323. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  15324. var light = lights[ l ];
  15325. if ( ! light.castShadow ) continue;
  15326. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15327. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15328. }
  15329. return maxShadows;
  15330. };
  15331. // Initialization
  15332. function initGL() {
  15333. try {
  15334. var attributes = {
  15335. alpha: _alpha,
  15336. premultipliedAlpha: _premultipliedAlpha,
  15337. antialias: _antialias,
  15338. stencil: _stencil,
  15339. preserveDrawingBuffer: _preserveDrawingBuffer
  15340. };
  15341. _gl = _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  15342. if ( _gl === null ) {
  15343. throw 'Error creating WebGL context.';
  15344. }
  15345. } catch ( error ) {
  15346. console.error( error );
  15347. }
  15348. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15349. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15350. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15351. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15352. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15353. if ( ! _glExtensionTextureFloat ) {
  15354. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15355. }
  15356. if ( ! _glExtensionStandardDerivatives ) {
  15357. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15358. }
  15359. if ( ! _glExtensionTextureFilterAnisotropic ) {
  15360. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15361. }
  15362. if ( ! _glExtensionCompressedTextureS3TC ) {
  15363. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15364. }
  15365. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15366. _gl.getShaderPrecisionFormat = function() {
  15367. return {
  15368. "rangeMin" : 1,
  15369. "rangeMax" : 1,
  15370. "precision" : 1
  15371. };
  15372. }
  15373. }
  15374. };
  15375. function setDefaultGLState () {
  15376. _gl.clearColor( 0, 0, 0, 1 );
  15377. _gl.clearDepth( 1 );
  15378. _gl.clearStencil( 0 );
  15379. _gl.enable( _gl.DEPTH_TEST );
  15380. _gl.depthFunc( _gl.LEQUAL );
  15381. _gl.frontFace( _gl.CCW );
  15382. _gl.cullFace( _gl.BACK );
  15383. _gl.enable( _gl.CULL_FACE );
  15384. _gl.enable( _gl.BLEND );
  15385. _gl.blendEquation( _gl.FUNC_ADD );
  15386. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15387. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  15388. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15389. };
  15390. // default plugins (order is important)
  15391. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15392. this.addPrePlugin( this.shadowMapPlugin );
  15393. this.addPostPlugin( new THREE.SpritePlugin() );
  15394. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15395. };
  15396. /**
  15397. * @author szimek / https://github.com/szimek/
  15398. * @author alteredq / http://alteredqualia.com/
  15399. */
  15400. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15401. this.width = width;
  15402. this.height = height;
  15403. options = options || {};
  15404. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15405. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15406. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15407. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15408. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15409. this.offset = new THREE.Vector2( 0, 0 );
  15410. this.repeat = new THREE.Vector2( 1, 1 );
  15411. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15412. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15413. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15414. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15415. this.generateMipmaps = true;
  15416. this.shareDepthFrom = null;
  15417. };
  15418. THREE.WebGLRenderTarget.prototype = {
  15419. constructor: THREE.WebGLRenderTarget,
  15420. clone: function () {
  15421. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15422. tmp.wrapS = this.wrapS;
  15423. tmp.wrapT = this.wrapT;
  15424. tmp.magFilter = this.magFilter;
  15425. tmp.minFilter = this.minFilter;
  15426. tmp.anisotropy = this.anisotropy;
  15427. tmp.offset.copy( this.offset );
  15428. tmp.repeat.copy( this.repeat );
  15429. tmp.format = this.format;
  15430. tmp.type = this.type;
  15431. tmp.depthBuffer = this.depthBuffer;
  15432. tmp.stencilBuffer = this.stencilBuffer;
  15433. tmp.generateMipmaps = this.generateMipmaps;
  15434. tmp.shareDepthFrom = this.shareDepthFrom;
  15435. return tmp;
  15436. },
  15437. dispose: function () {
  15438. this.dispatchEvent( { type: 'dispose' } );
  15439. }
  15440. };
  15441. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  15442. /**
  15443. * @author alteredq / http://alteredqualia.com
  15444. */
  15445. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15446. THREE.WebGLRenderTarget.call( this, width, height, options );
  15447. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15448. };
  15449. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15450. /**
  15451. * @author mrdoob / http://mrdoob.com/
  15452. */
  15453. THREE.RenderableVertex = function () {
  15454. this.positionWorld = new THREE.Vector3();
  15455. this.positionScreen = new THREE.Vector4();
  15456. this.visible = true;
  15457. };
  15458. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15459. this.positionWorld.copy( vertex.positionWorld );
  15460. this.positionScreen.copy( vertex.positionScreen );
  15461. };
  15462. /**
  15463. * @author mrdoob / http://mrdoob.com/
  15464. */
  15465. THREE.RenderableFace3 = function () {
  15466. this.id = 0;
  15467. this.v1 = new THREE.RenderableVertex();
  15468. this.v2 = new THREE.RenderableVertex();
  15469. this.v3 = new THREE.RenderableVertex();
  15470. this.centroidModel = new THREE.Vector3();
  15471. this.normalModel = new THREE.Vector3();
  15472. this.normalModelView = new THREE.Vector3();
  15473. this.vertexNormalsLength = 0;
  15474. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15475. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15476. this.color = null;
  15477. this.material = null;
  15478. this.uvs = [[]];
  15479. this.z = 0;
  15480. };
  15481. /**
  15482. * @author mrdoob / http://mrdoob.com/
  15483. */
  15484. THREE.RenderableObject = function () {
  15485. this.id = 0;
  15486. this.object = null;
  15487. this.z = 0;
  15488. };
  15489. /**
  15490. * @author mrdoob / http://mrdoob.com/
  15491. */
  15492. THREE.RenderableSprite = function () {
  15493. this.id = 0;
  15494. this.object = null;
  15495. this.x = 0;
  15496. this.y = 0;
  15497. this.z = 0;
  15498. this.rotation = 0;
  15499. this.scale = new THREE.Vector2();
  15500. this.material = null;
  15501. };
  15502. /**
  15503. * @author mrdoob / http://mrdoob.com/
  15504. */
  15505. THREE.RenderableLine = function () {
  15506. this.id = 0;
  15507. this.v1 = new THREE.RenderableVertex();
  15508. this.v2 = new THREE.RenderableVertex();
  15509. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  15510. this.material = null;
  15511. this.z = 0;
  15512. };
  15513. /**
  15514. * @author mrdoob / http://mrdoob.com/
  15515. * @author alteredq / http://alteredqualia.com/
  15516. */
  15517. THREE.GeometryUtils = {
  15518. // Merge two geometries or geometry and geometry from object (using object's transform)
  15519. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  15520. var matrix, normalMatrix,
  15521. vertexOffset = geometry1.vertices.length,
  15522. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15523. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15524. vertices1 = geometry1.vertices,
  15525. vertices2 = geometry2.vertices,
  15526. faces1 = geometry1.faces,
  15527. faces2 = geometry2.faces,
  15528. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15529. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15530. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  15531. if ( object2 instanceof THREE.Mesh ) {
  15532. object2.matrixAutoUpdate && object2.updateMatrix();
  15533. matrix = object2.matrix;
  15534. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  15535. }
  15536. // vertices
  15537. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15538. var vertex = vertices2[ i ];
  15539. var vertexCopy = vertex.clone();
  15540. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15541. vertices1.push( vertexCopy );
  15542. }
  15543. // faces
  15544. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15545. var face = faces2[ i ], faceCopy, normal, color,
  15546. faceVertexNormals = face.vertexNormals,
  15547. faceVertexColors = face.vertexColors;
  15548. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15549. faceCopy.normal.copy( face.normal );
  15550. if ( normalMatrix ) {
  15551. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15552. }
  15553. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15554. normal = faceVertexNormals[ j ].clone();
  15555. if ( normalMatrix ) {
  15556. normal.applyMatrix3( normalMatrix ).normalize();
  15557. }
  15558. faceCopy.vertexNormals.push( normal );
  15559. }
  15560. faceCopy.color.copy( face.color );
  15561. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15562. color = faceVertexColors[ j ];
  15563. faceCopy.vertexColors.push( color.clone() );
  15564. }
  15565. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  15566. faceCopy.centroid.copy( face.centroid );
  15567. if ( matrix ) {
  15568. faceCopy.centroid.applyMatrix4( matrix );
  15569. }
  15570. faces1.push( faceCopy );
  15571. }
  15572. // uvs
  15573. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15574. var uv = uvs2[ i ], uvCopy = [];
  15575. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15576. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15577. }
  15578. uvs1.push( uvCopy );
  15579. }
  15580. },
  15581. // Get random point in triangle (via barycentric coordinates)
  15582. // (uniform distribution)
  15583. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15584. randomPointInTriangle: function () {
  15585. var vector = new THREE.Vector3();
  15586. return function ( vectorA, vectorB, vectorC ) {
  15587. var point = new THREE.Vector3();
  15588. var a = THREE.Math.random16();
  15589. var b = THREE.Math.random16();
  15590. if ( ( a + b ) > 1 ) {
  15591. a = 1 - a;
  15592. b = 1 - b;
  15593. }
  15594. var c = 1 - a - b;
  15595. point.copy( vectorA );
  15596. point.multiplyScalar( a );
  15597. vector.copy( vectorB );
  15598. vector.multiplyScalar( b );
  15599. point.add( vector );
  15600. vector.copy( vectorC );
  15601. vector.multiplyScalar( c );
  15602. point.add( vector );
  15603. return point;
  15604. };
  15605. }(),
  15606. // Get random point in face (triangle / quad)
  15607. // (uniform distribution)
  15608. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15609. var vA, vB, vC, vD;
  15610. vA = geometry.vertices[ face.a ];
  15611. vB = geometry.vertices[ face.b ];
  15612. vC = geometry.vertices[ face.c ];
  15613. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15614. },
  15615. // Get uniformly distributed random points in mesh
  15616. // - create array with cumulative sums of face areas
  15617. // - pick random number from 0 to total area
  15618. // - find corresponding place in area array by binary search
  15619. // - get random point in face
  15620. randomPointsInGeometry: function ( geometry, n ) {
  15621. var face, i,
  15622. faces = geometry.faces,
  15623. vertices = geometry.vertices,
  15624. il = faces.length,
  15625. totalArea = 0,
  15626. cumulativeAreas = [],
  15627. vA, vB, vC, vD;
  15628. // precompute face areas
  15629. for ( i = 0; i < il; i ++ ) {
  15630. face = faces[ i ];
  15631. vA = vertices[ face.a ];
  15632. vB = vertices[ face.b ];
  15633. vC = vertices[ face.c ];
  15634. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  15635. totalArea += face._area;
  15636. cumulativeAreas[ i ] = totalArea;
  15637. }
  15638. // binary search cumulative areas array
  15639. function binarySearchIndices( value ) {
  15640. function binarySearch( start, end ) {
  15641. // return closest larger index
  15642. // if exact number is not found
  15643. if ( end < start )
  15644. return start;
  15645. var mid = start + Math.floor( ( end - start ) / 2 );
  15646. if ( cumulativeAreas[ mid ] > value ) {
  15647. return binarySearch( start, mid - 1 );
  15648. } else if ( cumulativeAreas[ mid ] < value ) {
  15649. return binarySearch( mid + 1, end );
  15650. } else {
  15651. return mid;
  15652. }
  15653. }
  15654. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  15655. return result;
  15656. }
  15657. // pick random face weighted by face area
  15658. var r, index,
  15659. result = [];
  15660. var stats = {};
  15661. for ( i = 0; i < n; i ++ ) {
  15662. r = THREE.Math.random16() * totalArea;
  15663. index = binarySearchIndices( r );
  15664. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  15665. if ( ! stats[ index ] ) {
  15666. stats[ index ] = 1;
  15667. } else {
  15668. stats[ index ] += 1;
  15669. }
  15670. }
  15671. return result;
  15672. },
  15673. // Get triangle area (half of parallelogram)
  15674. // http://mathworld.wolfram.com/TriangleArea.html
  15675. triangleArea: function () {
  15676. var vector1 = new THREE.Vector3();
  15677. var vector2 = new THREE.Vector3();
  15678. return function ( vectorA, vectorB, vectorC ) {
  15679. vector1.subVectors( vectorB, vectorA );
  15680. vector2.subVectors( vectorC, vectorA );
  15681. vector1.cross( vector2 );
  15682. return 0.5 * vector1.length();
  15683. };
  15684. }(),
  15685. // Center geometry so that 0,0,0 is in center of bounding box
  15686. center: function ( geometry ) {
  15687. geometry.computeBoundingBox();
  15688. var bb = geometry.boundingBox;
  15689. var offset = new THREE.Vector3();
  15690. offset.addVectors( bb.min, bb.max );
  15691. offset.multiplyScalar( -0.5 );
  15692. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  15693. geometry.computeBoundingBox();
  15694. return offset;
  15695. },
  15696. triangulateQuads: function ( geometry ) {
  15697. var i, il, j, jl;
  15698. var faces = [];
  15699. var faceVertexUvs = [];
  15700. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15701. faceVertexUvs[ i ] = [];
  15702. }
  15703. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15704. var face = geometry.faces[ i ];
  15705. faces.push( face );
  15706. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15707. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15708. }
  15709. }
  15710. geometry.faces = faces;
  15711. geometry.faceVertexUvs = faceVertexUvs;
  15712. geometry.computeCentroids();
  15713. geometry.computeFaceNormals();
  15714. geometry.computeVertexNormals();
  15715. if ( geometry.hasTangents ) geometry.computeTangents();
  15716. }
  15717. };
  15718. /**
  15719. * @author alteredq / http://alteredqualia.com/
  15720. * @author mrdoob / http://mrdoob.com/
  15721. */
  15722. THREE.ImageUtils = {
  15723. crossOrigin: 'anonymous',
  15724. loadTexture: function ( url, mapping, onLoad, onError ) {
  15725. var loader = new THREE.ImageLoader();
  15726. loader.crossOrigin = this.crossOrigin;
  15727. var texture = new THREE.Texture( undefined, mapping );
  15728. var image = loader.load( url, function () {
  15729. texture.needsUpdate = true;
  15730. if ( onLoad ) onLoad( texture );
  15731. } );
  15732. texture.image = image;
  15733. texture.sourceFile = url;
  15734. return texture;
  15735. },
  15736. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15737. var texture = new THREE.CompressedTexture();
  15738. texture.mapping = mapping;
  15739. var request = new XMLHttpRequest();
  15740. request.onload = function () {
  15741. var buffer = request.response;
  15742. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15743. texture.format = dds.format;
  15744. texture.mipmaps = dds.mipmaps;
  15745. texture.image.width = dds.width;
  15746. texture.image.height = dds.height;
  15747. // gl.generateMipmap fails for compressed textures
  15748. // mipmaps must be embedded in the DDS file
  15749. // or texture filters must not use mipmapping
  15750. texture.generateMipmaps = false;
  15751. texture.needsUpdate = true;
  15752. if ( onLoad ) onLoad( texture );
  15753. }
  15754. request.onerror = onError;
  15755. request.open( 'GET', url, true );
  15756. request.responseType = "arraybuffer";
  15757. request.send( null );
  15758. return texture;
  15759. },
  15760. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15761. var images = [];
  15762. images.loadCount = 0;
  15763. var texture = new THREE.Texture();
  15764. texture.image = images;
  15765. if ( mapping !== undefined ) texture.mapping = mapping;
  15766. // no flipping needed for cube textures
  15767. texture.flipY = false;
  15768. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15769. var cubeImage = new Image();
  15770. images[ i ] = cubeImage;
  15771. cubeImage.onload = function () {
  15772. images.loadCount += 1;
  15773. if ( images.loadCount === 6 ) {
  15774. texture.needsUpdate = true;
  15775. if ( onLoad ) onLoad( texture );
  15776. }
  15777. };
  15778. cubeImage.onerror = onError;
  15779. cubeImage.crossOrigin = this.crossOrigin;
  15780. cubeImage.src = array[ i ];
  15781. }
  15782. return texture;
  15783. },
  15784. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15785. var images = [];
  15786. images.loadCount = 0;
  15787. var texture = new THREE.CompressedTexture();
  15788. texture.image = images;
  15789. if ( mapping !== undefined ) texture.mapping = mapping;
  15790. // no flipping for cube textures
  15791. // (also flipping doesn't work for compressed textures )
  15792. texture.flipY = false;
  15793. // can't generate mipmaps for compressed textures
  15794. // mips must be embedded in DDS files
  15795. texture.generateMipmaps = false;
  15796. var generateCubeFaceCallback = function ( rq, img ) {
  15797. return function () {
  15798. var buffer = rq.response;
  15799. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15800. img.format = dds.format;
  15801. img.mipmaps = dds.mipmaps;
  15802. img.width = dds.width;
  15803. img.height = dds.height;
  15804. images.loadCount += 1;
  15805. if ( images.loadCount === 6 ) {
  15806. texture.format = dds.format;
  15807. texture.needsUpdate = true;
  15808. if ( onLoad ) onLoad( texture );
  15809. }
  15810. }
  15811. }
  15812. // compressed cubemap textures as 6 separate DDS files
  15813. if ( array instanceof Array ) {
  15814. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15815. var cubeImage = {};
  15816. images[ i ] = cubeImage;
  15817. var request = new XMLHttpRequest();
  15818. request.onload = generateCubeFaceCallback( request, cubeImage );
  15819. request.onerror = onError;
  15820. var url = array[ i ];
  15821. request.open( 'GET', url, true );
  15822. request.responseType = "arraybuffer";
  15823. request.send( null );
  15824. }
  15825. // compressed cubemap texture stored in a single DDS file
  15826. } else {
  15827. var url = array;
  15828. var request = new XMLHttpRequest();
  15829. request.onload = function( ) {
  15830. var buffer = request.response;
  15831. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15832. if ( dds.isCubemap ) {
  15833. var faces = dds.mipmaps.length / dds.mipmapCount;
  15834. for ( var f = 0; f < faces; f ++ ) {
  15835. images[ f ] = { mipmaps : [] };
  15836. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15837. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15838. images[ f ].format = dds.format;
  15839. images[ f ].width = dds.width;
  15840. images[ f ].height = dds.height;
  15841. }
  15842. }
  15843. texture.format = dds.format;
  15844. texture.needsUpdate = true;
  15845. if ( onLoad ) onLoad( texture );
  15846. }
  15847. }
  15848. request.onerror = onError;
  15849. request.open( 'GET', url, true );
  15850. request.responseType = "arraybuffer";
  15851. request.send( null );
  15852. }
  15853. return texture;
  15854. },
  15855. loadDDSTexture: function ( url, mapping, onLoad, onError ) {
  15856. var images = [];
  15857. images.loadCount = 0;
  15858. var texture = new THREE.CompressedTexture();
  15859. texture.image = images;
  15860. if ( mapping !== undefined ) texture.mapping = mapping;
  15861. // no flipping for cube textures
  15862. // (also flipping doesn't work for compressed textures )
  15863. texture.flipY = false;
  15864. // can't generate mipmaps for compressed textures
  15865. // mips must be embedded in DDS files
  15866. texture.generateMipmaps = false;
  15867. {
  15868. var request = new XMLHttpRequest();
  15869. request.onload = function( ) {
  15870. var buffer = request.response;
  15871. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15872. if ( dds.isCubemap ) {
  15873. var faces = dds.mipmaps.length / dds.mipmapCount;
  15874. for ( var f = 0; f < faces; f ++ ) {
  15875. images[ f ] = { mipmaps : [] };
  15876. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15877. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15878. images[ f ].format = dds.format;
  15879. images[ f ].width = dds.width;
  15880. images[ f ].height = dds.height;
  15881. }
  15882. }
  15883. } else {
  15884. texture.image.width = dds.width;
  15885. texture.image.height = dds.height;
  15886. texture.mipmaps = dds.mipmaps;
  15887. }
  15888. texture.format = dds.format;
  15889. texture.needsUpdate = true;
  15890. if ( onLoad ) onLoad( texture );
  15891. }
  15892. request.onerror = onError;
  15893. request.open( 'GET', url, true );
  15894. request.responseType = "arraybuffer";
  15895. request.send( null );
  15896. }
  15897. return texture;
  15898. },
  15899. parseDDS: function ( buffer, loadMipmaps ) {
  15900. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15901. // Adapted from @toji's DDS utils
  15902. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15903. // All values and structures referenced from:
  15904. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15905. var DDS_MAGIC = 0x20534444;
  15906. var DDSD_CAPS = 0x1,
  15907. DDSD_HEIGHT = 0x2,
  15908. DDSD_WIDTH = 0x4,
  15909. DDSD_PITCH = 0x8,
  15910. DDSD_PIXELFORMAT = 0x1000,
  15911. DDSD_MIPMAPCOUNT = 0x20000,
  15912. DDSD_LINEARSIZE = 0x80000,
  15913. DDSD_DEPTH = 0x800000;
  15914. var DDSCAPS_COMPLEX = 0x8,
  15915. DDSCAPS_MIPMAP = 0x400000,
  15916. DDSCAPS_TEXTURE = 0x1000;
  15917. var DDSCAPS2_CUBEMAP = 0x200,
  15918. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15919. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15920. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15921. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15922. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15923. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15924. DDSCAPS2_VOLUME = 0x200000;
  15925. var DDPF_ALPHAPIXELS = 0x1,
  15926. DDPF_ALPHA = 0x2,
  15927. DDPF_FOURCC = 0x4,
  15928. DDPF_RGB = 0x40,
  15929. DDPF_YUV = 0x200,
  15930. DDPF_LUMINANCE = 0x20000;
  15931. function fourCCToInt32( value ) {
  15932. return value.charCodeAt(0) +
  15933. (value.charCodeAt(1) << 8) +
  15934. (value.charCodeAt(2) << 16) +
  15935. (value.charCodeAt(3) << 24);
  15936. }
  15937. function int32ToFourCC( value ) {
  15938. return String.fromCharCode(
  15939. value & 0xff,
  15940. (value >> 8) & 0xff,
  15941. (value >> 16) & 0xff,
  15942. (value >> 24) & 0xff
  15943. );
  15944. }
  15945. function loadARGBMip( buffer, dataOffset, width, height ) {
  15946. var dataLength = width*height*4;
  15947. var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength );
  15948. var byteArray = new Uint8Array( dataLength );
  15949. var dst = 0;
  15950. var src = 0;
  15951. for ( var y = 0; y < height; y++ ) {
  15952. for ( var x = 0; x < width; x++ ) {
  15953. var b = srcBuffer[src]; src++;
  15954. var g = srcBuffer[src]; src++;
  15955. var r = srcBuffer[src]; src++;
  15956. var a = srcBuffer[src]; src++;
  15957. byteArray[dst] = r; dst++; //r
  15958. byteArray[dst] = g; dst++; //g
  15959. byteArray[dst] = b; dst++; //b
  15960. byteArray[dst] = a; dst++; //a
  15961. }
  15962. }
  15963. return byteArray;
  15964. }
  15965. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15966. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15967. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15968. var headerLengthInt = 31; // The header length in 32 bit ints
  15969. // Offsets into the header array
  15970. var off_magic = 0;
  15971. var off_size = 1;
  15972. var off_flags = 2;
  15973. var off_height = 3;
  15974. var off_width = 4;
  15975. var off_mipmapCount = 7;
  15976. var off_pfFlags = 20;
  15977. var off_pfFourCC = 21;
  15978. var off_RGBBitCount = 22;
  15979. var off_RBitMask = 23;
  15980. var off_GBitMask = 24;
  15981. var off_BBitMask = 25;
  15982. var off_ABitMask = 26;
  15983. var off_caps = 27;
  15984. var off_caps2 = 28;
  15985. var off_caps3 = 29;
  15986. var off_caps4 = 30;
  15987. // Parse header
  15988. var header = new Int32Array( buffer, 0, headerLengthInt );
  15989. if ( header[ off_magic ] !== DDS_MAGIC ) {
  15990. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  15991. return dds;
  15992. }
  15993. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  15994. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  15995. return dds;
  15996. }
  15997. var blockBytes;
  15998. var fourCC = header[ off_pfFourCC ];
  15999. var isRGBAUncompressed = false;
  16000. switch ( fourCC ) {
  16001. case FOURCC_DXT1:
  16002. blockBytes = 8;
  16003. dds.format = THREE.RGB_S3TC_DXT1_Format;
  16004. break;
  16005. case FOURCC_DXT3:
  16006. blockBytes = 16;
  16007. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  16008. break;
  16009. case FOURCC_DXT5:
  16010. blockBytes = 16;
  16011. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  16012. break;
  16013. default:
  16014. if( header[off_RGBBitCount] ==32
  16015. && header[off_RBitMask]&0xff0000
  16016. && header[off_GBitMask]&0xff00
  16017. && header[off_BBitMask]&0xff
  16018. && header[off_ABitMask]&0xff000000 ) {
  16019. isRGBAUncompressed = true;
  16020. blockBytes = 64;
  16021. dds.format = THREE.RGBAFormat;
  16022. } else {
  16023. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  16024. return dds;
  16025. }
  16026. }
  16027. dds.mipmapCount = 1;
  16028. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  16029. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  16030. }
  16031. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  16032. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  16033. dds.width = header[ off_width ];
  16034. dds.height = header[ off_height ];
  16035. var dataOffset = header[ off_size ] + 4;
  16036. // Extract mipmaps buffers
  16037. var width = dds.width;
  16038. var height = dds.height;
  16039. var faces = dds.isCubemap ? 6 : 1;
  16040. for ( var face = 0; face < faces; face ++ ) {
  16041. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16042. if( isRGBAUncompressed ) {
  16043. var byteArray = loadARGBMip( buffer, dataOffset, width, height );
  16044. var dataLength = byteArray.length;
  16045. } else {
  16046. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16047. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16048. }
  16049. var mipmap = { "data": byteArray, "width": width, "height": height };
  16050. dds.mipmaps.push( mipmap );
  16051. dataOffset += dataLength;
  16052. width = Math.max( width * 0.5, 1 );
  16053. height = Math.max( height * 0.5, 1 );
  16054. }
  16055. width = dds.width;
  16056. height = dds.height;
  16057. }
  16058. return dds;
  16059. },
  16060. getNormalMap: function ( image, depth ) {
  16061. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16062. var cross = function ( a, b ) {
  16063. return [ a[ 1 ] * b[ 2 ] - a[ 2 ] * b[ 1 ], a[ 2 ] * b[ 0 ] - a[ 0 ] * b[ 2 ], a[ 0 ] * b[ 1 ] - a[ 1 ] * b[ 0 ] ];
  16064. }
  16065. var subtract = function ( a, b ) {
  16066. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16067. }
  16068. var normalize = function ( a ) {
  16069. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16070. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16071. }
  16072. depth = depth | 1;
  16073. var width = image.width;
  16074. var height = image.height;
  16075. var canvas = document.createElement( 'canvas' );
  16076. canvas.width = width;
  16077. canvas.height = height;
  16078. var context = canvas.getContext( '2d' );
  16079. context.drawImage( image, 0, 0 );
  16080. var data = context.getImageData( 0, 0, width, height ).data;
  16081. var imageData = context.createImageData( width, height );
  16082. var output = imageData.data;
  16083. for ( var x = 0; x < width; x ++ ) {
  16084. for ( var y = 0; y < height; y ++ ) {
  16085. var ly = y - 1 < 0 ? 0 : y - 1;
  16086. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16087. var lx = x - 1 < 0 ? 0 : x - 1;
  16088. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16089. var points = [];
  16090. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16091. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16092. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16093. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16094. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16095. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16096. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16097. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16098. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16099. var normals = [];
  16100. var num_points = points.length;
  16101. for ( var i = 0; i < num_points; i ++ ) {
  16102. var v1 = points[ i ];
  16103. var v2 = points[ ( i + 1 ) % num_points ];
  16104. v1 = subtract( v1, origin );
  16105. v2 = subtract( v2, origin );
  16106. normals.push( normalize( cross( v1, v2 ) ) );
  16107. }
  16108. var normal = [ 0, 0, 0 ];
  16109. for ( var i = 0; i < normals.length; i ++ ) {
  16110. normal[ 0 ] += normals[ i ][ 0 ];
  16111. normal[ 1 ] += normals[ i ][ 1 ];
  16112. normal[ 2 ] += normals[ i ][ 2 ];
  16113. }
  16114. normal[ 0 ] /= normals.length;
  16115. normal[ 1 ] /= normals.length;
  16116. normal[ 2 ] /= normals.length;
  16117. var idx = ( y * width + x ) * 4;
  16118. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16119. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16120. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16121. output[ idx + 3 ] = 255;
  16122. }
  16123. }
  16124. context.putImageData( imageData, 0, 0 );
  16125. return canvas;
  16126. },
  16127. generateDataTexture: function ( width, height, color ) {
  16128. var size = width * height;
  16129. var data = new Uint8Array( 3 * size );
  16130. var r = Math.floor( color.r * 255 );
  16131. var g = Math.floor( color.g * 255 );
  16132. var b = Math.floor( color.b * 255 );
  16133. for ( var i = 0; i < size; i ++ ) {
  16134. data[ i * 3 ] = r;
  16135. data[ i * 3 + 1 ] = g;
  16136. data[ i * 3 + 2 ] = b;
  16137. }
  16138. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16139. texture.needsUpdate = true;
  16140. return texture;
  16141. }
  16142. };
  16143. /**
  16144. * @author alteredq / http://alteredqualia.com/
  16145. */
  16146. THREE.SceneUtils = {
  16147. createMultiMaterialObject: function ( geometry, materials ) {
  16148. var group = new THREE.Object3D();
  16149. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16150. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16151. }
  16152. return group;
  16153. },
  16154. detach : function ( child, parent, scene ) {
  16155. child.applyMatrix( parent.matrixWorld );
  16156. parent.remove( child );
  16157. scene.add( child );
  16158. },
  16159. attach: function ( child, scene, parent ) {
  16160. var matrixWorldInverse = new THREE.Matrix4();
  16161. matrixWorldInverse.getInverse( parent.matrixWorld );
  16162. child.applyMatrix( matrixWorldInverse );
  16163. scene.remove( child );
  16164. parent.add( child );
  16165. }
  16166. };
  16167. /**
  16168. * @author zz85 / http://www.lab4games.net/zz85/blog
  16169. * @author alteredq / http://alteredqualia.com/
  16170. *
  16171. * For Text operations in three.js (See TextGeometry)
  16172. *
  16173. * It uses techniques used in:
  16174. *
  16175. * typeface.js and canvastext
  16176. * For converting fonts and rendering with javascript
  16177. * http://typeface.neocracy.org
  16178. *
  16179. * Triangulation ported from AS3
  16180. * Simple Polygon Triangulation
  16181. * http://actionsnippet.com/?p=1462
  16182. *
  16183. * A Method to triangulate shapes with holes
  16184. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16185. *
  16186. */
  16187. THREE.FontUtils = {
  16188. faces : {},
  16189. // Just for now. face[weight][style]
  16190. face : "helvetiker",
  16191. weight: "normal",
  16192. style : "normal",
  16193. size : 150,
  16194. divisions : 10,
  16195. getFace : function() {
  16196. return this.faces[ this.face ][ this.weight ][ this.style ];
  16197. },
  16198. loadFace : function( data ) {
  16199. var family = data.familyName.toLowerCase();
  16200. var ThreeFont = this;
  16201. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16202. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16203. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16204. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16205. return data;
  16206. },
  16207. drawText : function( text ) {
  16208. var characterPts = [], allPts = [];
  16209. // RenderText
  16210. var i, p,
  16211. face = this.getFace(),
  16212. scale = this.size / face.resolution,
  16213. offset = 0,
  16214. chars = String( text ).split( '' ),
  16215. length = chars.length;
  16216. var fontPaths = [];
  16217. for ( i = 0; i < length; i ++ ) {
  16218. var path = new THREE.Path();
  16219. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16220. offset += ret.offset;
  16221. fontPaths.push( ret.path );
  16222. }
  16223. // get the width
  16224. var width = offset / 2;
  16225. //
  16226. // for ( p = 0; p < allPts.length; p++ ) {
  16227. //
  16228. // allPts[ p ].x -= width;
  16229. //
  16230. // }
  16231. //var extract = this.extractPoints( allPts, characterPts );
  16232. //extract.contour = allPts;
  16233. //extract.paths = fontPaths;
  16234. //extract.offset = width;
  16235. return { paths : fontPaths, offset : width };
  16236. },
  16237. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16238. var pts = [];
  16239. var i, i2, divisions,
  16240. outline, action, length,
  16241. scaleX, scaleY,
  16242. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16243. laste,
  16244. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16245. if ( !glyph ) return;
  16246. if ( glyph.o ) {
  16247. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16248. length = outline.length;
  16249. scaleX = scale;
  16250. scaleY = scale;
  16251. for ( i = 0; i < length; ) {
  16252. action = outline[ i ++ ];
  16253. //console.log( action );
  16254. switch( action ) {
  16255. case 'm':
  16256. // Move To
  16257. x = outline[ i++ ] * scaleX + offset;
  16258. y = outline[ i++ ] * scaleY;
  16259. path.moveTo( x, y );
  16260. break;
  16261. case 'l':
  16262. // Line To
  16263. x = outline[ i++ ] * scaleX + offset;
  16264. y = outline[ i++ ] * scaleY;
  16265. path.lineTo(x,y);
  16266. break;
  16267. case 'q':
  16268. // QuadraticCurveTo
  16269. cpx = outline[ i++ ] * scaleX + offset;
  16270. cpy = outline[ i++ ] * scaleY;
  16271. cpx1 = outline[ i++ ] * scaleX + offset;
  16272. cpy1 = outline[ i++ ] * scaleY;
  16273. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16274. laste = pts[ pts.length - 1 ];
  16275. if ( laste ) {
  16276. cpx0 = laste.x;
  16277. cpy0 = laste.y;
  16278. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16279. var t = i2 / divisions;
  16280. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16281. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16282. }
  16283. }
  16284. break;
  16285. case 'b':
  16286. // Cubic Bezier Curve
  16287. cpx = outline[ i++ ] * scaleX + offset;
  16288. cpy = outline[ i++ ] * scaleY;
  16289. cpx1 = outline[ i++ ] * scaleX + offset;
  16290. cpy1 = outline[ i++ ] * -scaleY;
  16291. cpx2 = outline[ i++ ] * scaleX + offset;
  16292. cpy2 = outline[ i++ ] * -scaleY;
  16293. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16294. laste = pts[ pts.length - 1 ];
  16295. if ( laste ) {
  16296. cpx0 = laste.x;
  16297. cpy0 = laste.y;
  16298. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16299. var t = i2 / divisions;
  16300. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16301. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16302. }
  16303. }
  16304. break;
  16305. }
  16306. }
  16307. }
  16308. return { offset: glyph.ha*scale, path:path};
  16309. }
  16310. };
  16311. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16312. // Parameters
  16313. parameters = parameters || {};
  16314. var size = parameters.size !== undefined ? parameters.size : 100;
  16315. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16316. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16317. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16318. var style = parameters.style !== undefined ? parameters.style : "normal";
  16319. THREE.FontUtils.size = size;
  16320. THREE.FontUtils.divisions = curveSegments;
  16321. THREE.FontUtils.face = font;
  16322. THREE.FontUtils.weight = weight;
  16323. THREE.FontUtils.style = style;
  16324. // Get a Font data json object
  16325. var data = THREE.FontUtils.drawText( text );
  16326. var paths = data.paths;
  16327. var shapes = [];
  16328. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16329. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16330. }
  16331. return shapes;
  16332. };
  16333. /**
  16334. * This code is a quick port of code written in C++ which was submitted to
  16335. * flipcode.com by John W. Ratcliff // July 22, 2000
  16336. * See original code and more information here:
  16337. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16338. *
  16339. * ported to actionscript by Zevan Rosser
  16340. * www.actionsnippet.com
  16341. *
  16342. * ported to javascript by Joshua Koo
  16343. * http://www.lab4games.net/zz85/blog
  16344. *
  16345. */
  16346. ( function( namespace ) {
  16347. var EPSILON = 0.0000000001;
  16348. // takes in an contour array and returns
  16349. var process = function( contour, indices ) {
  16350. var n = contour.length;
  16351. if ( n < 3 ) return null;
  16352. var result = [],
  16353. verts = [],
  16354. vertIndices = [];
  16355. /* we want a counter-clockwise polygon in verts */
  16356. var u, v, w;
  16357. if ( area( contour ) > 0.0 ) {
  16358. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16359. } else {
  16360. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16361. }
  16362. var nv = n;
  16363. /* remove nv - 2 vertices, creating 1 triangle every time */
  16364. var count = 2 * nv; /* error detection */
  16365. for( v = nv - 1; nv > 2; ) {
  16366. /* if we loop, it is probably a non-simple polygon */
  16367. if ( ( count-- ) <= 0 ) {
  16368. //** Triangulate: ERROR - probable bad polygon!
  16369. //throw ( "Warning, unable to triangulate polygon!" );
  16370. //return null;
  16371. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16372. console.log( "Warning, unable to triangulate polygon!" );
  16373. if ( indices ) return vertIndices;
  16374. return result;
  16375. }
  16376. /* three consecutive vertices in current polygon, <u,v,w> */
  16377. u = v; if ( nv <= u ) u = 0; /* previous */
  16378. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16379. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16380. if ( snip( contour, u, v, w, nv, verts ) ) {
  16381. var a, b, c, s, t;
  16382. /* true names of the vertices */
  16383. a = verts[ u ];
  16384. b = verts[ v ];
  16385. c = verts[ w ];
  16386. /* output Triangle */
  16387. result.push( [ contour[ a ],
  16388. contour[ b ],
  16389. contour[ c ] ] );
  16390. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16391. /* remove v from the remaining polygon */
  16392. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16393. verts[ s ] = verts[ t ];
  16394. }
  16395. nv--;
  16396. /* reset error detection counter */
  16397. count = 2 * nv;
  16398. }
  16399. }
  16400. if ( indices ) return vertIndices;
  16401. return result;
  16402. };
  16403. // calculate area of the contour polygon
  16404. var area = function ( contour ) {
  16405. var n = contour.length;
  16406. var a = 0.0;
  16407. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16408. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16409. }
  16410. return a * 0.5;
  16411. };
  16412. var snip = function ( contour, u, v, w, n, verts ) {
  16413. var p;
  16414. var ax, ay, bx, by;
  16415. var cx, cy, px, py;
  16416. ax = contour[ verts[ u ] ].x;
  16417. ay = contour[ verts[ u ] ].y;
  16418. bx = contour[ verts[ v ] ].x;
  16419. by = contour[ verts[ v ] ].y;
  16420. cx = contour[ verts[ w ] ].x;
  16421. cy = contour[ verts[ w ] ].y;
  16422. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16423. var aX, aY, bX, bY, cX, cY;
  16424. var apx, apy, bpx, bpy, cpx, cpy;
  16425. var cCROSSap, bCROSScp, aCROSSbp;
  16426. aX = cx - bx; aY = cy - by;
  16427. bX = ax - cx; bY = ay - cy;
  16428. cX = bx - ax; cY = by - ay;
  16429. for ( p = 0; p < n; p++ ) {
  16430. if( (p === u) || (p === v) || (p === w) ) continue;
  16431. px = contour[ verts[ p ] ].x
  16432. py = contour[ verts[ p ] ].y
  16433. apx = px - ax; apy = py - ay;
  16434. bpx = px - bx; bpy = py - by;
  16435. cpx = px - cx; cpy = py - cy;
  16436. // see if p is inside triangle abc
  16437. aCROSSbp = aX*bpy - aY*bpx;
  16438. cCROSSap = cX*apy - cY*apx;
  16439. bCROSScp = bX*cpy - bY*cpx;
  16440. if ( (aCROSSbp >= -EPSILON) && (bCROSScp >= -EPSILON) && (cCROSSap >= -EPSILON) ) return false;
  16441. }
  16442. return true;
  16443. };
  16444. namespace.Triangulate = process;
  16445. namespace.Triangulate.area = area;
  16446. return namespace;
  16447. })(THREE.FontUtils);
  16448. // To use the typeface.js face files, hook up the API
  16449. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16450. THREE.typeface_js = self._typeface_js;
  16451. /**
  16452. * @author zz85 / http://www.lab4games.net/zz85/blog
  16453. * Extensible curve object
  16454. *
  16455. * Some common of Curve methods
  16456. * .getPoint(t), getTangent(t)
  16457. * .getPointAt(u), getTagentAt(u)
  16458. * .getPoints(), .getSpacedPoints()
  16459. * .getLength()
  16460. * .updateArcLengths()
  16461. *
  16462. * This following classes subclasses THREE.Curve:
  16463. *
  16464. * -- 2d classes --
  16465. * THREE.LineCurve
  16466. * THREE.QuadraticBezierCurve
  16467. * THREE.CubicBezierCurve
  16468. * THREE.SplineCurve
  16469. * THREE.ArcCurve
  16470. * THREE.EllipseCurve
  16471. *
  16472. * -- 3d classes --
  16473. * THREE.LineCurve3
  16474. * THREE.QuadraticBezierCurve3
  16475. * THREE.CubicBezierCurve3
  16476. * THREE.SplineCurve3
  16477. * THREE.ClosedSplineCurve3
  16478. *
  16479. * A series of curves can be represented as a THREE.CurvePath
  16480. *
  16481. **/
  16482. /**************************************************************
  16483. * Abstract Curve base class
  16484. **************************************************************/
  16485. THREE.Curve = function () {
  16486. };
  16487. // Virtual base class method to overwrite and implement in subclasses
  16488. // - t [0 .. 1]
  16489. THREE.Curve.prototype.getPoint = function ( t ) {
  16490. console.log( "Warning, getPoint() not implemented!" );
  16491. return null;
  16492. };
  16493. // Get point at relative position in curve according to arc length
  16494. // - u [0 .. 1]
  16495. THREE.Curve.prototype.getPointAt = function ( u ) {
  16496. var t = this.getUtoTmapping( u );
  16497. return this.getPoint( t );
  16498. };
  16499. // Get sequence of points using getPoint( t )
  16500. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16501. if ( !divisions ) divisions = 5;
  16502. var d, pts = [];
  16503. for ( d = 0; d <= divisions; d ++ ) {
  16504. pts.push( this.getPoint( d / divisions ) );
  16505. }
  16506. return pts;
  16507. };
  16508. // Get sequence of points using getPointAt( u )
  16509. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16510. if ( !divisions ) divisions = 5;
  16511. var d, pts = [];
  16512. for ( d = 0; d <= divisions; d ++ ) {
  16513. pts.push( this.getPointAt( d / divisions ) );
  16514. }
  16515. return pts;
  16516. };
  16517. // Get total curve arc length
  16518. THREE.Curve.prototype.getLength = function () {
  16519. var lengths = this.getLengths();
  16520. return lengths[ lengths.length - 1 ];
  16521. };
  16522. // Get list of cumulative segment lengths
  16523. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16524. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16525. if ( this.cacheArcLengths
  16526. && ( this.cacheArcLengths.length == divisions + 1 )
  16527. && !this.needsUpdate) {
  16528. //console.log( "cached", this.cacheArcLengths );
  16529. return this.cacheArcLengths;
  16530. }
  16531. this.needsUpdate = false;
  16532. var cache = [];
  16533. var current, last = this.getPoint( 0 );
  16534. var p, sum = 0;
  16535. cache.push( 0 );
  16536. for ( p = 1; p <= divisions; p ++ ) {
  16537. current = this.getPoint ( p / divisions );
  16538. sum += current.distanceTo( last );
  16539. cache.push( sum );
  16540. last = current;
  16541. }
  16542. this.cacheArcLengths = cache;
  16543. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16544. };
  16545. THREE.Curve.prototype.updateArcLengths = function() {
  16546. this.needsUpdate = true;
  16547. this.getLengths();
  16548. };
  16549. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16550. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16551. var arcLengths = this.getLengths();
  16552. var i = 0, il = arcLengths.length;
  16553. var targetArcLength; // The targeted u distance value to get
  16554. if ( distance ) {
  16555. targetArcLength = distance;
  16556. } else {
  16557. targetArcLength = u * arcLengths[ il - 1 ];
  16558. }
  16559. //var time = Date.now();
  16560. // binary search for the index with largest value smaller than target u distance
  16561. var low = 0, high = il - 1, comparison;
  16562. while ( low <= high ) {
  16563. 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
  16564. comparison = arcLengths[ i ] - targetArcLength;
  16565. if ( comparison < 0 ) {
  16566. low = i + 1;
  16567. continue;
  16568. } else if ( comparison > 0 ) {
  16569. high = i - 1;
  16570. continue;
  16571. } else {
  16572. high = i;
  16573. break;
  16574. // DONE
  16575. }
  16576. }
  16577. i = high;
  16578. //console.log('b' , i, low, high, Date.now()- time);
  16579. if ( arcLengths[ i ] == targetArcLength ) {
  16580. var t = i / ( il - 1 );
  16581. return t;
  16582. }
  16583. // we could get finer grain at lengths, or use simple interpolatation between two points
  16584. var lengthBefore = arcLengths[ i ];
  16585. var lengthAfter = arcLengths[ i + 1 ];
  16586. var segmentLength = lengthAfter - lengthBefore;
  16587. // determine where we are between the 'before' and 'after' points
  16588. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16589. // add that fractional amount to t
  16590. var t = ( i + segmentFraction ) / ( il -1 );
  16591. return t;
  16592. };
  16593. // Returns a unit vector tangent at t
  16594. // In case any sub curve does not implement its tangent derivation,
  16595. // 2 points a small delta apart will be used to find its gradient
  16596. // which seems to give a reasonable approximation
  16597. THREE.Curve.prototype.getTangent = function( t ) {
  16598. var delta = 0.0001;
  16599. var t1 = t - delta;
  16600. var t2 = t + delta;
  16601. // Capping in case of danger
  16602. if ( t1 < 0 ) t1 = 0;
  16603. if ( t2 > 1 ) t2 = 1;
  16604. var pt1 = this.getPoint( t1 );
  16605. var pt2 = this.getPoint( t2 );
  16606. var vec = pt2.clone().sub(pt1);
  16607. return vec.normalize();
  16608. };
  16609. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16610. var t = this.getUtoTmapping( u );
  16611. return this.getTangent( t );
  16612. };
  16613. /**************************************************************
  16614. * Utils
  16615. **************************************************************/
  16616. THREE.Curve.Utils = {
  16617. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16618. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16619. },
  16620. // Puay Bing, thanks for helping with this derivative!
  16621. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16622. return -3 * p0 * (1 - t) * (1 - t) +
  16623. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16624. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16625. 3 * t * t * p3;
  16626. },
  16627. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16628. // To check if my formulas are correct
  16629. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16630. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16631. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16632. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16633. return h00 + h10 + h01 + h11;
  16634. },
  16635. // Catmull-Rom
  16636. interpolate: function( p0, p1, p2, p3, t ) {
  16637. var v0 = ( p2 - p0 ) * 0.5;
  16638. var v1 = ( p3 - p1 ) * 0.5;
  16639. var t2 = t * t;
  16640. var t3 = t * t2;
  16641. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16642. }
  16643. };
  16644. // TODO: Transformation for Curves?
  16645. /**************************************************************
  16646. * 3D Curves
  16647. **************************************************************/
  16648. // A Factory method for creating new curve subclasses
  16649. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16650. constructor.prototype = Object.create( THREE.Curve.prototype );
  16651. constructor.prototype.getPoint = getPointFunc;
  16652. return constructor;
  16653. };
  16654. /**
  16655. * @author zz85 / http://www.lab4games.net/zz85/blog
  16656. *
  16657. **/
  16658. /**************************************************************
  16659. * Curved Path - a curve path is simply a array of connected
  16660. * curves, but retains the api of a curve
  16661. **************************************************************/
  16662. THREE.CurvePath = function () {
  16663. this.curves = [];
  16664. this.bends = [];
  16665. this.autoClose = false; // Automatically closes the path
  16666. };
  16667. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16668. THREE.CurvePath.prototype.add = function ( curve ) {
  16669. this.curves.push( curve );
  16670. };
  16671. THREE.CurvePath.prototype.checkConnection = function() {
  16672. // TODO
  16673. // If the ending of curve is not connected to the starting
  16674. // or the next curve, then, this is not a real path
  16675. };
  16676. THREE.CurvePath.prototype.closePath = function() {
  16677. // TODO Test
  16678. // and verify for vector3 (needs to implement equals)
  16679. // Add a line curve if start and end of lines are not connected
  16680. var startPoint = this.curves[0].getPoint(0);
  16681. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16682. if (!startPoint.equals(endPoint)) {
  16683. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16684. }
  16685. };
  16686. // To get accurate point with reference to
  16687. // entire path distance at time t,
  16688. // following has to be done:
  16689. // 1. Length of each sub path have to be known
  16690. // 2. Locate and identify type of curve
  16691. // 3. Get t for the curve
  16692. // 4. Return curve.getPointAt(t')
  16693. THREE.CurvePath.prototype.getPoint = function( t ) {
  16694. var d = t * this.getLength();
  16695. var curveLengths = this.getCurveLengths();
  16696. var i = 0, diff, curve;
  16697. // To think about boundaries points.
  16698. while ( i < curveLengths.length ) {
  16699. if ( curveLengths[ i ] >= d ) {
  16700. diff = curveLengths[ i ] - d;
  16701. curve = this.curves[ i ];
  16702. var u = 1 - diff / curve.getLength();
  16703. return curve.getPointAt( u );
  16704. break;
  16705. }
  16706. i ++;
  16707. }
  16708. return null;
  16709. // loop where sum != 0, sum > d , sum+1 <d
  16710. };
  16711. /*
  16712. THREE.CurvePath.prototype.getTangent = function( t ) {
  16713. };*/
  16714. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16715. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16716. // getPoint() depends on getLength
  16717. THREE.CurvePath.prototype.getLength = function() {
  16718. var lens = this.getCurveLengths();
  16719. return lens[ lens.length - 1 ];
  16720. };
  16721. // Compute lengths and cache them
  16722. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16723. THREE.CurvePath.prototype.getCurveLengths = function() {
  16724. // We use cache values if curves and cache array are same length
  16725. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16726. return this.cacheLengths;
  16727. };
  16728. // Get length of subsurve
  16729. // Push sums into cached array
  16730. var lengths = [], sums = 0;
  16731. var i, il = this.curves.length;
  16732. for ( i = 0; i < il; i ++ ) {
  16733. sums += this.curves[ i ].getLength();
  16734. lengths.push( sums );
  16735. }
  16736. this.cacheLengths = lengths;
  16737. return lengths;
  16738. };
  16739. // Returns min and max coordinates, as well as centroid
  16740. THREE.CurvePath.prototype.getBoundingBox = function () {
  16741. var points = this.getPoints();
  16742. var maxX, maxY, maxZ;
  16743. var minX, minY, minZ;
  16744. maxX = maxY = Number.NEGATIVE_INFINITY;
  16745. minX = minY = Number.POSITIVE_INFINITY;
  16746. var p, i, il, sum;
  16747. var v3 = points[0] instanceof THREE.Vector3;
  16748. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16749. for ( i = 0, il = points.length; i < il; i ++ ) {
  16750. p = points[ i ];
  16751. if ( p.x > maxX ) maxX = p.x;
  16752. else if ( p.x < minX ) minX = p.x;
  16753. if ( p.y > maxY ) maxY = p.y;
  16754. else if ( p.y < minY ) minY = p.y;
  16755. if ( v3 ) {
  16756. if ( p.z > maxZ ) maxZ = p.z;
  16757. else if ( p.z < minZ ) minZ = p.z;
  16758. }
  16759. sum.add( p );
  16760. }
  16761. var ret = {
  16762. minX: minX,
  16763. minY: minY,
  16764. maxX: maxX,
  16765. maxY: maxY,
  16766. centroid: sum.divideScalar( il )
  16767. };
  16768. if ( v3 ) {
  16769. ret.maxZ = maxZ;
  16770. ret.minZ = minZ;
  16771. }
  16772. return ret;
  16773. };
  16774. /**************************************************************
  16775. * Create Geometries Helpers
  16776. **************************************************************/
  16777. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16778. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16779. var pts = this.getPoints( divisions, true );
  16780. return this.createGeometry( pts );
  16781. };
  16782. // Generate geometry from equidistance sampling along the path
  16783. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16784. var pts = this.getSpacedPoints( divisions, true );
  16785. return this.createGeometry( pts );
  16786. };
  16787. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16788. var geometry = new THREE.Geometry();
  16789. for ( var i = 0; i < points.length; i ++ ) {
  16790. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16791. }
  16792. return geometry;
  16793. };
  16794. /**************************************************************
  16795. * Bend / Wrap Helper Methods
  16796. **************************************************************/
  16797. // Wrap path / Bend modifiers?
  16798. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16799. this.bends.push( bendpath );
  16800. };
  16801. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16802. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16803. var i, il;
  16804. if ( !bends ) {
  16805. bends = this.bends;
  16806. }
  16807. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16808. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16809. }
  16810. return oldPts;
  16811. };
  16812. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16813. var oldPts = this.getSpacedPoints( segments );
  16814. var i, il;
  16815. if ( !bends ) {
  16816. bends = this.bends;
  16817. }
  16818. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16819. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16820. }
  16821. return oldPts;
  16822. };
  16823. // This returns getPoints() bend/wrapped around the contour of a path.
  16824. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16825. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16826. var bounds = this.getBoundingBox();
  16827. var i, il, p, oldX, oldY, xNorm;
  16828. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16829. p = oldPts[ i ];
  16830. oldX = p.x;
  16831. oldY = p.y;
  16832. xNorm = oldX / bounds.maxX;
  16833. // If using actual distance, for length > path, requires line extrusions
  16834. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16835. xNorm = path.getUtoTmapping( xNorm, oldX );
  16836. // check for out of bounds?
  16837. var pathPt = path.getPoint( xNorm );
  16838. var normal = path.getTangent( xNorm );
  16839. normal.set( -normal.y, normal.x ).multiplyScalar( oldY );
  16840. p.x = pathPt.x + normal.x;
  16841. p.y = pathPt.y + normal.y;
  16842. }
  16843. return oldPts;
  16844. };
  16845. /**
  16846. * @author alteredq / http://alteredqualia.com/
  16847. */
  16848. THREE.Gyroscope = function () {
  16849. THREE.Object3D.call( this );
  16850. };
  16851. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16852. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16853. this.matrixAutoUpdate && this.updateMatrix();
  16854. // update matrixWorld
  16855. if ( this.matrixWorldNeedsUpdate || force ) {
  16856. if ( this.parent ) {
  16857. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16858. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  16859. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  16860. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  16861. } else {
  16862. this.matrixWorld.copy( this.matrix );
  16863. }
  16864. this.matrixWorldNeedsUpdate = false;
  16865. force = true;
  16866. }
  16867. // update children
  16868. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16869. this.children[ i ].updateMatrixWorld( force );
  16870. }
  16871. };
  16872. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16873. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16874. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  16875. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  16876. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16877. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16878. /**
  16879. * @author zz85 / http://www.lab4games.net/zz85/blog
  16880. * Creates free form 2d path using series of points, lines or curves.
  16881. *
  16882. **/
  16883. THREE.Path = function ( points ) {
  16884. THREE.CurvePath.call(this);
  16885. this.actions = [];
  16886. if ( points ) {
  16887. this.fromPoints( points );
  16888. }
  16889. };
  16890. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16891. THREE.PathActions = {
  16892. MOVE_TO: 'moveTo',
  16893. LINE_TO: 'lineTo',
  16894. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16895. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16896. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16897. ARC: 'arc', // Circle
  16898. ELLIPSE: 'ellipse'
  16899. };
  16900. // TODO Clean up PATH API
  16901. // Create path using straight lines to connect all points
  16902. // - vectors: array of Vector2
  16903. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16904. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16905. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16906. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16907. };
  16908. };
  16909. // startPath() endPath()?
  16910. THREE.Path.prototype.moveTo = function ( x, y ) {
  16911. var args = Array.prototype.slice.call( arguments );
  16912. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16913. };
  16914. THREE.Path.prototype.lineTo = function ( x, y ) {
  16915. var args = Array.prototype.slice.call( arguments );
  16916. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16917. var x0 = lastargs[ lastargs.length - 2 ];
  16918. var y0 = lastargs[ lastargs.length - 1 ];
  16919. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16920. this.curves.push( curve );
  16921. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16922. };
  16923. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16924. var args = Array.prototype.slice.call( arguments );
  16925. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16926. var x0 = lastargs[ lastargs.length - 2 ];
  16927. var y0 = lastargs[ lastargs.length - 1 ];
  16928. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16929. new THREE.Vector2( aCPx, aCPy ),
  16930. new THREE.Vector2( aX, aY ) );
  16931. this.curves.push( curve );
  16932. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16933. };
  16934. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16935. aCP2x, aCP2y,
  16936. aX, aY ) {
  16937. var args = Array.prototype.slice.call( arguments );
  16938. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16939. var x0 = lastargs[ lastargs.length - 2 ];
  16940. var y0 = lastargs[ lastargs.length - 1 ];
  16941. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16942. new THREE.Vector2( aCP1x, aCP1y ),
  16943. new THREE.Vector2( aCP2x, aCP2y ),
  16944. new THREE.Vector2( aX, aY ) );
  16945. this.curves.push( curve );
  16946. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16947. };
  16948. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16949. var args = Array.prototype.slice.call( arguments );
  16950. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16951. var x0 = lastargs[ lastargs.length - 2 ];
  16952. var y0 = lastargs[ lastargs.length - 1 ];
  16953. //---
  16954. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16955. Array.prototype.push.apply( npts, pts );
  16956. var curve = new THREE.SplineCurve( npts );
  16957. this.curves.push( curve );
  16958. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16959. };
  16960. // FUTURE: Change the API or follow canvas API?
  16961. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16962. aStartAngle, aEndAngle, aClockwise ) {
  16963. var lastargs = this.actions[ this.actions.length - 1].args;
  16964. var x0 = lastargs[ lastargs.length - 2 ];
  16965. var y0 = lastargs[ lastargs.length - 1 ];
  16966. this.absarc(aX + x0, aY + y0, aRadius,
  16967. aStartAngle, aEndAngle, aClockwise );
  16968. };
  16969. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16970. aStartAngle, aEndAngle, aClockwise ) {
  16971. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16972. };
  16973. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16974. aStartAngle, aEndAngle, aClockwise ) {
  16975. var lastargs = this.actions[ this.actions.length - 1].args;
  16976. var x0 = lastargs[ lastargs.length - 2 ];
  16977. var y0 = lastargs[ lastargs.length - 1 ];
  16978. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16979. aStartAngle, aEndAngle, aClockwise );
  16980. };
  16981. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16982. aStartAngle, aEndAngle, aClockwise ) {
  16983. var args = Array.prototype.slice.call( arguments );
  16984. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16985. aStartAngle, aEndAngle, aClockwise );
  16986. this.curves.push( curve );
  16987. var lastPoint = curve.getPoint(1);
  16988. args.push(lastPoint.x);
  16989. args.push(lastPoint.y);
  16990. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16991. };
  16992. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16993. if ( ! divisions ) divisions = 40;
  16994. var points = [];
  16995. for ( var i = 0; i < divisions; i ++ ) {
  16996. points.push( this.getPoint( i / divisions ) );
  16997. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16998. }
  16999. // if ( closedPath ) {
  17000. //
  17001. // points.push( points[ 0 ] );
  17002. //
  17003. // }
  17004. return points;
  17005. };
  17006. /* Return an array of vectors based on contour of the path */
  17007. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17008. if (this.useSpacedPoints) {
  17009. console.log('tata');
  17010. return this.getSpacedPoints( divisions, closedPath );
  17011. }
  17012. divisions = divisions || 12;
  17013. var points = [];
  17014. var i, il, item, action, args;
  17015. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17016. laste, j,
  17017. t, tx, ty;
  17018. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17019. item = this.actions[ i ];
  17020. action = item.action;
  17021. args = item.args;
  17022. switch( action ) {
  17023. case THREE.PathActions.MOVE_TO:
  17024. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17025. break;
  17026. case THREE.PathActions.LINE_TO:
  17027. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17028. break;
  17029. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17030. cpx = args[ 2 ];
  17031. cpy = args[ 3 ];
  17032. cpx1 = args[ 0 ];
  17033. cpy1 = args[ 1 ];
  17034. if ( points.length > 0 ) {
  17035. laste = points[ points.length - 1 ];
  17036. cpx0 = laste.x;
  17037. cpy0 = laste.y;
  17038. } else {
  17039. laste = this.actions[ i - 1 ].args;
  17040. cpx0 = laste[ laste.length - 2 ];
  17041. cpy0 = laste[ laste.length - 1 ];
  17042. }
  17043. for ( j = 1; j <= divisions; j ++ ) {
  17044. t = j / divisions;
  17045. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17046. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17047. points.push( new THREE.Vector2( tx, ty ) );
  17048. }
  17049. break;
  17050. case THREE.PathActions.BEZIER_CURVE_TO:
  17051. cpx = args[ 4 ];
  17052. cpy = args[ 5 ];
  17053. cpx1 = args[ 0 ];
  17054. cpy1 = args[ 1 ];
  17055. cpx2 = args[ 2 ];
  17056. cpy2 = args[ 3 ];
  17057. if ( points.length > 0 ) {
  17058. laste = points[ points.length - 1 ];
  17059. cpx0 = laste.x;
  17060. cpy0 = laste.y;
  17061. } else {
  17062. laste = this.actions[ i - 1 ].args;
  17063. cpx0 = laste[ laste.length - 2 ];
  17064. cpy0 = laste[ laste.length - 1 ];
  17065. }
  17066. for ( j = 1; j <= divisions; j ++ ) {
  17067. t = j / divisions;
  17068. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17069. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17070. points.push( new THREE.Vector2( tx, ty ) );
  17071. }
  17072. break;
  17073. case THREE.PathActions.CSPLINE_THRU:
  17074. laste = this.actions[ i - 1 ].args;
  17075. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17076. var spts = [ last ];
  17077. var n = divisions * args[ 0 ].length;
  17078. spts = spts.concat( args[ 0 ] );
  17079. var spline = new THREE.SplineCurve( spts );
  17080. for ( j = 1; j <= n; j ++ ) {
  17081. points.push( spline.getPointAt( j / n ) ) ;
  17082. }
  17083. break;
  17084. case THREE.PathActions.ARC:
  17085. var aX = args[ 0 ], aY = args[ 1 ],
  17086. aRadius = args[ 2 ],
  17087. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17088. aClockwise = !!args[ 5 ];
  17089. var deltaAngle = aEndAngle - aStartAngle;
  17090. var angle;
  17091. var tdivisions = divisions * 2;
  17092. for ( j = 1; j <= tdivisions; j ++ ) {
  17093. t = j / tdivisions;
  17094. if ( ! aClockwise ) {
  17095. t = 1 - t;
  17096. }
  17097. angle = aStartAngle + t * deltaAngle;
  17098. tx = aX + aRadius * Math.cos( angle );
  17099. ty = aY + aRadius * Math.sin( angle );
  17100. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17101. points.push( new THREE.Vector2( tx, ty ) );
  17102. }
  17103. //console.log(points);
  17104. break;
  17105. case THREE.PathActions.ELLIPSE:
  17106. var aX = args[ 0 ], aY = args[ 1 ],
  17107. xRadius = args[ 2 ],
  17108. yRadius = args[ 3 ],
  17109. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17110. aClockwise = !!args[ 6 ];
  17111. var deltaAngle = aEndAngle - aStartAngle;
  17112. var angle;
  17113. var tdivisions = divisions * 2;
  17114. for ( j = 1; j <= tdivisions; j ++ ) {
  17115. t = j / tdivisions;
  17116. if ( ! aClockwise ) {
  17117. t = 1 - t;
  17118. }
  17119. angle = aStartAngle + t * deltaAngle;
  17120. tx = aX + xRadius * Math.cos( angle );
  17121. ty = aY + yRadius * Math.sin( angle );
  17122. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17123. points.push( new THREE.Vector2( tx, ty ) );
  17124. }
  17125. //console.log(points);
  17126. break;
  17127. } // end switch
  17128. }
  17129. // Normalize to remove the closing point by default.
  17130. var lastPoint = points[ points.length - 1];
  17131. var EPSILON = 0.0000000001;
  17132. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17133. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17134. points.splice( points.length - 1, 1);
  17135. if ( closedPath ) {
  17136. points.push( points[ 0 ] );
  17137. }
  17138. return points;
  17139. };
  17140. // Breaks path into shapes
  17141. THREE.Path.prototype.toShapes = function( isCCW ) {
  17142. var i, il, item, action, args;
  17143. var subPaths = [], lastPath = new THREE.Path();
  17144. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17145. item = this.actions[ i ];
  17146. args = item.args;
  17147. action = item.action;
  17148. if ( action == THREE.PathActions.MOVE_TO ) {
  17149. if ( lastPath.actions.length != 0 ) {
  17150. subPaths.push( lastPath );
  17151. lastPath = new THREE.Path();
  17152. }
  17153. }
  17154. lastPath[ action ].apply( lastPath, args );
  17155. }
  17156. if ( lastPath.actions.length != 0 ) {
  17157. subPaths.push( lastPath );
  17158. }
  17159. // console.log(subPaths);
  17160. if ( subPaths.length == 0 ) return [];
  17161. var solid, tmpPath, tmpShape, shapes = [];
  17162. if ( subPaths.length == 1) {
  17163. tmpPath = subPaths[0];
  17164. tmpShape = new THREE.Shape();
  17165. tmpShape.actions = tmpPath.actions;
  17166. tmpShape.curves = tmpPath.curves;
  17167. shapes.push( tmpShape );
  17168. return shapes;
  17169. }
  17170. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17171. holesFirst = isCCW ? !holesFirst : holesFirst;
  17172. // console.log("Holes first", holesFirst);
  17173. if ( holesFirst ) {
  17174. tmpShape = new THREE.Shape();
  17175. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17176. tmpPath = subPaths[ i ];
  17177. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17178. solid = isCCW ? !solid : solid;
  17179. if ( solid ) {
  17180. tmpShape.actions = tmpPath.actions;
  17181. tmpShape.curves = tmpPath.curves;
  17182. shapes.push( tmpShape );
  17183. tmpShape = new THREE.Shape();
  17184. //console.log('cw', i);
  17185. } else {
  17186. tmpShape.holes.push( tmpPath );
  17187. //console.log('ccw', i);
  17188. }
  17189. }
  17190. } else {
  17191. // Shapes first
  17192. tmpShape = undefined;
  17193. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17194. tmpPath = subPaths[ i ];
  17195. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17196. solid = isCCW ? !solid : solid;
  17197. if ( solid ) {
  17198. if ( tmpShape ) shapes.push( tmpShape );
  17199. tmpShape = new THREE.Shape();
  17200. tmpShape.actions = tmpPath.actions;
  17201. tmpShape.curves = tmpPath.curves;
  17202. } else {
  17203. tmpShape.holes.push( tmpPath );
  17204. }
  17205. }
  17206. shapes.push( tmpShape );
  17207. }
  17208. //console.log("shape", shapes);
  17209. return shapes;
  17210. };
  17211. /**
  17212. * @author zz85 / http://www.lab4games.net/zz85/blog
  17213. * Defines a 2d shape plane using paths.
  17214. **/
  17215. // STEP 1 Create a path.
  17216. // STEP 2 Turn path into shape.
  17217. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17218. // STEP 3a - Extract points from each shape, turn to vertices
  17219. // STEP 3b - Triangulate each shape, add faces.
  17220. THREE.Shape = function () {
  17221. THREE.Path.apply( this, arguments );
  17222. this.holes = [];
  17223. };
  17224. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17225. // Convenience method to return ExtrudeGeometry
  17226. THREE.Shape.prototype.extrude = function ( options ) {
  17227. var extruded = new THREE.ExtrudeGeometry( this, options );
  17228. return extruded;
  17229. };
  17230. // Convenience method to return ShapeGeometry
  17231. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17232. var geometry = new THREE.ShapeGeometry( this, options );
  17233. return geometry;
  17234. };
  17235. // Get points of holes
  17236. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17237. var i, il = this.holes.length, holesPts = [];
  17238. for ( i = 0; i < il; i ++ ) {
  17239. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17240. }
  17241. return holesPts;
  17242. };
  17243. // Get points of holes (spaced by regular distance)
  17244. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17245. var i, il = this.holes.length, holesPts = [];
  17246. for ( i = 0; i < il; i ++ ) {
  17247. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17248. }
  17249. return holesPts;
  17250. };
  17251. // Get points of shape and holes (keypoints based on segments parameter)
  17252. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17253. return {
  17254. shape: this.getTransformedPoints( divisions ),
  17255. holes: this.getPointsHoles( divisions )
  17256. };
  17257. };
  17258. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17259. if (this.useSpacedPoints) {
  17260. return this.extractAllSpacedPoints(divisions);
  17261. }
  17262. return this.extractAllPoints(divisions);
  17263. };
  17264. //
  17265. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17266. //
  17267. // return {
  17268. //
  17269. // shape: this.transform( bend, divisions ),
  17270. // holes: this.getPointsHoles( divisions, bend )
  17271. //
  17272. // };
  17273. //
  17274. // };
  17275. // Get points of shape and holes (spaced by regular distance)
  17276. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17277. return {
  17278. shape: this.getTransformedSpacedPoints( divisions ),
  17279. holes: this.getSpacedPointsHoles( divisions )
  17280. };
  17281. };
  17282. /**************************************************************
  17283. * Utils
  17284. **************************************************************/
  17285. THREE.Shape.Utils = {
  17286. /*
  17287. contour - array of vector2 for contour
  17288. holes - array of array of vector2
  17289. */
  17290. removeHoles: function ( contour, holes ) {
  17291. var shape = contour.concat(); // work on this shape
  17292. var allpoints = shape.concat();
  17293. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17294. var prevShapeVert, nextShapeVert,
  17295. prevHoleVert, nextHoleVert,
  17296. holeIndex, shapeIndex,
  17297. shapeId, shapeGroup,
  17298. h, h2,
  17299. hole, shortest, d,
  17300. p, pts1, pts2,
  17301. tmpShape1, tmpShape2,
  17302. tmpHole1, tmpHole2,
  17303. verts = [];
  17304. for ( h = 0; h < holes.length; h ++ ) {
  17305. hole = holes[ h ];
  17306. /*
  17307. shapeholes[ h ].concat(); // preserves original
  17308. holes.push( hole );
  17309. */
  17310. Array.prototype.push.apply( allpoints, hole );
  17311. shortest = Number.POSITIVE_INFINITY;
  17312. // Find the shortest pair of pts between shape and hole
  17313. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17314. // Using distanceToSquared() intead of distanceTo() should speed a little
  17315. // since running square roots operations are reduced.
  17316. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17317. pts1 = hole[ h2 ];
  17318. var dist = [];
  17319. for ( p = 0; p < shape.length; p++ ) {
  17320. pts2 = shape[ p ];
  17321. d = pts1.distanceToSquared( pts2 );
  17322. dist.push( d );
  17323. if ( d < shortest ) {
  17324. shortest = d;
  17325. holeIndex = h2;
  17326. shapeIndex = p;
  17327. }
  17328. }
  17329. }
  17330. //console.log("shortest", shortest, dist);
  17331. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17332. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17333. var areaapts = [
  17334. hole[ holeIndex ],
  17335. shape[ shapeIndex ],
  17336. shape[ prevShapeVert ]
  17337. ];
  17338. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17339. var areabpts = [
  17340. hole[ holeIndex ],
  17341. hole[ prevHoleVert ],
  17342. shape[ shapeIndex ]
  17343. ];
  17344. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17345. var shapeOffset = 1;
  17346. var holeOffset = -1;
  17347. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17348. shapeIndex += shapeOffset;
  17349. holeIndex += holeOffset;
  17350. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17351. shapeIndex %= shape.length;
  17352. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17353. holeIndex %= hole.length;
  17354. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17355. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17356. areaapts = [
  17357. hole[ holeIndex ],
  17358. shape[ shapeIndex ],
  17359. shape[ prevShapeVert ]
  17360. ];
  17361. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17362. areabpts = [
  17363. hole[ holeIndex ],
  17364. hole[ prevHoleVert ],
  17365. shape[ shapeIndex ]
  17366. ];
  17367. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17368. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17369. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17370. // In case areas are not correct.
  17371. //console.log("USE THIS");
  17372. shapeIndex = oldShapeIndex;
  17373. holeIndex = oldHoleIndex ;
  17374. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17375. shapeIndex %= shape.length;
  17376. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17377. holeIndex %= hole.length;
  17378. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17379. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17380. } else {
  17381. //console.log("USE THAT ")
  17382. }
  17383. tmpShape1 = shape.slice( 0, shapeIndex );
  17384. tmpShape2 = shape.slice( shapeIndex );
  17385. tmpHole1 = hole.slice( holeIndex );
  17386. tmpHole2 = hole.slice( 0, holeIndex );
  17387. // Should check orders here again?
  17388. var trianglea = [
  17389. hole[ holeIndex ],
  17390. shape[ shapeIndex ],
  17391. shape[ prevShapeVert ]
  17392. ];
  17393. var triangleb = [
  17394. hole[ holeIndex ] ,
  17395. hole[ prevHoleVert ],
  17396. shape[ shapeIndex ]
  17397. ];
  17398. verts.push( trianglea );
  17399. verts.push( triangleb );
  17400. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17401. }
  17402. return {
  17403. shape:shape, /* shape with no holes */
  17404. isolatedPts: verts, /* isolated faces */
  17405. allpoints: allpoints
  17406. }
  17407. },
  17408. triangulateShape: function ( contour, holes ) {
  17409. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17410. var shape = shapeWithoutHoles.shape,
  17411. allpoints = shapeWithoutHoles.allpoints,
  17412. isolatedPts = shapeWithoutHoles.isolatedPts;
  17413. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17414. // 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.
  17415. //console.log( "triangles",triangles, triangles.length );
  17416. //console.log( "allpoints",allpoints, allpoints.length );
  17417. var i, il, f, face,
  17418. key, index,
  17419. allPointsMap = {},
  17420. isolatedPointsMap = {};
  17421. // prepare all points map
  17422. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17423. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17424. if ( allPointsMap[ key ] !== undefined ) {
  17425. console.log( "Duplicate point", key );
  17426. }
  17427. allPointsMap[ key ] = i;
  17428. }
  17429. // check all face vertices against all points map
  17430. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17431. face = triangles[ i ];
  17432. for ( f = 0; f < 3; f ++ ) {
  17433. key = face[ f ].x + ":" + face[ f ].y;
  17434. index = allPointsMap[ key ];
  17435. if ( index !== undefined ) {
  17436. face[ f ] = index;
  17437. }
  17438. }
  17439. }
  17440. // check isolated points vertices against all points map
  17441. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17442. face = isolatedPts[ i ];
  17443. for ( f = 0; f < 3; f ++ ) {
  17444. key = face[ f ].x + ":" + face[ f ].y;
  17445. index = allPointsMap[ key ];
  17446. if ( index !== undefined ) {
  17447. face[ f ] = index;
  17448. }
  17449. }
  17450. }
  17451. return triangles.concat( isolatedPts );
  17452. }, // end triangulate shapes
  17453. /*
  17454. triangulate2 : function( pts, holes ) {
  17455. // For use with Poly2Tri.js
  17456. var allpts = pts.concat();
  17457. var shape = [];
  17458. for (var p in pts) {
  17459. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17460. }
  17461. var swctx = new js.poly2tri.SweepContext(shape);
  17462. for (var h in holes) {
  17463. var aHole = holes[h];
  17464. var newHole = []
  17465. for (i in aHole) {
  17466. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17467. allpts.push(aHole[i]);
  17468. }
  17469. swctx.AddHole(newHole);
  17470. }
  17471. var find;
  17472. var findIndexForPt = function (pt) {
  17473. find = new THREE.Vector2(pt.x, pt.y);
  17474. var p;
  17475. for (p=0, pl = allpts.length; p<pl; p++) {
  17476. if (allpts[p].equals(find)) return p;
  17477. }
  17478. return -1;
  17479. };
  17480. // triangulate
  17481. js.poly2tri.sweep.Triangulate(swctx);
  17482. var triangles = swctx.GetTriangles();
  17483. var tr ;
  17484. var facesPts = [];
  17485. for (var t in triangles) {
  17486. tr = triangles[t];
  17487. facesPts.push([
  17488. findIndexForPt(tr.GetPoint(0)),
  17489. findIndexForPt(tr.GetPoint(1)),
  17490. findIndexForPt(tr.GetPoint(2))
  17491. ]);
  17492. }
  17493. // console.log(facesPts);
  17494. // console.log("triangles", triangles.length, triangles);
  17495. // Returns array of faces with 3 element each
  17496. return facesPts;
  17497. },
  17498. */
  17499. isClockWise: function ( pts ) {
  17500. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17501. },
  17502. // Bezier Curves formulas obtained from
  17503. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17504. // Quad Bezier Functions
  17505. b2p0: function ( t, p ) {
  17506. var k = 1 - t;
  17507. return k * k * p;
  17508. },
  17509. b2p1: function ( t, p ) {
  17510. return 2 * ( 1 - t ) * t * p;
  17511. },
  17512. b2p2: function ( t, p ) {
  17513. return t * t * p;
  17514. },
  17515. b2: function ( t, p0, p1, p2 ) {
  17516. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17517. },
  17518. // Cubic Bezier Functions
  17519. b3p0: function ( t, p ) {
  17520. var k = 1 - t;
  17521. return k * k * k * p;
  17522. },
  17523. b3p1: function ( t, p ) {
  17524. var k = 1 - t;
  17525. return 3 * k * k * t * p;
  17526. },
  17527. b3p2: function ( t, p ) {
  17528. var k = 1 - t;
  17529. return 3 * k * t * t * p;
  17530. },
  17531. b3p3: function ( t, p ) {
  17532. return t * t * t * p;
  17533. },
  17534. b3: function ( t, p0, p1, p2, p3 ) {
  17535. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17536. }
  17537. };
  17538. /**************************************************************
  17539. * Line
  17540. **************************************************************/
  17541. THREE.LineCurve = function ( v1, v2 ) {
  17542. this.v1 = v1;
  17543. this.v2 = v2;
  17544. };
  17545. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17546. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17547. var point = this.v2.clone().sub(this.v1);
  17548. point.multiplyScalar( t ).add( this.v1 );
  17549. return point;
  17550. };
  17551. // Line curve is linear, so we can overwrite default getPointAt
  17552. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17553. return this.getPoint( u );
  17554. };
  17555. THREE.LineCurve.prototype.getTangent = function( t ) {
  17556. var tangent = this.v2.clone().sub(this.v1);
  17557. return tangent.normalize();
  17558. };
  17559. /**************************************************************
  17560. * Quadratic Bezier curve
  17561. **************************************************************/
  17562. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17563. this.v0 = v0;
  17564. this.v1 = v1;
  17565. this.v2 = v2;
  17566. };
  17567. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17568. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17569. var tx, ty;
  17570. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17571. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17572. return new THREE.Vector2( tx, ty );
  17573. };
  17574. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17575. var tx, ty;
  17576. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17577. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17578. // returns unit vector
  17579. var tangent = new THREE.Vector2( tx, ty );
  17580. tangent.normalize();
  17581. return tangent;
  17582. };
  17583. /**************************************************************
  17584. * Cubic Bezier curve
  17585. **************************************************************/
  17586. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17587. this.v0 = v0;
  17588. this.v1 = v1;
  17589. this.v2 = v2;
  17590. this.v3 = v3;
  17591. };
  17592. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17593. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  17594. var tx, ty;
  17595. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17596. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17597. return new THREE.Vector2( tx, ty );
  17598. };
  17599. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  17600. var tx, ty;
  17601. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17602. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17603. var tangent = new THREE.Vector2( tx, ty );
  17604. tangent.normalize();
  17605. return tangent;
  17606. };
  17607. /**************************************************************
  17608. * Spline curve
  17609. **************************************************************/
  17610. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  17611. this.points = (points == undefined) ? [] : points;
  17612. };
  17613. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  17614. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  17615. var v = new THREE.Vector2();
  17616. var c = [];
  17617. var points = this.points, point, intPoint, weight;
  17618. point = ( points.length - 1 ) * t;
  17619. intPoint = Math.floor( point );
  17620. weight = point - intPoint;
  17621. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17622. c[ 1 ] = intPoint;
  17623. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  17624. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  17625. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17626. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17627. return v;
  17628. };
  17629. /**************************************************************
  17630. * Ellipse curve
  17631. **************************************************************/
  17632. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  17633. this.aX = aX;
  17634. this.aY = aY;
  17635. this.xRadius = xRadius;
  17636. this.yRadius = yRadius;
  17637. this.aStartAngle = aStartAngle;
  17638. this.aEndAngle = aEndAngle;
  17639. this.aClockwise = aClockwise;
  17640. };
  17641. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  17642. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  17643. var angle;
  17644. var deltaAngle = this.aEndAngle - this.aStartAngle;
  17645. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  17646. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  17647. if ( this.aClockwise === true ) {
  17648. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  17649. } else {
  17650. angle = this.aStartAngle + t * deltaAngle;
  17651. }
  17652. var tx = this.aX + this.xRadius * Math.cos( angle );
  17653. var ty = this.aY + this.yRadius * Math.sin( angle );
  17654. return new THREE.Vector2( tx, ty );
  17655. };
  17656. /**************************************************************
  17657. * Arc curve
  17658. **************************************************************/
  17659. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17660. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  17661. };
  17662. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  17663. /**************************************************************
  17664. * Line3D
  17665. **************************************************************/
  17666. THREE.LineCurve3 = THREE.Curve.create(
  17667. function ( v1, v2 ) {
  17668. this.v1 = v1;
  17669. this.v2 = v2;
  17670. },
  17671. function ( t ) {
  17672. var r = new THREE.Vector3();
  17673. r.subVectors( this.v2, this.v1 ); // diff
  17674. r.multiplyScalar( t );
  17675. r.add( this.v1 );
  17676. return r;
  17677. }
  17678. );
  17679. /**************************************************************
  17680. * Quadratic Bezier 3D curve
  17681. **************************************************************/
  17682. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  17683. function ( v0, v1, v2 ) {
  17684. this.v0 = v0;
  17685. this.v1 = v1;
  17686. this.v2 = v2;
  17687. },
  17688. function ( t ) {
  17689. var tx, ty, tz;
  17690. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17691. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17692. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  17693. return new THREE.Vector3( tx, ty, tz );
  17694. }
  17695. );
  17696. /**************************************************************
  17697. * Cubic Bezier 3D curve
  17698. **************************************************************/
  17699. THREE.CubicBezierCurve3 = THREE.Curve.create(
  17700. function ( v0, v1, v2, v3 ) {
  17701. this.v0 = v0;
  17702. this.v1 = v1;
  17703. this.v2 = v2;
  17704. this.v3 = v3;
  17705. },
  17706. function ( t ) {
  17707. var tx, ty, tz;
  17708. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17709. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17710. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  17711. return new THREE.Vector3( tx, ty, tz );
  17712. }
  17713. );
  17714. /**************************************************************
  17715. * Spline 3D curve
  17716. **************************************************************/
  17717. THREE.SplineCurve3 = THREE.Curve.create(
  17718. function ( points /* array of Vector3 */) {
  17719. this.points = (points == undefined) ? [] : points;
  17720. },
  17721. function ( t ) {
  17722. var v = new THREE.Vector3();
  17723. var c = [];
  17724. var points = this.points, point, intPoint, weight;
  17725. point = ( points.length - 1 ) * t;
  17726. intPoint = Math.floor( point );
  17727. weight = point - intPoint;
  17728. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17729. c[ 1 ] = intPoint;
  17730. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17731. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17732. var pt0 = points[ c[0] ],
  17733. pt1 = points[ c[1] ],
  17734. pt2 = points[ c[2] ],
  17735. pt3 = points[ c[3] ];
  17736. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  17737. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  17738. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  17739. return v;
  17740. }
  17741. );
  17742. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  17743. // var v = new THREE.Vector3();
  17744. // var c = [];
  17745. // var points = this.points, point, intPoint, weight;
  17746. // point = ( points.length - 1 ) * t;
  17747. // intPoint = Math.floor( point );
  17748. // weight = point - intPoint;
  17749. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17750. // c[ 1 ] = intPoint;
  17751. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17752. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17753. // var pt0 = points[ c[0] ],
  17754. // pt1 = points[ c[1] ],
  17755. // pt2 = points[ c[2] ],
  17756. // pt3 = points[ c[3] ];
  17757. // // t = weight;
  17758. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  17759. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  17760. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  17761. // return v;
  17762. // }
  17763. /**************************************************************
  17764. * Closed Spline 3D curve
  17765. **************************************************************/
  17766. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  17767. function ( points /* array of Vector3 */) {
  17768. this.points = (points == undefined) ? [] : points;
  17769. },
  17770. function ( t ) {
  17771. var v = new THREE.Vector3();
  17772. var c = [];
  17773. var points = this.points, point, intPoint, weight;
  17774. point = ( points.length - 0 ) * t;
  17775. // This needs to be from 0-length +1
  17776. intPoint = Math.floor( point );
  17777. weight = point - intPoint;
  17778. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  17779. c[ 0 ] = ( intPoint - 1 ) % points.length;
  17780. c[ 1 ] = ( intPoint ) % points.length;
  17781. c[ 2 ] = ( intPoint + 1 ) % points.length;
  17782. c[ 3 ] = ( intPoint + 2 ) % points.length;
  17783. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17784. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17785. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  17786. return v;
  17787. }
  17788. );
  17789. /**
  17790. * @author mikael emtinger / http://gomo.se/
  17791. */
  17792. THREE.AnimationHandler = (function() {
  17793. var playing = [];
  17794. var library = {};
  17795. var that = {};
  17796. //--- update ---
  17797. that.update = function( deltaTimeMS ) {
  17798. for( var i = 0; i < playing.length; i ++ )
  17799. playing[ i ].update( deltaTimeMS );
  17800. };
  17801. //--- add ---
  17802. that.addToUpdate = function( animation ) {
  17803. if ( playing.indexOf( animation ) === -1 )
  17804. playing.push( animation );
  17805. };
  17806. //--- remove ---
  17807. that.removeFromUpdate = function( animation ) {
  17808. var index = playing.indexOf( animation );
  17809. if( index !== -1 )
  17810. playing.splice( index, 1 );
  17811. };
  17812. //--- add ---
  17813. that.add = function( data ) {
  17814. if ( library[ data.name ] !== undefined )
  17815. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17816. library[ data.name ] = data;
  17817. initData( data );
  17818. };
  17819. //--- get ---
  17820. that.get = function( name ) {
  17821. if ( typeof name === "string" ) {
  17822. if ( library[ name ] ) {
  17823. return library[ name ];
  17824. } else {
  17825. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17826. return null;
  17827. }
  17828. } else {
  17829. // todo: add simple tween library
  17830. }
  17831. };
  17832. //--- parse ---
  17833. that.parse = function( root ) {
  17834. // setup hierarchy
  17835. var hierarchy = [];
  17836. if ( root instanceof THREE.SkinnedMesh ) {
  17837. for( var b = 0; b < root.bones.length; b++ ) {
  17838. hierarchy.push( root.bones[ b ] );
  17839. }
  17840. } else {
  17841. parseRecurseHierarchy( root, hierarchy );
  17842. }
  17843. return hierarchy;
  17844. };
  17845. var parseRecurseHierarchy = function( root, hierarchy ) {
  17846. hierarchy.push( root );
  17847. for( var c = 0; c < root.children.length; c++ )
  17848. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17849. }
  17850. //--- init data ---
  17851. var initData = function( data ) {
  17852. if( data.initialized === true )
  17853. return;
  17854. // loop through all keys
  17855. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17856. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17857. // remove minus times
  17858. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17859. data.hierarchy[ h ].keys[ k ].time = 0;
  17860. // create quaternions
  17861. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17862. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17863. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17864. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17865. }
  17866. }
  17867. // prepare morph target keys
  17868. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17869. // get all used
  17870. var usedMorphTargets = {};
  17871. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17872. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17873. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17874. usedMorphTargets[ morphTargetName ] = -1;
  17875. }
  17876. }
  17877. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17878. // set all used on all frames
  17879. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17880. var influences = {};
  17881. for ( var morphTargetName in usedMorphTargets ) {
  17882. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17883. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17884. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17885. break;
  17886. }
  17887. }
  17888. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17889. influences[ morphTargetName ] = 0;
  17890. }
  17891. }
  17892. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17893. }
  17894. }
  17895. // remove all keys that are on the same time
  17896. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17897. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17898. data.hierarchy[ h ].keys.splice( k, 1 );
  17899. k --;
  17900. }
  17901. }
  17902. // set index
  17903. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17904. data.hierarchy[ h ].keys[ k ].index = k;
  17905. }
  17906. }
  17907. // JIT
  17908. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17909. data.JIT = {};
  17910. data.JIT.hierarchy = [];
  17911. for( var h = 0; h < data.hierarchy.length; h ++ )
  17912. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17913. // done
  17914. data.initialized = true;
  17915. };
  17916. // interpolation types
  17917. that.LINEAR = 0;
  17918. that.CATMULLROM = 1;
  17919. that.CATMULLROM_FORWARD = 2;
  17920. return that;
  17921. }());
  17922. /**
  17923. * @author mikael emtinger / http://gomo.se/
  17924. * @author mrdoob / http://mrdoob.com/
  17925. * @author alteredq / http://alteredqualia.com/
  17926. */
  17927. THREE.Animation = function ( root, name, interpolationType ) {
  17928. this.root = root;
  17929. this.data = THREE.AnimationHandler.get( name );
  17930. this.hierarchy = THREE.AnimationHandler.parse( root );
  17931. this.currentTime = 0;
  17932. this.timeScale = 1;
  17933. this.isPlaying = false;
  17934. this.isPaused = true;
  17935. this.loop = true;
  17936. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17937. this.points = [];
  17938. this.target = new THREE.Vector3();
  17939. };
  17940. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17941. if ( this.isPlaying === false ) {
  17942. this.isPlaying = true;
  17943. this.loop = loop !== undefined ? loop : true;
  17944. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17945. // reset key cache
  17946. var h, hl = this.hierarchy.length,
  17947. object;
  17948. for ( h = 0; h < hl; h ++ ) {
  17949. object = this.hierarchy[ h ];
  17950. object.matrixAutoUpdate = true;
  17951. if ( object.animationCache === undefined ) {
  17952. object.animationCache = {};
  17953. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17954. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17955. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17956. }
  17957. var prevKey = object.animationCache.prevKey;
  17958. var nextKey = object.animationCache.nextKey;
  17959. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17960. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17961. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17962. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17963. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17964. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17965. }
  17966. this.update( 0 );
  17967. }
  17968. this.isPaused = false;
  17969. THREE.AnimationHandler.addToUpdate( this );
  17970. };
  17971. THREE.Animation.prototype.pause = function() {
  17972. if ( this.isPaused === true ) {
  17973. THREE.AnimationHandler.addToUpdate( this );
  17974. } else {
  17975. THREE.AnimationHandler.removeFromUpdate( this );
  17976. }
  17977. this.isPaused = !this.isPaused;
  17978. };
  17979. THREE.Animation.prototype.stop = function() {
  17980. this.isPlaying = false;
  17981. this.isPaused = false;
  17982. THREE.AnimationHandler.removeFromUpdate( this );
  17983. };
  17984. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17985. // early out
  17986. if ( this.isPlaying === false ) return;
  17987. // vars
  17988. var types = [ "pos", "rot", "scl" ];
  17989. var type;
  17990. var scale;
  17991. var vector;
  17992. var prevXYZ, nextXYZ;
  17993. var prevKey, nextKey;
  17994. var object;
  17995. var animationCache;
  17996. var frame;
  17997. var JIThierarchy = this.data.JIT.hierarchy;
  17998. var currentTime, unloopedCurrentTime;
  17999. var currentPoint, forwardPoint, angle;
  18000. this.currentTime += deltaTimeMS * this.timeScale;
  18001. unloopedCurrentTime = this.currentTime;
  18002. // Mod operation fails on floats
  18003. // was this supposed to be in frames?
  18004. while ( this.currentTime > this.data.length ) {
  18005. this.currentTime -= this.data.length;
  18006. }
  18007. currentTime = this.currentTime = this.currentTime % this.data.length;
  18008. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18009. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18010. object = this.hierarchy[ h ];
  18011. animationCache = object.animationCache;
  18012. // loop through pos/rot/scl
  18013. for ( var t = 0; t < 3; t ++ ) {
  18014. // get keys
  18015. type = types[ t ];
  18016. prevKey = animationCache.prevKey[ type ];
  18017. nextKey = animationCache.nextKey[ type ];
  18018. // switch keys?
  18019. if ( nextKey.time <= unloopedCurrentTime ) {
  18020. // did we loop?
  18021. if ( currentTime <= unloopedCurrentTime ) {
  18022. if ( this.loop ) {
  18023. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18024. nextKey = this.getNextKeyWith( type, h, 1 );
  18025. // if ( nextKey.index < prevKey.index ) then we have wrapped over the end, and nextKey.time < currentTime will loop forever
  18026. while ( nextKey !== null && nextKey.time < currentTime && nextKey.index > prevKey.index) {
  18027. prevKey = nextKey;
  18028. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18029. }
  18030. } else {
  18031. this.stop();
  18032. return;
  18033. }
  18034. } else {
  18035. do {
  18036. prevKey = nextKey;
  18037. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18038. } while ( nextKey !== null && nextKey.time < currentTime && nextKey.index > prevKey.index )
  18039. // if ( nextKey.index < prevKey.index ) then we have wrapped over the end, and nextKey.time < currentTime will loop forever
  18040. }
  18041. animationCache.prevKey[ type ] = prevKey;
  18042. animationCache.nextKey[ type ] = nextKey;
  18043. }
  18044. object.matrixAutoUpdate = true;
  18045. object.matrixWorldNeedsUpdate = true;
  18046. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18047. prevXYZ = prevKey[ type ];
  18048. nextXYZ = nextKey[ type ];
  18049. // check scale error
  18050. if ( scale < 0 || scale > 1 ) {
  18051. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  18052. scale = scale < 0 ? 0 : 1;
  18053. }
  18054. // interpolate
  18055. if ( type === "pos" ) {
  18056. vector = object.position;
  18057. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18058. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18059. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18060. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18061. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18062. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18063. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18064. this.points[ 1 ] = prevXYZ;
  18065. this.points[ 2 ] = nextXYZ;
  18066. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18067. scale = scale * 0.33 + 0.33;
  18068. currentPoint = this.interpolateCatmullRom( this.points, scale );
  18069. vector.x = currentPoint[ 0 ];
  18070. vector.y = currentPoint[ 1 ];
  18071. vector.z = currentPoint[ 2 ];
  18072. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18073. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  18074. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18075. this.target.sub( vector );
  18076. this.target.y = 0;
  18077. this.target.normalize();
  18078. angle = Math.atan2( this.target.x, this.target.z );
  18079. object.rotation.set( 0, angle, 0 );
  18080. }
  18081. }
  18082. } else if ( type === "rot" ) {
  18083. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18084. } else if ( type === "scl" ) {
  18085. vector = object.scale;
  18086. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18087. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18088. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18089. }
  18090. }
  18091. }
  18092. };
  18093. // Catmull-Rom spline
  18094. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  18095. var c = [], v3 = [],
  18096. point, intPoint, weight, w2, w3,
  18097. pa, pb, pc, pd;
  18098. point = ( points.length - 1 ) * scale;
  18099. intPoint = Math.floor( point );
  18100. weight = point - intPoint;
  18101. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18102. c[ 1 ] = intPoint;
  18103. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18104. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18105. pa = points[ c[ 0 ] ];
  18106. pb = points[ c[ 1 ] ];
  18107. pc = points[ c[ 2 ] ];
  18108. pd = points[ c[ 3 ] ];
  18109. w2 = weight * weight;
  18110. w3 = weight * w2;
  18111. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18112. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18113. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18114. return v3;
  18115. };
  18116. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18117. var v0 = ( p2 - p0 ) * 0.5,
  18118. v1 = ( p3 - p1 ) * 0.5;
  18119. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18120. };
  18121. // Get next key with
  18122. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18123. var keys = this.data.hierarchy[ h ].keys;
  18124. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18125. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18126. key = key < keys.length - 1 ? key : keys.length - 1;
  18127. } else {
  18128. key = key % keys.length;
  18129. }
  18130. for ( ; key < keys.length; key++ ) {
  18131. if ( keys[ key ][ type ] !== undefined ) {
  18132. return keys[ key ];
  18133. }
  18134. }
  18135. return this.data.hierarchy[ h ].keys[ 0 ];
  18136. };
  18137. // Get previous key with
  18138. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18139. var keys = this.data.hierarchy[ h ].keys;
  18140. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18141. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18142. key = key > 0 ? key : 0;
  18143. } else {
  18144. key = key >= 0 ? key : key + keys.length;
  18145. }
  18146. for ( ; key >= 0; key -- ) {
  18147. if ( keys[ key ][ type ] !== undefined ) {
  18148. return keys[ key ];
  18149. }
  18150. }
  18151. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18152. };
  18153. /**
  18154. * @author mikael emtinger / http://gomo.se/
  18155. * @author mrdoob / http://mrdoob.com/
  18156. * @author alteredq / http://alteredqualia.com/
  18157. * @author khang duong
  18158. * @author erik kitson
  18159. */
  18160. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  18161. this.root = root;
  18162. this.data = THREE.AnimationHandler.get( data );
  18163. this.hierarchy = THREE.AnimationHandler.parse( root );
  18164. this.currentTime = 0;
  18165. this.timeScale = 0.001;
  18166. this.isPlaying = false;
  18167. this.isPaused = true;
  18168. this.loop = true;
  18169. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  18170. // initialize to first keyframes
  18171. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18172. var keys = this.data.hierarchy[h].keys,
  18173. sids = this.data.hierarchy[h].sids,
  18174. obj = this.hierarchy[h];
  18175. if ( keys.length && sids ) {
  18176. for ( var s = 0; s < sids.length; s++ ) {
  18177. var sid = sids[ s ],
  18178. next = this.getNextKeyWith( sid, h, 0 );
  18179. if ( next ) {
  18180. next.apply( sid );
  18181. }
  18182. }
  18183. obj.matrixAutoUpdate = false;
  18184. this.data.hierarchy[h].node.updateMatrix();
  18185. obj.matrixWorldNeedsUpdate = true;
  18186. }
  18187. }
  18188. };
  18189. // Play
  18190. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18191. if( !this.isPlaying ) {
  18192. this.isPlaying = true;
  18193. this.loop = loop !== undefined ? loop : true;
  18194. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18195. this.startTimeMs = startTimeMS;
  18196. this.startTime = 10000000;
  18197. this.endTime = -this.startTime;
  18198. // reset key cache
  18199. var h, hl = this.hierarchy.length,
  18200. object,
  18201. node;
  18202. for ( h = 0; h < hl; h++ ) {
  18203. object = this.hierarchy[ h ];
  18204. node = this.data.hierarchy[ h ];
  18205. if ( node.animationCache === undefined ) {
  18206. node.animationCache = {};
  18207. node.animationCache.prevKey = null;
  18208. node.animationCache.nextKey = null;
  18209. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18210. }
  18211. var keys = this.data.hierarchy[h].keys;
  18212. if (keys.length) {
  18213. node.animationCache.prevKey = keys[ 0 ];
  18214. node.animationCache.nextKey = keys[ 1 ];
  18215. this.startTime = Math.min( keys[0].time, this.startTime );
  18216. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18217. }
  18218. }
  18219. this.update( 0 );
  18220. }
  18221. this.isPaused = false;
  18222. THREE.AnimationHandler.addToUpdate( this );
  18223. };
  18224. // Pause
  18225. THREE.KeyFrameAnimation.prototype.pause = function() {
  18226. if( this.isPaused ) {
  18227. THREE.AnimationHandler.addToUpdate( this );
  18228. } else {
  18229. THREE.AnimationHandler.removeFromUpdate( this );
  18230. }
  18231. this.isPaused = !this.isPaused;
  18232. };
  18233. // Stop
  18234. THREE.KeyFrameAnimation.prototype.stop = function() {
  18235. this.isPlaying = false;
  18236. this.isPaused = false;
  18237. THREE.AnimationHandler.removeFromUpdate( this );
  18238. // reset JIT matrix and remove cache
  18239. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18240. var obj = this.hierarchy[ h ];
  18241. var node = this.data.hierarchy[ h ];
  18242. if ( node.animationCache !== undefined ) {
  18243. var original = node.animationCache.originalMatrix;
  18244. if( obj instanceof THREE.Bone ) {
  18245. original.copy( obj.skinMatrix );
  18246. obj.skinMatrix = original;
  18247. } else {
  18248. original.copy( obj.matrix );
  18249. obj.matrix = original;
  18250. }
  18251. delete node.animationCache;
  18252. }
  18253. }
  18254. };
  18255. // Update
  18256. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18257. // early out
  18258. if( !this.isPlaying ) return;
  18259. // vars
  18260. var prevKey, nextKey;
  18261. var object;
  18262. var node;
  18263. var frame;
  18264. var JIThierarchy = this.data.JIT.hierarchy;
  18265. var currentTime, unloopedCurrentTime;
  18266. var looped;
  18267. // update
  18268. this.currentTime += deltaTimeMS * this.timeScale;
  18269. unloopedCurrentTime = this.currentTime;
  18270. currentTime = this.currentTime = this.currentTime % this.data.length;
  18271. // if looped around, the current time should be based on the startTime
  18272. if ( currentTime < this.startTimeMs ) {
  18273. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18274. }
  18275. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18276. looped = currentTime < unloopedCurrentTime;
  18277. if ( looped && !this.loop ) {
  18278. // Set the animation to the last keyframes and stop
  18279. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18280. var keys = this.data.hierarchy[h].keys,
  18281. sids = this.data.hierarchy[h].sids,
  18282. end = keys.length-1,
  18283. obj = this.hierarchy[h];
  18284. if ( keys.length ) {
  18285. for ( var s = 0; s < sids.length; s++ ) {
  18286. var sid = sids[ s ],
  18287. prev = this.getPrevKeyWith( sid, h, end );
  18288. if ( prev ) {
  18289. prev.apply( sid );
  18290. }
  18291. }
  18292. this.data.hierarchy[h].node.updateMatrix();
  18293. obj.matrixWorldNeedsUpdate = true;
  18294. }
  18295. }
  18296. this.stop();
  18297. return;
  18298. }
  18299. // check pre-infinity
  18300. if ( currentTime < this.startTime ) {
  18301. return;
  18302. }
  18303. // update
  18304. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18305. object = this.hierarchy[ h ];
  18306. node = this.data.hierarchy[ h ];
  18307. var keys = node.keys,
  18308. animationCache = node.animationCache;
  18309. // use JIT?
  18310. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18311. if( object instanceof THREE.Bone ) {
  18312. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18313. object.matrixWorldNeedsUpdate = false;
  18314. } else {
  18315. object.matrix = JIThierarchy[ h ][ frame ];
  18316. object.matrixWorldNeedsUpdate = true;
  18317. }
  18318. // use interpolation
  18319. } else if ( keys.length ) {
  18320. // make sure so original matrix and not JIT matrix is set
  18321. if ( this.JITCompile && animationCache ) {
  18322. if( object instanceof THREE.Bone ) {
  18323. object.skinMatrix = animationCache.originalMatrix;
  18324. } else {
  18325. object.matrix = animationCache.originalMatrix;
  18326. }
  18327. }
  18328. prevKey = animationCache.prevKey;
  18329. nextKey = animationCache.nextKey;
  18330. if ( prevKey && nextKey ) {
  18331. // switch keys?
  18332. if ( nextKey.time <= unloopedCurrentTime ) {
  18333. // did we loop?
  18334. if ( looped && this.loop ) {
  18335. prevKey = keys[ 0 ];
  18336. nextKey = keys[ 1 ];
  18337. while ( nextKey.time < currentTime ) {
  18338. prevKey = nextKey;
  18339. nextKey = keys[ prevKey.index + 1 ];
  18340. }
  18341. } else if ( !looped ) {
  18342. var lastIndex = keys.length - 1;
  18343. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18344. prevKey = nextKey;
  18345. nextKey = keys[ prevKey.index + 1 ];
  18346. }
  18347. }
  18348. animationCache.prevKey = prevKey;
  18349. animationCache.nextKey = nextKey;
  18350. }
  18351. if(nextKey.time >= currentTime)
  18352. prevKey.interpolate( nextKey, currentTime );
  18353. else
  18354. prevKey.interpolate( nextKey, nextKey.time);
  18355. }
  18356. this.data.hierarchy[h].node.updateMatrix();
  18357. object.matrixWorldNeedsUpdate = true;
  18358. }
  18359. }
  18360. // update JIT?
  18361. if ( this.JITCompile ) {
  18362. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18363. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18364. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18365. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18366. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18367. } else {
  18368. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18369. }
  18370. }
  18371. }
  18372. }
  18373. };
  18374. // Get next key with
  18375. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18376. var keys = this.data.hierarchy[ h ].keys;
  18377. key = key % keys.length;
  18378. for ( ; key < keys.length; key++ ) {
  18379. if ( keys[ key ].hasTarget( sid ) ) {
  18380. return keys[ key ];
  18381. }
  18382. }
  18383. return keys[ 0 ];
  18384. };
  18385. // Get previous key with
  18386. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18387. var keys = this.data.hierarchy[ h ].keys;
  18388. key = key >= 0 ? key : key + keys.length;
  18389. for ( ; key >= 0; key-- ) {
  18390. if ( keys[ key ].hasTarget( sid ) ) {
  18391. return keys[ key ];
  18392. }
  18393. }
  18394. return keys[ keys.length - 1 ];
  18395. };
  18396. /**
  18397. * Camera for rendering cube maps
  18398. * - renders scene into axis-aligned cube
  18399. *
  18400. * @author alteredq / http://alteredqualia.com/
  18401. */
  18402. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18403. THREE.Object3D.call( this );
  18404. var fov = 90, aspect = 1;
  18405. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18406. cameraPX.up.set( 0, -1, 0 );
  18407. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18408. this.add( cameraPX );
  18409. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18410. cameraNX.up.set( 0, -1, 0 );
  18411. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18412. this.add( cameraNX );
  18413. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18414. cameraPY.up.set( 0, 0, 1 );
  18415. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18416. this.add( cameraPY );
  18417. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18418. cameraNY.up.set( 0, 0, -1 );
  18419. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18420. this.add( cameraNY );
  18421. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18422. cameraPZ.up.set( 0, -1, 0 );
  18423. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18424. this.add( cameraPZ );
  18425. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18426. cameraNZ.up.set( 0, -1, 0 );
  18427. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18428. this.add( cameraNZ );
  18429. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18430. this.updateCubeMap = function ( renderer, scene ) {
  18431. var renderTarget = this.renderTarget;
  18432. var generateMipmaps = renderTarget.generateMipmaps;
  18433. renderTarget.generateMipmaps = false;
  18434. renderTarget.activeCubeFace = 0;
  18435. renderer.render( scene, cameraPX, renderTarget );
  18436. renderTarget.activeCubeFace = 1;
  18437. renderer.render( scene, cameraNX, renderTarget );
  18438. renderTarget.activeCubeFace = 2;
  18439. renderer.render( scene, cameraPY, renderTarget );
  18440. renderTarget.activeCubeFace = 3;
  18441. renderer.render( scene, cameraNY, renderTarget );
  18442. renderTarget.activeCubeFace = 4;
  18443. renderer.render( scene, cameraPZ, renderTarget );
  18444. renderTarget.generateMipmaps = generateMipmaps;
  18445. renderTarget.activeCubeFace = 5;
  18446. renderer.render( scene, cameraNZ, renderTarget );
  18447. };
  18448. };
  18449. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18450. /*
  18451. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18452. *
  18453. * A general perpose camera, for setting FOV, Lens Focal Length,
  18454. * and switching between perspective and orthographic views easily.
  18455. * Use this only if you do not wish to manage
  18456. * both a Orthographic and Perspective Camera
  18457. *
  18458. */
  18459. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18460. THREE.Camera.call( this );
  18461. this.fov = fov;
  18462. this.left = -width / 2;
  18463. this.right = width / 2
  18464. this.top = height / 2;
  18465. this.bottom = -height / 2;
  18466. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18467. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18468. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18469. this.zoom = 1;
  18470. this.toPerspective();
  18471. var aspect = width/height;
  18472. };
  18473. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18474. THREE.CombinedCamera.prototype.toPerspective = function () {
  18475. // Switches to the Perspective Camera
  18476. this.near = this.cameraP.near;
  18477. this.far = this.cameraP.far;
  18478. this.cameraP.fov = this.fov / this.zoom ;
  18479. this.cameraP.updateProjectionMatrix();
  18480. this.projectionMatrix = this.cameraP.projectionMatrix;
  18481. this.inPerspectiveMode = true;
  18482. this.inOrthographicMode = false;
  18483. };
  18484. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18485. // Switches to the Orthographic camera estimating viewport from Perspective
  18486. var fov = this.fov;
  18487. var aspect = this.cameraP.aspect;
  18488. var near = this.cameraP.near;
  18489. var far = this.cameraP.far;
  18490. // The size that we set is the mid plane of the viewing frustum
  18491. var hyperfocus = ( near + far ) / 2;
  18492. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18493. var planeHeight = 2 * halfHeight;
  18494. var planeWidth = planeHeight * aspect;
  18495. var halfWidth = planeWidth / 2;
  18496. halfHeight /= this.zoom;
  18497. halfWidth /= this.zoom;
  18498. this.cameraO.left = -halfWidth;
  18499. this.cameraO.right = halfWidth;
  18500. this.cameraO.top = halfHeight;
  18501. this.cameraO.bottom = -halfHeight;
  18502. // this.cameraO.left = -farHalfWidth;
  18503. // this.cameraO.right = farHalfWidth;
  18504. // this.cameraO.top = farHalfHeight;
  18505. // this.cameraO.bottom = -farHalfHeight;
  18506. // this.cameraO.left = this.left / this.zoom;
  18507. // this.cameraO.right = this.right / this.zoom;
  18508. // this.cameraO.top = this.top / this.zoom;
  18509. // this.cameraO.bottom = this.bottom / this.zoom;
  18510. this.cameraO.updateProjectionMatrix();
  18511. this.near = this.cameraO.near;
  18512. this.far = this.cameraO.far;
  18513. this.projectionMatrix = this.cameraO.projectionMatrix;
  18514. this.inPerspectiveMode = false;
  18515. this.inOrthographicMode = true;
  18516. };
  18517. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18518. this.cameraP.aspect = width / height;
  18519. this.left = -width / 2;
  18520. this.right = width / 2
  18521. this.top = height / 2;
  18522. this.bottom = -height / 2;
  18523. };
  18524. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18525. this.fov = fov;
  18526. if ( this.inPerspectiveMode ) {
  18527. this.toPerspective();
  18528. } else {
  18529. this.toOrthographic();
  18530. }
  18531. };
  18532. // For mantaining similar API with PerspectiveCamera
  18533. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18534. if ( this.inPerspectiveMode ) {
  18535. this.toPerspective();
  18536. } else {
  18537. this.toPerspective();
  18538. this.toOrthographic();
  18539. }
  18540. };
  18541. /*
  18542. * Uses Focal Length (in mm) to estimate and set FOV
  18543. * 35mm (fullframe) camera is used if frame size is not specified;
  18544. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18545. */
  18546. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18547. if ( frameHeight === undefined ) frameHeight = 24;
  18548. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18549. this.setFov( fov );
  18550. return fov;
  18551. };
  18552. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18553. this.zoom = zoom;
  18554. if ( this.inPerspectiveMode ) {
  18555. this.toPerspective();
  18556. } else {
  18557. this.toOrthographic();
  18558. }
  18559. };
  18560. THREE.CombinedCamera.prototype.toFrontView = function() {
  18561. this.rotation.x = 0;
  18562. this.rotation.y = 0;
  18563. this.rotation.z = 0;
  18564. // should we be modifing the matrix instead?
  18565. this.rotationAutoUpdate = false;
  18566. };
  18567. THREE.CombinedCamera.prototype.toBackView = function() {
  18568. this.rotation.x = 0;
  18569. this.rotation.y = Math.PI;
  18570. this.rotation.z = 0;
  18571. this.rotationAutoUpdate = false;
  18572. };
  18573. THREE.CombinedCamera.prototype.toLeftView = function() {
  18574. this.rotation.x = 0;
  18575. this.rotation.y = - Math.PI / 2;
  18576. this.rotation.z = 0;
  18577. this.rotationAutoUpdate = false;
  18578. };
  18579. THREE.CombinedCamera.prototype.toRightView = function() {
  18580. this.rotation.x = 0;
  18581. this.rotation.y = Math.PI / 2;
  18582. this.rotation.z = 0;
  18583. this.rotationAutoUpdate = false;
  18584. };
  18585. THREE.CombinedCamera.prototype.toTopView = function() {
  18586. this.rotation.x = - Math.PI / 2;
  18587. this.rotation.y = 0;
  18588. this.rotation.z = 0;
  18589. this.rotationAutoUpdate = false;
  18590. };
  18591. THREE.CombinedCamera.prototype.toBottomView = function() {
  18592. this.rotation.x = Math.PI / 2;
  18593. this.rotation.y = 0;
  18594. this.rotation.z = 0;
  18595. this.rotationAutoUpdate = false;
  18596. };
  18597. /**
  18598. * @author hughes
  18599. */
  18600. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18601. THREE.Geometry.call( this );
  18602. this.radius = radius = radius || 50;
  18603. this.segments = segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18604. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18605. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18606. var i, uvs = [],
  18607. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18608. this.vertices.push(center);
  18609. uvs.push( centerUV );
  18610. for ( i = 0; i <= segments; i ++ ) {
  18611. var vertex = new THREE.Vector3();
  18612. var segment = thetaStart + i / segments * thetaLength;
  18613. vertex.x = radius * Math.cos( segment );
  18614. vertex.y = radius * Math.sin( segment );
  18615. this.vertices.push( vertex );
  18616. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  18617. }
  18618. var n = new THREE.Vector3( 0, 0, 1 );
  18619. for ( i = 1; i <= segments; i ++ ) {
  18620. var v1 = i;
  18621. var v2 = i + 1 ;
  18622. var v3 = 0;
  18623. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  18624. this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] );
  18625. }
  18626. this.computeCentroids();
  18627. this.computeFaceNormals();
  18628. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18629. };
  18630. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18631. /**
  18632. * @author mrdoob / http://mrdoob.com/
  18633. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18634. */
  18635. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18636. THREE.Geometry.call( this );
  18637. var scope = this;
  18638. this.width = width;
  18639. this.height = height;
  18640. this.depth = depth;
  18641. this.widthSegments = widthSegments || 1;
  18642. this.heightSegments = heightSegments || 1;
  18643. this.depthSegments = depthSegments || 1;
  18644. var width_half = this.width / 2;
  18645. var height_half = this.height / 2;
  18646. var depth_half = this.depth / 2;
  18647. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18648. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18649. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18650. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18651. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18652. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18653. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18654. var w, ix, iy,
  18655. gridX = scope.widthSegments,
  18656. gridY = scope.heightSegments,
  18657. width_half = width / 2,
  18658. height_half = height / 2,
  18659. offset = scope.vertices.length;
  18660. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18661. w = 'z';
  18662. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18663. w = 'y';
  18664. gridY = scope.depthSegments;
  18665. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18666. w = 'x';
  18667. gridX = scope.depthSegments;
  18668. }
  18669. var gridX1 = gridX + 1,
  18670. gridY1 = gridY + 1,
  18671. segment_width = width / gridX,
  18672. segment_height = height / gridY,
  18673. normal = new THREE.Vector3();
  18674. normal[ w ] = depth > 0 ? 1 : - 1;
  18675. for ( iy = 0; iy < gridY1; iy ++ ) {
  18676. for ( ix = 0; ix < gridX1; ix ++ ) {
  18677. var vector = new THREE.Vector3();
  18678. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18679. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18680. vector[ w ] = depth;
  18681. scope.vertices.push( vector );
  18682. }
  18683. }
  18684. for ( iy = 0; iy < gridY; iy++ ) {
  18685. for ( ix = 0; ix < gridX; ix++ ) {
  18686. var a = ix + gridX1 * iy;
  18687. var b = ix + gridX1 * ( iy + 1 );
  18688. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18689. var d = ( ix + 1 ) + gridX1 * iy;
  18690. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  18691. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  18692. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  18693. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  18694. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  18695. face.normal.copy( normal );
  18696. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18697. face.materialIndex = materialIndex;
  18698. scope.faces.push( face );
  18699. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  18700. face = new THREE.Face3( b + offset, c + offset, d + offset );
  18701. face.normal.copy( normal );
  18702. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18703. face.materialIndex = materialIndex;
  18704. scope.faces.push( face );
  18705. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  18706. }
  18707. }
  18708. }
  18709. this.computeCentroids();
  18710. this.mergeVertices();
  18711. };
  18712. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18713. /**
  18714. * @author mrdoob / http://mrdoob.com/
  18715. */
  18716. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  18717. THREE.Geometry.call( this );
  18718. this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18719. this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18720. this.height = height = height !== undefined ? height : 100;
  18721. this.radialSegments = radialSegments = radialSegments || 8;
  18722. this.heightSegments = heightSegments = heightSegments || 1;
  18723. this.openEnded = openEnded = openEnded !== undefined ? openEnded : false;
  18724. var heightHalf = height / 2;
  18725. var x, y, vertices = [], uvs = [];
  18726. for ( y = 0; y <= heightSegments; y ++ ) {
  18727. var verticesRow = [];
  18728. var uvsRow = [];
  18729. var v = y / heightSegments;
  18730. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18731. for ( x = 0; x <= radialSegments; x ++ ) {
  18732. var u = x / radialSegments;
  18733. var vertex = new THREE.Vector3();
  18734. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18735. vertex.y = - v * height + heightHalf;
  18736. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18737. this.vertices.push( vertex );
  18738. verticesRow.push( this.vertices.length - 1 );
  18739. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18740. }
  18741. vertices.push( verticesRow );
  18742. uvs.push( uvsRow );
  18743. }
  18744. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18745. var na, nb;
  18746. for ( x = 0; x < radialSegments; x ++ ) {
  18747. if ( radiusTop !== 0 ) {
  18748. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18749. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18750. } else {
  18751. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18752. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18753. }
  18754. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18755. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18756. for ( y = 0; y < heightSegments; y ++ ) {
  18757. var v1 = vertices[ y ][ x ];
  18758. var v2 = vertices[ y + 1 ][ x ];
  18759. var v3 = vertices[ y + 1 ][ x + 1 ];
  18760. var v4 = vertices[ y ][ x + 1 ];
  18761. var n1 = na.clone();
  18762. var n2 = na.clone();
  18763. var n3 = nb.clone();
  18764. var n4 = nb.clone();
  18765. var uv1 = uvs[ y ][ x ].clone();
  18766. var uv2 = uvs[ y + 1 ][ x ].clone();
  18767. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18768. var uv4 = uvs[ y ][ x + 1 ].clone();
  18769. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  18770. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  18771. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  18772. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  18773. }
  18774. }
  18775. // top cap
  18776. if ( openEnded === false && radiusTop > 0 ) {
  18777. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18778. for ( x = 0; x < radialSegments; x ++ ) {
  18779. var v1 = vertices[ 0 ][ x ];
  18780. var v2 = vertices[ 0 ][ x + 1 ];
  18781. var v3 = this.vertices.length - 1;
  18782. var n1 = new THREE.Vector3( 0, 1, 0 );
  18783. var n2 = new THREE.Vector3( 0, 1, 0 );
  18784. var n3 = new THREE.Vector3( 0, 1, 0 );
  18785. var uv1 = uvs[ 0 ][ x ].clone();
  18786. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18787. var uv3 = new THREE.Vector2( uv2.x, 0 );
  18788. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18789. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18790. }
  18791. }
  18792. // bottom cap
  18793. if ( openEnded === false && radiusBottom > 0 ) {
  18794. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18795. for ( x = 0; x < radialSegments; x ++ ) {
  18796. var v1 = vertices[ y ][ x + 1 ];
  18797. var v2 = vertices[ y ][ x ];
  18798. var v3 = this.vertices.length - 1;
  18799. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18800. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18801. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18802. var uv1 = uvs[ y ][ x + 1 ].clone();
  18803. var uv2 = uvs[ y ][ x ].clone();
  18804. var uv3 = new THREE.Vector2( uv2.x, 1 );
  18805. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18806. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18807. }
  18808. }
  18809. this.computeCentroids();
  18810. this.computeFaceNormals();
  18811. }
  18812. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18813. /**
  18814. * @author zz85 / http://www.lab4games.net/zz85/blog
  18815. *
  18816. * Creates extruded geometry from a path shape.
  18817. *
  18818. * parameters = {
  18819. *
  18820. * curveSegments: <int>, // number of points on the curves
  18821. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18822. * amount: <int>, // Depth to extrude the shape
  18823. *
  18824. * bevelEnabled: <bool>, // turn on bevel
  18825. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18826. * bevelSize: <float>, // how far from shape outline is bevel
  18827. * bevelSegments: <int>, // number of bevel layers
  18828. *
  18829. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18830. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18831. *
  18832. * material: <int> // material index for front and back faces
  18833. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18834. * uvGenerator: <Object> // object that provides UV generator functions
  18835. *
  18836. * }
  18837. **/
  18838. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18839. if ( typeof( shapes ) === "undefined" ) {
  18840. shapes = [];
  18841. return;
  18842. }
  18843. THREE.Geometry.call( this );
  18844. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18845. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18846. this.addShapeList( shapes, options );
  18847. this.computeCentroids();
  18848. this.computeFaceNormals();
  18849. // can't really use automatic vertex normals
  18850. // as then front and back sides get smoothed too
  18851. // should do separate smoothing just for sides
  18852. //this.computeVertexNormals();
  18853. //console.log( "took", ( Date.now() - startTime ) );
  18854. };
  18855. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18856. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18857. var sl = shapes.length;
  18858. for ( var s = 0; s < sl; s ++ ) {
  18859. var shape = shapes[ s ];
  18860. this.addShape( shape, options );
  18861. }
  18862. };
  18863. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18864. var amount = options.amount !== undefined ? options.amount : 100;
  18865. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18866. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18867. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18868. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18869. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18870. var steps = options.steps !== undefined ? options.steps : 1;
  18871. var extrudePath = options.extrudePath;
  18872. var extrudePts, extrudeByPath = false;
  18873. var material = options.material;
  18874. var extrudeMaterial = options.extrudeMaterial;
  18875. // Use default WorldUVGenerator if no UV generators are specified.
  18876. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18877. var shapebb = this.shapebb;
  18878. //shapebb = shape.getBoundingBox();
  18879. var splineTube, binormal, normal, position2;
  18880. if ( extrudePath ) {
  18881. extrudePts = extrudePath.getSpacedPoints( steps );
  18882. extrudeByPath = true;
  18883. bevelEnabled = false; // bevels not supported for path extrusion
  18884. // SETUP TNB variables
  18885. // Reuse TNB from TubeGeomtry for now.
  18886. // TODO1 - have a .isClosed in spline?
  18887. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18888. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18889. binormal = new THREE.Vector3();
  18890. normal = new THREE.Vector3();
  18891. position2 = new THREE.Vector3();
  18892. }
  18893. // Safeguards if bevels are not enabled
  18894. if ( ! bevelEnabled ) {
  18895. bevelSegments = 0;
  18896. bevelThickness = 0;
  18897. bevelSize = 0;
  18898. }
  18899. // Variables initalization
  18900. var ahole, h, hl; // looping of holes
  18901. var scope = this;
  18902. var bevelPoints = [];
  18903. var shapesOffset = this.vertices.length;
  18904. var shapePoints = shape.extractPoints( curveSegments );
  18905. var vertices = shapePoints.shape;
  18906. var holes = shapePoints.holes;
  18907. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18908. if ( reverse ) {
  18909. vertices = vertices.reverse();
  18910. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18911. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18912. ahole = holes[ h ];
  18913. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18914. holes[ h ] = ahole.reverse();
  18915. }
  18916. }
  18917. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18918. }
  18919. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18920. /* Vertices */
  18921. var contour = vertices; // vertices has all points but contour has only points of circumference
  18922. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18923. ahole = holes[ h ];
  18924. vertices = vertices.concat( ahole );
  18925. }
  18926. function scalePt2 ( pt, vec, size ) {
  18927. if ( !vec ) console.log( "die" );
  18928. return vec.clone().multiplyScalar( size ).add( pt );
  18929. }
  18930. var b, bs, t, z,
  18931. vert, vlen = vertices.length,
  18932. face, flen = faces.length,
  18933. cont, clen = contour.length;
  18934. // Find directions for point movement
  18935. var RAD_TO_DEGREES = 180 / Math.PI;
  18936. function getBevelVec( pt_i, pt_j, pt_k ) {
  18937. // Algorithm 2
  18938. return getBevelVec2( pt_i, pt_j, pt_k );
  18939. }
  18940. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18941. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18942. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18943. if ( anglea > angleb ) {
  18944. angleb += Math.PI * 2;
  18945. }
  18946. var anglec = ( anglea + angleb ) / 2;
  18947. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18948. var x = - Math.cos( anglec );
  18949. var y = - Math.sin( anglec );
  18950. var vec = new THREE.Vector2( x, y ); //.normalize();
  18951. return vec;
  18952. }
  18953. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18954. var a = THREE.ExtrudeGeometry.__v1,
  18955. b = THREE.ExtrudeGeometry.__v2,
  18956. v_hat = THREE.ExtrudeGeometry.__v3,
  18957. w_hat = THREE.ExtrudeGeometry.__v4,
  18958. p = THREE.ExtrudeGeometry.__v5,
  18959. q = THREE.ExtrudeGeometry.__v6,
  18960. v, w,
  18961. v_dot_w_hat, q_sub_p_dot_w_hat,
  18962. s, intersection;
  18963. // good reading for line-line intersection
  18964. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18965. // define a as vector j->i
  18966. // define b as vectot k->i
  18967. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18968. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18969. // get unit vectors
  18970. v = a.normalize();
  18971. w = b.normalize();
  18972. // normals from pt i
  18973. v_hat.set( -v.y, v.x );
  18974. w_hat.set( w.y, -w.x );
  18975. // pts from i
  18976. p.copy( pt_i ).add( v_hat );
  18977. q.copy( pt_i ).add( w_hat );
  18978. if ( p.equals( q ) ) {
  18979. //console.log("Warning: lines are straight");
  18980. return w_hat.clone();
  18981. }
  18982. // Points from j, k. helps prevents points cross overover most of the time
  18983. p.copy( pt_j ).add( v_hat );
  18984. q.copy( pt_k ).add( w_hat );
  18985. v_dot_w_hat = v.dot( w_hat );
  18986. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  18987. // We should not reach these conditions
  18988. if ( v_dot_w_hat === 0 ) {
  18989. console.log( "Either infinite or no solutions!" );
  18990. if ( q_sub_p_dot_w_hat === 0 ) {
  18991. console.log( "Its finite solutions." );
  18992. } else {
  18993. console.log( "Too bad, no solutions." );
  18994. }
  18995. }
  18996. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18997. if ( s < 0 ) {
  18998. // in case of emergecy, revert to algorithm 1.
  18999. return getBevelVec1( pt_i, pt_j, pt_k );
  19000. }
  19001. intersection = v.multiplyScalar( s ).add( p );
  19002. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  19003. }
  19004. var contourMovements = [];
  19005. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19006. if ( j === il ) j = 0;
  19007. if ( k === il ) k = 0;
  19008. // (j)---(i)---(k)
  19009. // console.log('i,j,k', i, j , k)
  19010. var pt_i = contour[ i ];
  19011. var pt_j = contour[ j ];
  19012. var pt_k = contour[ k ];
  19013. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19014. }
  19015. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19016. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19017. ahole = holes[ h ];
  19018. oneHoleMovements = [];
  19019. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19020. if ( j === il ) j = 0;
  19021. if ( k === il ) k = 0;
  19022. // (j)---(i)---(k)
  19023. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19024. }
  19025. holesMovements.push( oneHoleMovements );
  19026. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19027. }
  19028. // Loop bevelSegments, 1 for the front, 1 for the back
  19029. for ( b = 0; b < bevelSegments; b ++ ) {
  19030. //for ( b = bevelSegments; b > 0; b -- ) {
  19031. t = b / bevelSegments;
  19032. z = bevelThickness * ( 1 - t );
  19033. //z = bevelThickness * t;
  19034. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  19035. //bs = bevelSize * t ; // linear
  19036. // contract shape
  19037. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19038. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19039. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  19040. v( vert.x, vert.y, - z );
  19041. }
  19042. // expand holes
  19043. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19044. ahole = holes[ h ];
  19045. oneHoleMovements = holesMovements[ h ];
  19046. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19047. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19048. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  19049. v( vert.x, vert.y, -z );
  19050. }
  19051. }
  19052. }
  19053. bs = bevelSize;
  19054. // Back facing vertices
  19055. for ( i = 0; i < vlen; i ++ ) {
  19056. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19057. if ( !extrudeByPath ) {
  19058. v( vert.x, vert.y, 0 );
  19059. } else {
  19060. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19061. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19062. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19063. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  19064. v( position2.x, position2.y, position2.z );
  19065. }
  19066. }
  19067. // Add stepped vertices...
  19068. // Including front facing vertices
  19069. var s;
  19070. for ( s = 1; s <= steps; s ++ ) {
  19071. for ( i = 0; i < vlen; i ++ ) {
  19072. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19073. if ( !extrudeByPath ) {
  19074. v( vert.x, vert.y, amount / steps * s );
  19075. } else {
  19076. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19077. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19078. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19079. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19080. v( position2.x, position2.y, position2.z );
  19081. }
  19082. }
  19083. }
  19084. // Add bevel segments planes
  19085. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19086. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19087. t = b / bevelSegments;
  19088. z = bevelThickness * ( 1 - t );
  19089. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19090. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19091. // contract shape
  19092. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19093. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19094. v( vert.x, vert.y, amount + z );
  19095. }
  19096. // expand holes
  19097. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19098. ahole = holes[ h ];
  19099. oneHoleMovements = holesMovements[ h ];
  19100. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19101. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19102. if ( !extrudeByPath ) {
  19103. v( vert.x, vert.y, amount + z );
  19104. } else {
  19105. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19106. }
  19107. }
  19108. }
  19109. }
  19110. /* Faces */
  19111. // Top and bottom faces
  19112. buildLidFaces();
  19113. // Sides faces
  19114. buildSideFaces();
  19115. ///// Internal functions
  19116. function buildLidFaces() {
  19117. if ( bevelEnabled ) {
  19118. var layer = 0 ; // steps + 1
  19119. var offset = vlen * layer;
  19120. // Bottom faces
  19121. for ( i = 0; i < flen; i ++ ) {
  19122. face = faces[ i ];
  19123. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19124. }
  19125. layer = steps + bevelSegments * 2;
  19126. offset = vlen * layer;
  19127. // Top faces
  19128. for ( i = 0; i < flen; i ++ ) {
  19129. face = faces[ i ];
  19130. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19131. }
  19132. } else {
  19133. // Bottom faces
  19134. for ( i = 0; i < flen; i++ ) {
  19135. face = faces[ i ];
  19136. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19137. }
  19138. // Top faces
  19139. for ( i = 0; i < flen; i ++ ) {
  19140. face = faces[ i ];
  19141. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19142. }
  19143. }
  19144. }
  19145. // Create faces for the z-sides of the shape
  19146. function buildSideFaces() {
  19147. var layeroffset = 0;
  19148. sidewalls( contour, layeroffset );
  19149. layeroffset += contour.length;
  19150. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19151. ahole = holes[ h ];
  19152. sidewalls( ahole, layeroffset );
  19153. //, true
  19154. layeroffset += ahole.length;
  19155. }
  19156. }
  19157. function sidewalls( contour, layeroffset ) {
  19158. var j, k;
  19159. i = contour.length;
  19160. while ( --i >= 0 ) {
  19161. j = i;
  19162. k = i - 1;
  19163. if ( k < 0 ) k = contour.length - 1;
  19164. //console.log('b', i,j, i-1, k,vertices.length);
  19165. var s = 0, sl = steps + bevelSegments * 2;
  19166. for ( s = 0; s < sl; s ++ ) {
  19167. var slen1 = vlen * s;
  19168. var slen2 = vlen * ( s + 1 );
  19169. var a = layeroffset + j + slen1,
  19170. b = layeroffset + k + slen1,
  19171. c = layeroffset + k + slen2,
  19172. d = layeroffset + j + slen2;
  19173. f4( a, b, c, d, contour, s, sl, j, k );
  19174. }
  19175. }
  19176. }
  19177. function v( x, y, z ) {
  19178. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19179. }
  19180. function f3( a, b, c, isBottom ) {
  19181. a += shapesOffset;
  19182. b += shapesOffset;
  19183. c += shapesOffset;
  19184. // normal, color, material
  19185. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19186. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19187. scope.faceVertexUvs[ 0 ].push( uvs );
  19188. }
  19189. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19190. a += shapesOffset;
  19191. b += shapesOffset;
  19192. c += shapesOffset;
  19193. d += shapesOffset;
  19194. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  19195. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  19196. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19197. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19198. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  19199. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  19200. }
  19201. };
  19202. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19203. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19204. var ax = geometry.vertices[ indexA ].x,
  19205. ay = geometry.vertices[ indexA ].y,
  19206. bx = geometry.vertices[ indexB ].x,
  19207. by = geometry.vertices[ indexB ].y,
  19208. cx = geometry.vertices[ indexC ].x,
  19209. cy = geometry.vertices[ indexC ].y;
  19210. return [
  19211. new THREE.Vector2( ax, ay ),
  19212. new THREE.Vector2( bx, by ),
  19213. new THREE.Vector2( cx, cy )
  19214. ];
  19215. },
  19216. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19217. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19218. },
  19219. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19220. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19221. contourIndex1, contourIndex2 ) {
  19222. var ax = geometry.vertices[ indexA ].x,
  19223. ay = geometry.vertices[ indexA ].y,
  19224. az = geometry.vertices[ indexA ].z,
  19225. bx = geometry.vertices[ indexB ].x,
  19226. by = geometry.vertices[ indexB ].y,
  19227. bz = geometry.vertices[ indexB ].z,
  19228. cx = geometry.vertices[ indexC ].x,
  19229. cy = geometry.vertices[ indexC ].y,
  19230. cz = geometry.vertices[ indexC ].z,
  19231. dx = geometry.vertices[ indexD ].x,
  19232. dy = geometry.vertices[ indexD ].y,
  19233. dz = geometry.vertices[ indexD ].z;
  19234. if ( Math.abs( ay - by ) < 0.01 ) {
  19235. return [
  19236. new THREE.Vector2( ax, 1 - az ),
  19237. new THREE.Vector2( bx, 1 - bz ),
  19238. new THREE.Vector2( cx, 1 - cz ),
  19239. new THREE.Vector2( dx, 1 - dz )
  19240. ];
  19241. } else {
  19242. return [
  19243. new THREE.Vector2( ay, 1 - az ),
  19244. new THREE.Vector2( by, 1 - bz ),
  19245. new THREE.Vector2( cy, 1 - cz ),
  19246. new THREE.Vector2( dy, 1 - dz )
  19247. ];
  19248. }
  19249. }
  19250. };
  19251. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19252. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19253. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19254. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19255. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19256. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19257. /**
  19258. * @author jonobr1 / http://jonobr1.com
  19259. *
  19260. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19261. * ExtrudeGeometry.
  19262. *
  19263. * parameters = {
  19264. *
  19265. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19266. *
  19267. * material: <int> // material index for front and back faces
  19268. * uvGenerator: <Object> // object that provides UV generator functions
  19269. *
  19270. * }
  19271. **/
  19272. THREE.ShapeGeometry = function ( shapes, options ) {
  19273. THREE.Geometry.call( this );
  19274. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19275. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19276. this.addShapeList( shapes, options );
  19277. this.computeCentroids();
  19278. this.computeFaceNormals();
  19279. };
  19280. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19281. /**
  19282. * Add an array of shapes to THREE.ShapeGeometry.
  19283. */
  19284. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19285. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19286. this.addShape( shapes[ i ], options );
  19287. }
  19288. return this;
  19289. };
  19290. /**
  19291. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19292. */
  19293. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19294. if ( options === undefined ) options = {};
  19295. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19296. var material = options.material;
  19297. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19298. var shapebb = this.shapebb;
  19299. //
  19300. var i, l, hole, s;
  19301. var shapesOffset = this.vertices.length;
  19302. var shapePoints = shape.extractPoints( curveSegments );
  19303. var vertices = shapePoints.shape;
  19304. var holes = shapePoints.holes;
  19305. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19306. if ( reverse ) {
  19307. vertices = vertices.reverse();
  19308. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19309. for ( i = 0, l = holes.length; i < l; i++ ) {
  19310. hole = holes[ i ];
  19311. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19312. holes[ i ] = hole.reverse();
  19313. }
  19314. }
  19315. reverse = false;
  19316. }
  19317. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19318. // Vertices
  19319. var contour = vertices;
  19320. for ( i = 0, l = holes.length; i < l; i++ ) {
  19321. hole = holes[ i ];
  19322. vertices = vertices.concat( hole );
  19323. }
  19324. //
  19325. var vert, vlen = vertices.length;
  19326. var face, flen = faces.length;
  19327. var cont, clen = contour.length;
  19328. for ( i = 0; i < vlen; i++ ) {
  19329. vert = vertices[ i ];
  19330. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19331. }
  19332. for ( i = 0; i < flen; i++ ) {
  19333. face = faces[ i ];
  19334. var a = face[ 0 ] + shapesOffset;
  19335. var b = face[ 1 ] + shapesOffset;
  19336. var c = face[ 2 ] + shapesOffset;
  19337. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19338. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19339. }
  19340. };
  19341. /**
  19342. * @author astrodud / http://astrodud.isgreat.org/
  19343. * @author zz85 / https://github.com/zz85
  19344. * @author bhouston / http://exocortex.com
  19345. */
  19346. // points - to create a closed torus, one must use a set of points
  19347. // like so: [ a, b, c, d, a ], see first is the same as last.
  19348. // segments - the number of circumference segments to create
  19349. // phiStart - the starting radian
  19350. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19351. // 2*pi is a closed lathe, less than 2PI is a portion.
  19352. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19353. THREE.Geometry.call( this );
  19354. segments = segments || 12;
  19355. phiStart = phiStart || 0;
  19356. phiLength = phiLength || 2 * Math.PI;
  19357. var inversePointLength = 1.0 / ( points.length - 1 );
  19358. var inverseSegments = 1.0 / segments;
  19359. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19360. var phi = phiStart + i * inverseSegments * phiLength;
  19361. var c = Math.cos( phi ),
  19362. s = Math.sin( phi );
  19363. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19364. var pt = points[ j ];
  19365. var vertex = new THREE.Vector3();
  19366. vertex.x = c * pt.x - s * pt.y;
  19367. vertex.y = s * pt.x + c * pt.y;
  19368. vertex.z = pt.z;
  19369. this.vertices.push( vertex );
  19370. }
  19371. }
  19372. var np = points.length;
  19373. for ( var i = 0, il = segments; i < il; i ++ ) {
  19374. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19375. var base = j + np * i;
  19376. var a = base;
  19377. var b = base + np;
  19378. var c = base + 1 + np;
  19379. var d = base + 1;
  19380. var u0 = i * inverseSegments;
  19381. var v0 = j * inversePointLength;
  19382. var u1 = u0 + inverseSegments;
  19383. var v1 = v0 + inversePointLength;
  19384. this.faces.push( new THREE.Face3( a, b, d ) );
  19385. this.faceVertexUvs[ 0 ].push( [
  19386. new THREE.Vector2( u0, v0 ),
  19387. new THREE.Vector2( u1, v0 ),
  19388. new THREE.Vector2( u0, v1 )
  19389. ] );
  19390. this.faces.push( new THREE.Face3( b, c, d ) );
  19391. this.faceVertexUvs[ 0 ].push( [
  19392. new THREE.Vector2( u1, v0 ),
  19393. new THREE.Vector2( u1, v1 ),
  19394. new THREE.Vector2( u0, v1 )
  19395. ] );
  19396. }
  19397. }
  19398. this.mergeVertices();
  19399. this.computeCentroids();
  19400. this.computeFaceNormals();
  19401. this.computeVertexNormals();
  19402. };
  19403. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19404. /**
  19405. * @author mrdoob / http://mrdoob.com/
  19406. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19407. */
  19408. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19409. THREE.Geometry.call( this );
  19410. this.width = width;
  19411. this.height = height;
  19412. this.widthSegments = widthSegments || 1;
  19413. this.heightSegments = heightSegments || 1;
  19414. var ix, iz;
  19415. var width_half = width / 2;
  19416. var height_half = height / 2;
  19417. var gridX = this.widthSegments;
  19418. var gridZ = this.heightSegments;
  19419. var gridX1 = gridX + 1;
  19420. var gridZ1 = gridZ + 1;
  19421. var segment_width = this.width / gridX;
  19422. var segment_height = this.height / gridZ;
  19423. var normal = new THREE.Vector3( 0, 0, 1 );
  19424. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19425. for ( ix = 0; ix < gridX1; ix ++ ) {
  19426. var x = ix * segment_width - width_half;
  19427. var y = iz * segment_height - height_half;
  19428. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19429. }
  19430. }
  19431. for ( iz = 0; iz < gridZ; iz ++ ) {
  19432. for ( ix = 0; ix < gridX; ix ++ ) {
  19433. var a = ix + gridX1 * iz;
  19434. var b = ix + gridX1 * ( iz + 1 );
  19435. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19436. var d = ( ix + 1 ) + gridX1 * iz;
  19437. var uva = new THREE.Vector2( ix / gridX, 1 - iz / gridZ );
  19438. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ );
  19439. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ );
  19440. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ );
  19441. var face = new THREE.Face3( a, b, d );
  19442. face.normal.copy( normal );
  19443. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19444. this.faces.push( face );
  19445. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19446. face = new THREE.Face3( b, c, d );
  19447. face.normal.copy( normal );
  19448. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19449. this.faces.push( face );
  19450. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19451. }
  19452. }
  19453. this.computeCentroids();
  19454. };
  19455. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19456. /**
  19457. * @author Kaleb Murphy
  19458. */
  19459. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19460. THREE.Geometry.call( this );
  19461. innerRadius = innerRadius || 0;
  19462. outerRadius = outerRadius || 50;
  19463. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19464. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19465. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19466. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19467. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19468. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19469. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19470. var vertex = new THREE.Vector3();
  19471. var segment = thetaStart + o / thetaSegments * thetaLength;
  19472. vertex.x = radius * Math.cos( segment );
  19473. vertex.y = radius * Math.sin( segment );
  19474. this.vertices.push( vertex );
  19475. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  19476. }
  19477. radius += radiusStep;
  19478. }
  19479. var n = new THREE.Vector3( 0, 0, 1 );
  19480. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19481. var thetaSegment = i * thetaSegments;
  19482. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19483. var segment = o + thetaSegment;
  19484. var v1 = segment + i;
  19485. var v2 = segment + thetaSegments + i;
  19486. var v3 = segment + thetaSegments + 1 + i;
  19487. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19488. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19489. v1 = segment + i;
  19490. v2 = segment + thetaSegments + 1 + i;
  19491. v3 = segment + 1 + i;
  19492. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19493. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19494. }
  19495. }
  19496. this.computeCentroids();
  19497. this.computeFaceNormals();
  19498. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19499. };
  19500. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19501. /**
  19502. * @author mrdoob / http://mrdoob.com/
  19503. */
  19504. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19505. THREE.Geometry.call( this );
  19506. this.radius = radius = radius || 50;
  19507. this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19508. this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19509. this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0;
  19510. this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19511. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19512. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19513. var x, y, vertices = [], uvs = [];
  19514. for ( y = 0; y <= heightSegments; y ++ ) {
  19515. var verticesRow = [];
  19516. var uvsRow = [];
  19517. for ( x = 0; x <= widthSegments; x ++ ) {
  19518. var u = x / widthSegments;
  19519. var v = y / heightSegments;
  19520. var vertex = new THREE.Vector3();
  19521. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19522. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19523. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19524. this.vertices.push( vertex );
  19525. verticesRow.push( this.vertices.length - 1 );
  19526. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19527. }
  19528. vertices.push( verticesRow );
  19529. uvs.push( uvsRow );
  19530. }
  19531. for ( y = 0; y < this.heightSegments; y ++ ) {
  19532. for ( x = 0; x < this.widthSegments; x ++ ) {
  19533. var v1 = vertices[ y ][ x + 1 ];
  19534. var v2 = vertices[ y ][ x ];
  19535. var v3 = vertices[ y + 1 ][ x ];
  19536. var v4 = vertices[ y + 1 ][ x + 1 ];
  19537. var n1 = this.vertices[ v1 ].clone().normalize();
  19538. var n2 = this.vertices[ v2 ].clone().normalize();
  19539. var n3 = this.vertices[ v3 ].clone().normalize();
  19540. var n4 = this.vertices[ v4 ].clone().normalize();
  19541. var uv1 = uvs[ y ][ x + 1 ].clone();
  19542. var uv2 = uvs[ y ][ x ].clone();
  19543. var uv3 = uvs[ y + 1 ][ x ].clone();
  19544. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19545. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19546. uv1.x = ( uv1.x + uv2.x ) / 2;
  19547. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19548. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19549. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19550. uv3.x = ( uv3.x + uv4.x ) / 2;
  19551. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19552. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19553. } else {
  19554. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19555. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19556. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19557. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19558. }
  19559. }
  19560. }
  19561. this.computeCentroids();
  19562. this.computeFaceNormals();
  19563. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19564. };
  19565. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19566. /**
  19567. * @author zz85 / http://www.lab4games.net/zz85/blog
  19568. * @author alteredq / http://alteredqualia.com/
  19569. *
  19570. * For creating 3D text geometry in three.js
  19571. *
  19572. * Text = 3D Text
  19573. *
  19574. * parameters = {
  19575. * size: <float>, // size of the text
  19576. * height: <float>, // thickness to extrude text
  19577. * curveSegments: <int>, // number of points on the curves
  19578. *
  19579. * font: <string>, // font name
  19580. * weight: <string>, // font weight (normal, bold)
  19581. * style: <string>, // font style (normal, italics)
  19582. *
  19583. * bevelEnabled: <bool>, // turn on bevel
  19584. * bevelThickness: <float>, // how deep into text bevel goes
  19585. * bevelSize: <float>, // how far from text outline is bevel
  19586. * }
  19587. *
  19588. */
  19589. /* Usage Examples
  19590. // TextGeometry wrapper
  19591. var text3d = new TextGeometry( text, options );
  19592. // Complete manner
  19593. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19594. var text3d = new ExtrudeGeometry( textShapes, options );
  19595. */
  19596. THREE.TextGeometry = function ( text, parameters ) {
  19597. parameters = parameters || {};
  19598. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19599. // translate parameters to ExtrudeGeometry API
  19600. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19601. // defaults
  19602. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19603. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19604. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19605. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19606. };
  19607. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19608. /**
  19609. * @author oosmoxiecode
  19610. * @author mrdoob / http://mrdoob.com/
  19611. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19612. */
  19613. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19614. THREE.Geometry.call( this );
  19615. var scope = this;
  19616. this.radius = radius || 100;
  19617. this.tube = tube || 40;
  19618. this.radialSegments = radialSegments || 8;
  19619. this.tubularSegments = tubularSegments || 6;
  19620. this.arc = arc || Math.PI * 2;
  19621. var center = new THREE.Vector3(), uvs = [], normals = [];
  19622. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19623. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19624. var u = i / this.tubularSegments * this.arc;
  19625. var v = j / this.radialSegments * Math.PI * 2;
  19626. center.x = this.radius * Math.cos( u );
  19627. center.y = this.radius * Math.sin( u );
  19628. var vertex = new THREE.Vector3();
  19629. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19630. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19631. vertex.z = this.tube * Math.sin( v );
  19632. this.vertices.push( vertex );
  19633. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19634. normals.push( vertex.clone().sub( center ).normalize() );
  19635. }
  19636. }
  19637. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19638. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19639. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19640. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19641. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19642. var d = ( this.tubularSegments + 1 ) * j + i;
  19643. var face = new THREE.Face3( a, b, d, [ normals[ a ], normals[ b ], normals[ d ] ] );
  19644. face.normal.add( normals[ a ] );
  19645. face.normal.add( normals[ b ] );
  19646. face.normal.add( normals[ d ] );
  19647. face.normal.normalize();
  19648. this.faces.push( face );
  19649. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  19650. face = new THREE.Face3( b, c, d, [ normals[ b ], normals[ c ], normals[ d ] ] );
  19651. face.normal.add( normals[ b ] );
  19652. face.normal.add( normals[ c ] );
  19653. face.normal.add( normals[ d ] );
  19654. face.normal.normalize();
  19655. this.faces.push( face );
  19656. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19657. }
  19658. }
  19659. this.computeCentroids();
  19660. };
  19661. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19662. /**
  19663. * @author oosmoxiecode
  19664. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19665. */
  19666. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19667. THREE.Geometry.call( this );
  19668. var scope = this;
  19669. this.radius = radius || 100;
  19670. this.tube = tube || 40;
  19671. this.radialSegments = radialSegments || 64;
  19672. this.tubularSegments = tubularSegments || 8;
  19673. this.p = p || 2;
  19674. this.q = q || 3;
  19675. this.heightScale = heightScale || 1;
  19676. this.grid = new Array( this.radialSegments );
  19677. var tang = new THREE.Vector3();
  19678. var n = new THREE.Vector3();
  19679. var bitan = new THREE.Vector3();
  19680. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19681. this.grid[ i ] = new Array( this.tubularSegments );
  19682. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19683. var p1 = getPos( u, this.q, this.p, this.radius, this.heightScale );
  19684. var p2 = getPos( u + 0.01, this.q, this.p, this.radius, this.heightScale );
  19685. tang.subVectors( p2, p1 );
  19686. n.addVectors( p2, p1 );
  19687. bitan.crossVectors( tang, n );
  19688. n.crossVectors( bitan, tang );
  19689. bitan.normalize();
  19690. n.normalize();
  19691. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19692. var v = j / this.tubularSegments * 2 * Math.PI;
  19693. var cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19694. var cy = this.tube * Math.sin( v );
  19695. var pos = new THREE.Vector3();
  19696. pos.x = p1.x + cx * n.x + cy * bitan.x;
  19697. pos.y = p1.y + cx * n.y + cy * bitan.y;
  19698. pos.z = p1.z + cx * n.z + cy * bitan.z;
  19699. this.grid[ i ][ j ] = scope.vertices.push( pos ) - 1;
  19700. }
  19701. }
  19702. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19703. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19704. var ip = ( i + 1 ) % this.radialSegments;
  19705. var jp = ( j + 1 ) % this.tubularSegments;
  19706. var a = this.grid[ i ][ j ];
  19707. var b = this.grid[ ip ][ j ];
  19708. var c = this.grid[ ip ][ jp ];
  19709. var d = this.grid[ i ][ jp ];
  19710. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19711. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19712. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19713. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19714. this.faces.push( new THREE.Face3( a, b, d ) );
  19715. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19716. this.faces.push( new THREE.Face3( b, c, d ) );
  19717. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19718. }
  19719. }
  19720. this.computeCentroids();
  19721. this.computeFaceNormals();
  19722. this.computeVertexNormals();
  19723. function getPos( u, in_q, in_p, radius, heightScale ) {
  19724. var cu = Math.cos( u );
  19725. var su = Math.sin( u );
  19726. var quOverP = in_q / in_p * u;
  19727. var cs = Math.cos( quOverP );
  19728. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19729. var ty = radius * ( 2 + cs ) * su * 0.5;
  19730. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19731. return new THREE.Vector3( tx, ty, tz );
  19732. }
  19733. };
  19734. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19735. /**
  19736. * @author WestLangley / https://github.com/WestLangley
  19737. * @author zz85 / https://github.com/zz85
  19738. * @author miningold / https://github.com/miningold
  19739. *
  19740. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19741. *
  19742. * Creates a tube which extrudes along a 3d spline
  19743. *
  19744. * Uses parallel transport frames as described in
  19745. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19746. */
  19747. THREE.TubeGeometry = function( path, segments, radius, radialSegments, closed ) {
  19748. THREE.Geometry.call( this );
  19749. this.path = path;
  19750. this.segments = segments || 64;
  19751. this.radius = radius || 1;
  19752. this.radialSegments = radialSegments || 8;
  19753. this.closed = closed || false;
  19754. this.grid = [];
  19755. var scope = this,
  19756. tangent,
  19757. normal,
  19758. binormal,
  19759. numpoints = this.segments + 1,
  19760. x, y, z,
  19761. tx, ty, tz,
  19762. u, v,
  19763. cx, cy,
  19764. pos, pos2 = new THREE.Vector3(),
  19765. i, j,
  19766. ip, jp,
  19767. a, b, c, d,
  19768. uva, uvb, uvc, uvd;
  19769. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19770. tangents = frames.tangents,
  19771. normals = frames.normals,
  19772. binormals = frames.binormals;
  19773. // proxy internals
  19774. this.tangents = tangents;
  19775. this.normals = normals;
  19776. this.binormals = binormals;
  19777. function vert( x, y, z ) {
  19778. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19779. }
  19780. // consruct the grid
  19781. for ( i = 0; i < numpoints; i++ ) {
  19782. this.grid[ i ] = [];
  19783. u = i / ( numpoints - 1 );
  19784. pos = path.getPointAt( u );
  19785. tangent = tangents[ i ];
  19786. normal = normals[ i ];
  19787. binormal = binormals[ i ];
  19788. for ( j = 0; j < this.radialSegments; j++ ) {
  19789. v = j / this.radialSegments * 2 * Math.PI;
  19790. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19791. cy = this.radius * Math.sin( v );
  19792. pos2.copy( pos );
  19793. pos2.x += cx * normal.x + cy * binormal.x;
  19794. pos2.y += cx * normal.y + cy * binormal.y;
  19795. pos2.z += cx * normal.z + cy * binormal.z;
  19796. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19797. }
  19798. }
  19799. // construct the mesh
  19800. for ( i = 0; i < this.segments; i++ ) {
  19801. for ( j = 0; j < this.radialSegments; j++ ) {
  19802. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  19803. jp = (j + 1) % this.radialSegments;
  19804. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19805. b = this.grid[ ip ][ j ];
  19806. c = this.grid[ ip ][ jp ];
  19807. d = this.grid[ i ][ jp ];
  19808. uva = new THREE.Vector2( i / this.segments, j / this.radialSegments );
  19809. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radialSegments );
  19810. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radialSegments );
  19811. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radialSegments );
  19812. this.faces.push( new THREE.Face3( a, b, d ) );
  19813. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19814. this.faces.push( new THREE.Face3( b, c, d ) );
  19815. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19816. }
  19817. }
  19818. this.computeCentroids();
  19819. this.computeFaceNormals();
  19820. this.computeVertexNormals();
  19821. };
  19822. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19823. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19824. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19825. var tangent = new THREE.Vector3(),
  19826. normal = new THREE.Vector3(),
  19827. binormal = new THREE.Vector3(),
  19828. tangents = [],
  19829. normals = [],
  19830. binormals = [],
  19831. vec = new THREE.Vector3(),
  19832. mat = new THREE.Matrix4(),
  19833. numpoints = segments + 1,
  19834. theta,
  19835. epsilon = 0.0001,
  19836. smallest,
  19837. tx, ty, tz,
  19838. i, u, v;
  19839. // expose internals
  19840. this.tangents = tangents;
  19841. this.normals = normals;
  19842. this.binormals = binormals;
  19843. // compute the tangent vectors for each segment on the path
  19844. for ( i = 0; i < numpoints; i++ ) {
  19845. u = i / ( numpoints - 1 );
  19846. tangents[ i ] = path.getTangentAt( u );
  19847. tangents[ i ].normalize();
  19848. }
  19849. initialNormal3();
  19850. function initialNormal1(lastBinormal) {
  19851. // fixed start binormal. Has dangers of 0 vectors
  19852. normals[ 0 ] = new THREE.Vector3();
  19853. binormals[ 0 ] = new THREE.Vector3();
  19854. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19855. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19856. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19857. }
  19858. function initialNormal2() {
  19859. // This uses the Frenet-Serret formula for deriving binormal
  19860. var t2 = path.getTangentAt( epsilon );
  19861. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19862. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19863. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19864. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19865. }
  19866. function initialNormal3() {
  19867. // select an initial normal vector perpenicular to the first tangent vector,
  19868. // and in the direction of the smallest tangent xyz component
  19869. normals[ 0 ] = new THREE.Vector3();
  19870. binormals[ 0 ] = new THREE.Vector3();
  19871. smallest = Number.MAX_VALUE;
  19872. tx = Math.abs( tangents[ 0 ].x );
  19873. ty = Math.abs( tangents[ 0 ].y );
  19874. tz = Math.abs( tangents[ 0 ].z );
  19875. if ( tx <= smallest ) {
  19876. smallest = tx;
  19877. normal.set( 1, 0, 0 );
  19878. }
  19879. if ( ty <= smallest ) {
  19880. smallest = ty;
  19881. normal.set( 0, 1, 0 );
  19882. }
  19883. if ( tz <= smallest ) {
  19884. normal.set( 0, 0, 1 );
  19885. }
  19886. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19887. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19888. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19889. }
  19890. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19891. for ( i = 1; i < numpoints; i++ ) {
  19892. normals[ i ] = normals[ i-1 ].clone();
  19893. binormals[ i ] = binormals[ i-1 ].clone();
  19894. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  19895. if ( vec.length() > epsilon ) {
  19896. vec.normalize();
  19897. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  19898. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19899. }
  19900. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19901. }
  19902. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19903. if ( closed ) {
  19904. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  19905. theta /= ( numpoints - 1 );
  19906. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19907. theta = -theta;
  19908. }
  19909. for ( i = 1; i < numpoints; i++ ) {
  19910. // twist a little...
  19911. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19912. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19913. }
  19914. }
  19915. };
  19916. /**
  19917. * @author clockworkgeek / https://github.com/clockworkgeek
  19918. * @author timothypratley / https://github.com/timothypratley
  19919. * @author WestLangley / http://github.com/WestLangley
  19920. */
  19921. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19922. THREE.Geometry.call( this );
  19923. radius = radius || 1;
  19924. detail = detail || 0;
  19925. var that = this;
  19926. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19927. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19928. }
  19929. var midpoints = [], p = this.vertices;
  19930. var f = [];
  19931. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19932. var v1 = p[ faces[ i ][ 0 ] ];
  19933. var v2 = p[ faces[ i ][ 1 ] ];
  19934. var v3 = p[ faces[ i ][ 2 ] ];
  19935. f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19936. }
  19937. for ( var i = 0, l = f.length; i < l; i ++ ) {
  19938. subdivide(f[ i ], detail);
  19939. }
  19940. // Handle case when face straddles the seam
  19941. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  19942. var uvs = this.faceVertexUvs[ 0 ][ i ];
  19943. var x0 = uvs[ 0 ].x;
  19944. var x1 = uvs[ 1 ].x;
  19945. var x2 = uvs[ 2 ].x;
  19946. var max = Math.max( x0, Math.max( x1, x2 ) );
  19947. var min = Math.min( x0, Math.min( x1, x2 ) );
  19948. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  19949. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  19950. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  19951. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  19952. }
  19953. }
  19954. // Apply radius
  19955. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19956. this.vertices[ i ].multiplyScalar( radius );
  19957. }
  19958. // Merge vertices
  19959. this.mergeVertices();
  19960. this.computeCentroids();
  19961. this.computeFaceNormals();
  19962. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19963. // Project vector onto sphere's surface
  19964. function prepare( vector ) {
  19965. var vertex = vector.normalize().clone();
  19966. vertex.index = that.vertices.push( vertex ) - 1;
  19967. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19968. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19969. var v = inclination( vector ) / Math.PI + 0.5;
  19970. vertex.uv = new THREE.Vector2( u, 1 - v );
  19971. return vertex;
  19972. }
  19973. // Approximate a curved face with recursively sub-divided triangles.
  19974. function make( v1, v2, v3 ) {
  19975. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19976. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19977. that.faces.push( face );
  19978. var azi = azimuth( face.centroid );
  19979. that.faceVertexUvs[ 0 ].push( [
  19980. correctUV( v1.uv, v1, azi ),
  19981. correctUV( v2.uv, v2, azi ),
  19982. correctUV( v3.uv, v3, azi )
  19983. ] );
  19984. }
  19985. // Analytically subdivide a face to the required detail level.
  19986. function subdivide(face, detail ) {
  19987. var cols = Math.pow(2, detail);
  19988. var cells = Math.pow(4, detail);
  19989. var a = prepare( that.vertices[ face.a ] );
  19990. var b = prepare( that.vertices[ face.b ] );
  19991. var c = prepare( that.vertices[ face.c ] );
  19992. var v = [];
  19993. // Construct all of the vertices for this subdivision.
  19994. for ( var i = 0 ; i <= cols; i ++ ) {
  19995. v[ i ] = [];
  19996. var aj = prepare( a.clone().lerp( c, i / cols ) );
  19997. var bj = prepare( b.clone().lerp( c, i / cols ) );
  19998. var rows = cols - i;
  19999. for ( var j = 0; j <= rows; j ++) {
  20000. if ( j == 0 && i == cols ) {
  20001. v[ i ][ j ] = aj;
  20002. } else {
  20003. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  20004. }
  20005. }
  20006. }
  20007. // Construct all of the faces.
  20008. for ( var i = 0; i < cols ; i ++ ) {
  20009. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  20010. var k = Math.floor( j / 2 );
  20011. if ( j % 2 == 0 ) {
  20012. make(
  20013. v[ i ][ k + 1],
  20014. v[ i + 1 ][ k ],
  20015. v[ i ][ k ]
  20016. );
  20017. } else {
  20018. make(
  20019. v[ i ][ k + 1 ],
  20020. v[ i + 1][ k + 1],
  20021. v[ i + 1 ][ k ]
  20022. );
  20023. }
  20024. }
  20025. }
  20026. }
  20027. // Angle around the Y axis, counter-clockwise when looking from above.
  20028. function azimuth( vector ) {
  20029. return Math.atan2( vector.z, -vector.x );
  20030. }
  20031. // Angle above the XZ plane.
  20032. function inclination( vector ) {
  20033. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20034. }
  20035. // Texture fixing helper. Spheres have some odd behaviours.
  20036. function correctUV( uv, vector, azimuth ) {
  20037. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  20038. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  20039. return uv.clone();
  20040. }
  20041. };
  20042. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20043. /**
  20044. * @author timothypratley / https://github.com/timothypratley
  20045. */
  20046. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20047. this.radius = radius;
  20048. this.detail = detail;
  20049. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20050. var vertices = [
  20051. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  20052. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  20053. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  20054. ];
  20055. var faces = [
  20056. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  20057. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  20058. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  20059. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  20060. ];
  20061. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20062. };
  20063. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20064. /**
  20065. * @author timothypratley / https://github.com/timothypratley
  20066. */
  20067. THREE.OctahedronGeometry = function ( radius, detail ) {
  20068. var vertices = [
  20069. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  20070. ];
  20071. var faces = [
  20072. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  20073. ];
  20074. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20075. };
  20076. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20077. /**
  20078. * @author timothypratley / https://github.com/timothypratley
  20079. */
  20080. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20081. var vertices = [
  20082. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  20083. ];
  20084. var faces = [
  20085. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  20086. ];
  20087. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20088. };
  20089. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20090. /**
  20091. * @author zz85 / https://github.com/zz85
  20092. * Parametric Surfaces Geometry
  20093. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20094. *
  20095. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  20096. *
  20097. */
  20098. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  20099. THREE.Geometry.call( this );
  20100. var verts = this.vertices;
  20101. var faces = this.faces;
  20102. var uvs = this.faceVertexUvs[ 0 ];
  20103. var i, il, j, p;
  20104. var u, v;
  20105. var stackCount = stacks + 1;
  20106. var sliceCount = slices + 1;
  20107. for ( i = 0; i <= stacks; i ++ ) {
  20108. v = i / stacks;
  20109. for ( j = 0; j <= slices; j ++ ) {
  20110. u = j / slices;
  20111. p = func( u, v );
  20112. verts.push( p );
  20113. }
  20114. }
  20115. var a, b, c, d;
  20116. var uva, uvb, uvc, uvd;
  20117. for ( i = 0; i < stacks; i ++ ) {
  20118. for ( j = 0; j < slices; j ++ ) {
  20119. a = i * sliceCount + j;
  20120. b = i * sliceCount + j + 1;
  20121. c = (i + 1) * sliceCount + j + 1;
  20122. d = (i + 1) * sliceCount + j;
  20123. uva = new THREE.Vector2( j / slices, i / stacks );
  20124. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20125. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20126. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20127. faces.push( new THREE.Face3( a, b, d ) );
  20128. uvs.push( [ uva, uvb, uvd ] );
  20129. faces.push( new THREE.Face3( b, c, d ) );
  20130. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  20131. }
  20132. }
  20133. // console.log(this);
  20134. // magic bullet
  20135. // var diff = this.mergeVertices();
  20136. // console.log('removed ', diff, ' vertices by merging');
  20137. this.computeCentroids();
  20138. this.computeFaceNormals();
  20139. this.computeVertexNormals();
  20140. };
  20141. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20142. /**
  20143. * @author sroucheray / http://sroucheray.org/
  20144. * @author mrdoob / http://mrdoob.com/
  20145. */
  20146. THREE.AxisHelper = function ( size ) {
  20147. size = size || 1;
  20148. var geometry = new THREE.Geometry();
  20149. geometry.vertices.push(
  20150. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  20151. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  20152. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  20153. );
  20154. geometry.colors.push(
  20155. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20156. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20157. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20158. );
  20159. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20160. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20161. };
  20162. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20163. /**
  20164. * @author WestLangley / http://github.com/WestLangley
  20165. * @author zz85 / http://github.com/zz85
  20166. * @author bhouston / http://exocortex.com
  20167. *
  20168. * Creates an arrow for visualizing directions
  20169. *
  20170. * Parameters:
  20171. * dir - Vector3
  20172. * origin - Vector3
  20173. * length - Number
  20174. * hex - color in hex value
  20175. * headLength - Number
  20176. * headWidth - Number
  20177. */
  20178. THREE.ArrowHelper = function ( dir, origin, length, hex, headLength, headWidth ) {
  20179. // dir is assumed to be normalized
  20180. THREE.Object3D.call( this );
  20181. if ( hex === undefined ) hex = 0xffff00;
  20182. if ( length === undefined ) length = 1;
  20183. if ( headLength === undefined ) headLength = 0.2 * length;
  20184. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20185. this.position = origin;
  20186. var lineGeometry = new THREE.Geometry();
  20187. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20188. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20189. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20190. this.line.matrixAutoUpdate = false;
  20191. this.add( this.line );
  20192. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  20193. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  20194. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20195. this.cone.matrixAutoUpdate = false;
  20196. this.add( this.cone );
  20197. this.setDirection( dir );
  20198. this.setLength( length, headLength, headWidth );
  20199. };
  20200. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20201. THREE.ArrowHelper.prototype.setDirection = function () {
  20202. var axis = new THREE.Vector3();
  20203. var radians;
  20204. return function ( dir ) {
  20205. // dir is assumed to be normalized
  20206. if ( dir.y > 0.99999 ) {
  20207. this.quaternion.set( 0, 0, 0, 1 );
  20208. } else if ( dir.y < - 0.99999 ) {
  20209. this.quaternion.set( 1, 0, 0, 0 );
  20210. } else {
  20211. axis.set( dir.z, 0, - dir.x ).normalize();
  20212. radians = Math.acos( dir.y );
  20213. this.quaternion.setFromAxisAngle( axis, radians );
  20214. }
  20215. };
  20216. }();
  20217. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  20218. if ( headLength === undefined ) headLength = 0.2 * length;
  20219. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20220. this.line.scale.set( 1, length, 1 );
  20221. this.line.updateMatrix();
  20222. this.cone.scale.set( headWidth, headLength, headWidth );
  20223. this.cone.position.y = length;
  20224. this.cone.updateMatrix();
  20225. };
  20226. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20227. this.line.material.color.setHex( hex );
  20228. this.cone.material.color.setHex( hex );
  20229. };
  20230. /**
  20231. * @author mrdoob / http://mrdoob.com/
  20232. */
  20233. THREE.BoxHelper = function ( object ) {
  20234. // 5____4
  20235. // 1/___0/|
  20236. // | 6__|_7
  20237. // 2/___3/
  20238. var vertices = [
  20239. new THREE.Vector3( 1, 1, 1 ),
  20240. new THREE.Vector3( - 1, 1, 1 ),
  20241. new THREE.Vector3( - 1, - 1, 1 ),
  20242. new THREE.Vector3( 1, - 1, 1 ),
  20243. new THREE.Vector3( 1, 1, - 1 ),
  20244. new THREE.Vector3( - 1, 1, - 1 ),
  20245. new THREE.Vector3( - 1, - 1, - 1 ),
  20246. new THREE.Vector3( 1, - 1, - 1 )
  20247. ];
  20248. this.vertices = vertices;
  20249. // TODO: Wouldn't be nice if Line had .segments?
  20250. var geometry = new THREE.Geometry();
  20251. geometry.vertices.push(
  20252. vertices[ 0 ], vertices[ 1 ],
  20253. vertices[ 1 ], vertices[ 2 ],
  20254. vertices[ 2 ], vertices[ 3 ],
  20255. vertices[ 3 ], vertices[ 0 ],
  20256. vertices[ 4 ], vertices[ 5 ],
  20257. vertices[ 5 ], vertices[ 6 ],
  20258. vertices[ 6 ], vertices[ 7 ],
  20259. vertices[ 7 ], vertices[ 4 ],
  20260. vertices[ 0 ], vertices[ 4 ],
  20261. vertices[ 1 ], vertices[ 5 ],
  20262. vertices[ 2 ], vertices[ 6 ],
  20263. vertices[ 3 ], vertices[ 7 ]
  20264. );
  20265. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20266. if ( object !== undefined ) {
  20267. this.update( object );
  20268. }
  20269. };
  20270. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20271. THREE.BoxHelper.prototype.update = function ( object ) {
  20272. var geometry = object.geometry;
  20273. if ( geometry.boundingBox === null ) {
  20274. geometry.computeBoundingBox();
  20275. }
  20276. var min = geometry.boundingBox.min;
  20277. var max = geometry.boundingBox.max;
  20278. var vertices = this.vertices;
  20279. vertices[ 0 ].set( max.x, max.y, max.z );
  20280. vertices[ 1 ].set( min.x, max.y, max.z );
  20281. vertices[ 2 ].set( min.x, min.y, max.z );
  20282. vertices[ 3 ].set( max.x, min.y, max.z );
  20283. vertices[ 4 ].set( max.x, max.y, min.z );
  20284. vertices[ 5 ].set( min.x, max.y, min.z );
  20285. vertices[ 6 ].set( min.x, min.y, min.z );
  20286. vertices[ 7 ].set( max.x, min.y, min.z );
  20287. this.geometry.computeBoundingSphere();
  20288. this.geometry.verticesNeedUpdate = true;
  20289. this.matrixAutoUpdate = false;
  20290. this.matrixWorld = object.matrixWorld;
  20291. };
  20292. /**
  20293. * @author WestLangley / http://github.com/WestLangley
  20294. */
  20295. // a helper to show the world-axis-aligned bounding box for an object
  20296. THREE.BoundingBoxHelper = function ( object, hex ) {
  20297. var color = hex || 0x888888;
  20298. this.object = object;
  20299. this.box = new THREE.Box3();
  20300. THREE.Mesh.call( this, new THREE.CubeGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20301. };
  20302. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20303. THREE.BoundingBoxHelper.prototype.update = function () {
  20304. this.box.setFromObject( this.object );
  20305. this.box.size( this.scale );
  20306. this.box.center( this.position );
  20307. };
  20308. /**
  20309. * @author alteredq / http://alteredqualia.com/
  20310. *
  20311. * - shows frustum, line of sight and up of the camera
  20312. * - suitable for fast updates
  20313. * - based on frustum visualization in lightgl.js shadowmap example
  20314. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20315. */
  20316. THREE.CameraHelper = function ( camera ) {
  20317. var geometry = new THREE.Geometry();
  20318. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20319. var pointMap = {};
  20320. // colors
  20321. var hexFrustum = 0xffaa00;
  20322. var hexCone = 0xff0000;
  20323. var hexUp = 0x00aaff;
  20324. var hexTarget = 0xffffff;
  20325. var hexCross = 0x333333;
  20326. // near
  20327. addLine( "n1", "n2", hexFrustum );
  20328. addLine( "n2", "n4", hexFrustum );
  20329. addLine( "n4", "n3", hexFrustum );
  20330. addLine( "n3", "n1", hexFrustum );
  20331. // far
  20332. addLine( "f1", "f2", hexFrustum );
  20333. addLine( "f2", "f4", hexFrustum );
  20334. addLine( "f4", "f3", hexFrustum );
  20335. addLine( "f3", "f1", hexFrustum );
  20336. // sides
  20337. addLine( "n1", "f1", hexFrustum );
  20338. addLine( "n2", "f2", hexFrustum );
  20339. addLine( "n3", "f3", hexFrustum );
  20340. addLine( "n4", "f4", hexFrustum );
  20341. // cone
  20342. addLine( "p", "n1", hexCone );
  20343. addLine( "p", "n2", hexCone );
  20344. addLine( "p", "n3", hexCone );
  20345. addLine( "p", "n4", hexCone );
  20346. // up
  20347. addLine( "u1", "u2", hexUp );
  20348. addLine( "u2", "u3", hexUp );
  20349. addLine( "u3", "u1", hexUp );
  20350. // target
  20351. addLine( "c", "t", hexTarget );
  20352. addLine( "p", "c", hexCross );
  20353. // cross
  20354. addLine( "cn1", "cn2", hexCross );
  20355. addLine( "cn3", "cn4", hexCross );
  20356. addLine( "cf1", "cf2", hexCross );
  20357. addLine( "cf3", "cf4", hexCross );
  20358. function addLine( a, b, hex ) {
  20359. addPoint( a, hex );
  20360. addPoint( b, hex );
  20361. }
  20362. function addPoint( id, hex ) {
  20363. geometry.vertices.push( new THREE.Vector3() );
  20364. geometry.colors.push( new THREE.Color( hex ) );
  20365. if ( pointMap[ id ] === undefined ) {
  20366. pointMap[ id ] = [];
  20367. }
  20368. pointMap[ id ].push( geometry.vertices.length - 1 );
  20369. }
  20370. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20371. this.camera = camera;
  20372. this.matrixWorld = camera.matrixWorld;
  20373. this.matrixAutoUpdate = false;
  20374. this.pointMap = pointMap;
  20375. this.update();
  20376. };
  20377. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20378. THREE.CameraHelper.prototype.update = function () {
  20379. var vector = new THREE.Vector3();
  20380. var camera = new THREE.Camera();
  20381. var projector = new THREE.Projector();
  20382. return function () {
  20383. var scope = this;
  20384. var w = 1, h = 1;
  20385. // we need just camera projection matrix
  20386. // world matrix must be identity
  20387. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20388. // center / target
  20389. setPoint( "c", 0, 0, -1 );
  20390. setPoint( "t", 0, 0, 1 );
  20391. // near
  20392. setPoint( "n1", -w, -h, -1 );
  20393. setPoint( "n2", w, -h, -1 );
  20394. setPoint( "n3", -w, h, -1 );
  20395. setPoint( "n4", w, h, -1 );
  20396. // far
  20397. setPoint( "f1", -w, -h, 1 );
  20398. setPoint( "f2", w, -h, 1 );
  20399. setPoint( "f3", -w, h, 1 );
  20400. setPoint( "f4", w, h, 1 );
  20401. // up
  20402. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20403. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20404. setPoint( "u3", 0, h * 2, -1 );
  20405. // cross
  20406. setPoint( "cf1", -w, 0, 1 );
  20407. setPoint( "cf2", w, 0, 1 );
  20408. setPoint( "cf3", 0, -h, 1 );
  20409. setPoint( "cf4", 0, h, 1 );
  20410. setPoint( "cn1", -w, 0, -1 );
  20411. setPoint( "cn2", w, 0, -1 );
  20412. setPoint( "cn3", 0, -h, -1 );
  20413. setPoint( "cn4", 0, h, -1 );
  20414. function setPoint( point, x, y, z ) {
  20415. vector.set( x, y, z );
  20416. projector.unprojectVector( vector, camera );
  20417. var points = scope.pointMap[ point ];
  20418. if ( points !== undefined ) {
  20419. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20420. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20421. }
  20422. }
  20423. }
  20424. this.geometry.verticesNeedUpdate = true;
  20425. };
  20426. }();
  20427. /**
  20428. * @author alteredq / http://alteredqualia.com/
  20429. * @author mrdoob / http://mrdoob.com/
  20430. * @author WestLangley / http://github.com/WestLangley
  20431. */
  20432. THREE.DirectionalLightHelper = function ( light, size ) {
  20433. THREE.Object3D.call( this );
  20434. this.light = light;
  20435. this.light.updateMatrixWorld();
  20436. this.matrixWorld = light.matrixWorld;
  20437. this.matrixAutoUpdate = false;
  20438. size = size || 1;
  20439. var geometry = new THREE.PlaneGeometry( size, size );
  20440. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20441. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20442. this.lightPlane = new THREE.Mesh( geometry, material );
  20443. this.add( this.lightPlane );
  20444. geometry = new THREE.Geometry();
  20445. geometry.vertices.push( new THREE.Vector3() );
  20446. geometry.vertices.push( new THREE.Vector3() );
  20447. material = new THREE.LineBasicMaterial( { fog: false } );
  20448. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20449. this.targetLine = new THREE.Line( geometry, material );
  20450. this.add( this.targetLine );
  20451. this.update();
  20452. };
  20453. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20454. THREE.DirectionalLightHelper.prototype.dispose = function () {
  20455. this.lightPlane.geometry.dispose();
  20456. this.lightPlane.material.dispose();
  20457. this.targetLine.geometry.dispose();
  20458. this.targetLine.material.dispose();
  20459. };
  20460. THREE.DirectionalLightHelper.prototype.update = function () {
  20461. var v1 = new THREE.Vector3();
  20462. var v2 = new THREE.Vector3();
  20463. var v3 = new THREE.Vector3();
  20464. return function () {
  20465. v1.setFromMatrixPosition( this.light.matrixWorld );
  20466. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20467. v3.subVectors( v2, v1 );
  20468. this.lightPlane.lookAt( v3 );
  20469. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20470. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  20471. this.targetLine.geometry.verticesNeedUpdate = true;
  20472. this.targetLine.material.color.copy( this.lightPlane.material.color );
  20473. }
  20474. }();
  20475. /**
  20476. * @author mrdoob / http://mrdoob.com/
  20477. * @author WestLangley / http://github.com/WestLangley
  20478. */
  20479. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20480. this.object = object;
  20481. this.size = size || 1;
  20482. var color = hex || 0xffff00;
  20483. var width = linewidth || 1;
  20484. var geometry = new THREE.Geometry();
  20485. var faces = this.object.geometry.faces;
  20486. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20487. geometry.vertices.push( new THREE.Vector3() );
  20488. geometry.vertices.push( new THREE.Vector3() );
  20489. }
  20490. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20491. this.matrixAutoUpdate = false;
  20492. this.normalMatrix = new THREE.Matrix3();
  20493. this.update();
  20494. };
  20495. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20496. THREE.FaceNormalsHelper.prototype.update = ( function ( object ) {
  20497. var v1 = new THREE.Vector3();
  20498. return function ( object ) {
  20499. this.object.updateMatrixWorld( true );
  20500. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20501. var vertices = this.geometry.vertices;
  20502. var faces = this.object.geometry.faces;
  20503. var worldMatrix = this.object.matrixWorld;
  20504. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20505. var face = faces[ i ];
  20506. v1.copy( face.normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20507. var idx = 2 * i;
  20508. vertices[ idx ].copy( face.centroid ).applyMatrix4( worldMatrix );
  20509. vertices[ idx + 1 ].addVectors( vertices[ idx ], v1 );
  20510. }
  20511. this.geometry.verticesNeedUpdate = true;
  20512. return this;
  20513. }
  20514. }());
  20515. /**
  20516. * @author mrdoob / http://mrdoob.com/
  20517. */
  20518. THREE.GridHelper = function ( size, step ) {
  20519. var geometry = new THREE.Geometry();
  20520. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20521. this.color1 = new THREE.Color( 0x444444 );
  20522. this.color2 = new THREE.Color( 0x888888 );
  20523. for ( var i = - size; i <= size; i += step ) {
  20524. geometry.vertices.push(
  20525. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  20526. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  20527. );
  20528. var color = i === 0 ? this.color1 : this.color2;
  20529. geometry.colors.push( color, color, color, color );
  20530. }
  20531. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20532. };
  20533. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  20534. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  20535. this.color1.set( colorCenterLine );
  20536. this.color2.set( colorGrid );
  20537. this.geometry.colorsNeedUpdate = true;
  20538. }
  20539. /**
  20540. * @author alteredq / http://alteredqualia.com/
  20541. * @author mrdoob / http://mrdoob.com/
  20542. */
  20543. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20544. THREE.Object3D.call( this );
  20545. this.light = light;
  20546. this.light.updateMatrixWorld();
  20547. this.matrixWorld = light.matrixWorld;
  20548. this.matrixAutoUpdate = false;
  20549. this.colors = [ new THREE.Color(), new THREE.Color() ];
  20550. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20551. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20552. for ( var i = 0, il = 8; i < il; i ++ ) {
  20553. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  20554. }
  20555. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  20556. this.lightSphere = new THREE.Mesh( geometry, material );
  20557. this.add( this.lightSphere );
  20558. this.update();
  20559. };
  20560. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20561. THREE.HemisphereLightHelper.prototype.dispose = function () {
  20562. this.lightSphere.geometry.dispose();
  20563. this.lightSphere.material.dispose();
  20564. };
  20565. THREE.HemisphereLightHelper.prototype.update = function () {
  20566. var vector = new THREE.Vector3();
  20567. return function () {
  20568. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  20569. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  20570. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20571. this.lightSphere.geometry.colorsNeedUpdate = true;
  20572. }
  20573. }();
  20574. /**
  20575. * @author alteredq / http://alteredqualia.com/
  20576. * @author mrdoob / http://mrdoob.com/
  20577. */
  20578. THREE.PointLightHelper = function ( light, sphereSize ) {
  20579. this.light = light;
  20580. this.light.updateMatrixWorld();
  20581. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20582. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20583. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20584. THREE.Mesh.call( this, geometry, material );
  20585. this.matrixWorld = this.light.matrixWorld;
  20586. this.matrixAutoUpdate = false;
  20587. /*
  20588. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20589. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20590. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20591. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20592. var d = light.distance;
  20593. if ( d === 0.0 ) {
  20594. this.lightDistance.visible = false;
  20595. } else {
  20596. this.lightDistance.scale.set( d, d, d );
  20597. }
  20598. this.add( this.lightDistance );
  20599. */
  20600. };
  20601. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  20602. THREE.PointLightHelper.prototype.dispose = function () {
  20603. this.geometry.dispose();
  20604. this.material.dispose();
  20605. };
  20606. THREE.PointLightHelper.prototype.update = function () {
  20607. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20608. /*
  20609. var d = this.light.distance;
  20610. if ( d === 0.0 ) {
  20611. this.lightDistance.visible = false;
  20612. } else {
  20613. this.lightDistance.visible = true;
  20614. this.lightDistance.scale.set( d, d, d );
  20615. }
  20616. */
  20617. };
  20618. /**
  20619. * @author alteredq / http://alteredqualia.com/
  20620. * @author mrdoob / http://mrdoob.com/
  20621. * @author WestLangley / http://github.com/WestLangley
  20622. */
  20623. THREE.SpotLightHelper = function ( light ) {
  20624. THREE.Object3D.call( this );
  20625. this.light = light;
  20626. this.light.updateMatrixWorld();
  20627. this.matrixWorld = light.matrixWorld;
  20628. this.matrixAutoUpdate = false;
  20629. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  20630. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  20631. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20632. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20633. this.cone = new THREE.Mesh( geometry, material );
  20634. this.add( this.cone );
  20635. this.update();
  20636. };
  20637. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20638. THREE.SpotLightHelper.prototype.dispose = function () {
  20639. this.cone.geometry.dispose();
  20640. this.cone.material.dispose();
  20641. };
  20642. THREE.SpotLightHelper.prototype.update = function () {
  20643. var vector = new THREE.Vector3();
  20644. var vector2 = new THREE.Vector3();
  20645. return function () {
  20646. var coneLength = this.light.distance ? this.light.distance : 10000;
  20647. var coneWidth = coneLength * Math.tan( this.light.angle );
  20648. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20649. vector.setFromMatrixPosition( this.light.matrixWorld );
  20650. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  20651. this.cone.lookAt( vector2.sub( vector ) );
  20652. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20653. };
  20654. }();
  20655. /**
  20656. * @author mrdoob / http://mrdoob.com/
  20657. * @author WestLangley / http://github.com/WestLangley
  20658. */
  20659. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  20660. this.object = object;
  20661. this.size = size || 1;
  20662. var color = hex || 0xff0000;
  20663. var width = linewidth || 1;
  20664. var geometry = new THREE.Geometry();
  20665. var vertices = object.geometry.vertices;
  20666. var faces = object.geometry.faces;
  20667. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20668. var face = faces[ i ];
  20669. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20670. geometry.vertices.push( new THREE.Vector3() );
  20671. geometry.vertices.push( new THREE.Vector3() );
  20672. }
  20673. }
  20674. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20675. this.matrixAutoUpdate = false;
  20676. this.normalMatrix = new THREE.Matrix3();
  20677. this.update();
  20678. };
  20679. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20680. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  20681. var v1 = new THREE.Vector3();
  20682. return function( object ) {
  20683. var keys = [ 'a', 'b', 'c', 'd' ];
  20684. this.object.updateMatrixWorld( true );
  20685. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20686. var vertices = this.geometry.vertices;
  20687. var verts = this.object.geometry.vertices;
  20688. var faces = this.object.geometry.faces;
  20689. var worldMatrix = this.object.matrixWorld;
  20690. var idx = 0;
  20691. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20692. var face = faces[ i ];
  20693. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20694. var vertexId = face[ keys[ j ] ];
  20695. var vertex = verts[ vertexId ];
  20696. var normal = face.vertexNormals[ j ];
  20697. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20698. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20699. v1.add( vertices[ idx ] );
  20700. idx = idx + 1;
  20701. vertices[ idx ].copy( v1 );
  20702. idx = idx + 1;
  20703. }
  20704. }
  20705. this.geometry.verticesNeedUpdate = true;
  20706. return this;
  20707. }
  20708. }());
  20709. /**
  20710. * @author mrdoob / http://mrdoob.com/
  20711. * @author WestLangley / http://github.com/WestLangley
  20712. */
  20713. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  20714. this.object = object;
  20715. this.size = size || 1;
  20716. var color = hex || 0x0000ff;
  20717. var width = linewidth || 1;
  20718. var geometry = new THREE.Geometry();
  20719. var vertices = object.geometry.vertices;
  20720. var faces = object.geometry.faces;
  20721. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20722. var face = faces[ i ];
  20723. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20724. geometry.vertices.push( new THREE.Vector3() );
  20725. geometry.vertices.push( new THREE.Vector3() );
  20726. }
  20727. }
  20728. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20729. this.matrixAutoUpdate = false;
  20730. this.update();
  20731. };
  20732. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  20733. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  20734. var v1 = new THREE.Vector3();
  20735. return function( object ) {
  20736. var keys = [ 'a', 'b', 'c', 'd' ];
  20737. this.object.updateMatrixWorld( true );
  20738. var vertices = this.geometry.vertices;
  20739. var verts = this.object.geometry.vertices;
  20740. var faces = this.object.geometry.faces;
  20741. var worldMatrix = this.object.matrixWorld;
  20742. var idx = 0;
  20743. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20744. var face = faces[ i ];
  20745. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20746. var vertexId = face[ keys[ j ] ];
  20747. var vertex = verts[ vertexId ];
  20748. var tangent = face.vertexTangents[ j ];
  20749. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20750. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  20751. v1.add( vertices[ idx ] );
  20752. idx = idx + 1;
  20753. vertices[ idx ].copy( v1 );
  20754. idx = idx + 1;
  20755. }
  20756. }
  20757. this.geometry.verticesNeedUpdate = true;
  20758. return this;
  20759. }
  20760. }());
  20761. /**
  20762. * @author mrdoob / http://mrdoob.com/
  20763. */
  20764. THREE.WireframeHelper = function ( object ) {
  20765. var edge = [ 0, 0 ], hash = {};
  20766. var sortFunction = function ( a, b ) { return a - b };
  20767. var keys = [ 'a', 'b', 'c', 'd' ];
  20768. var geometry = new THREE.BufferGeometry();
  20769. if ( object.geometry instanceof THREE.Geometry ) {
  20770. var vertices = object.geometry.vertices;
  20771. var faces = object.geometry.faces;
  20772. var numEdges = 0;
  20773. // allocate maximal size
  20774. var edges = new Uint32Array( 6 * faces.length );
  20775. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20776. var face = faces[ i ];
  20777. for ( var j = 0; j < 3; j ++ ) {
  20778. edge[ 0 ] = face[ keys[ j ] ];
  20779. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20780. edge.sort( sortFunction );
  20781. var key = edge.toString();
  20782. if ( hash[ key ] === undefined ) {
  20783. edges[ 2 * numEdges ] = edge[ 0 ];
  20784. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  20785. hash[ key ] = true;
  20786. numEdges ++;
  20787. }
  20788. }
  20789. }
  20790. geometry.addAttribute( 'position', Float32Array, 2 * numEdges , 3 );
  20791. var coords = geometry.attributes.position.array;
  20792. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  20793. for ( var j = 0; j < 2; j ++ ) {
  20794. var vertex = vertices[ edges [ 2 * i + j] ];
  20795. var index = 6 * i + 3 * j;
  20796. coords[ index + 0 ] = vertex.x;
  20797. coords[ index + 1 ] = vertex.y;
  20798. coords[ index + 2 ] = vertex.z;
  20799. }
  20800. }
  20801. } else if ( object.geometry.offsets.length ) {
  20802. var vertices = object.geometry.attributes.position.array;
  20803. var indices = object.geometry.attributes.index.array;
  20804. var offsets = object.geometry.offsets;
  20805. var numEdges = 0;
  20806. // allocate maximal size
  20807. var edges = new Uint32Array( 2 * indices.length );
  20808. for ( var o = 0, ol = offsets.length; o < ol; ++ o ) {
  20809. var start = offsets[ o ].start;
  20810. var count = offsets[ o ].count;
  20811. var index = offsets[ o ].index;
  20812. for ( var i = start, il = start + count; i < il; i += 3 ) {
  20813. for ( var j = 0; j < 3; j ++ ) {
  20814. edge[ 0 ] = index + indices[ i + j ];
  20815. edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ];
  20816. edge.sort( sortFunction );
  20817. var key = edge.toString();
  20818. if ( hash[ key ] === undefined ) {
  20819. edges[ 2 * numEdges ] = edge[ 0 ];
  20820. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  20821. hash[ key ] = true;
  20822. numEdges ++;
  20823. }
  20824. }
  20825. }
  20826. }
  20827. geometry.addAttribute( 'position', Float32Array, 2 * numEdges , 3 );
  20828. var coords = geometry.attributes.position.array;
  20829. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  20830. for ( var j = 0; j < 2; j ++ ) {
  20831. var index = 6 * i + 3 * j;
  20832. var index2 = 3 * edges[ 2 * i + j];
  20833. coords[ index + 0 ] = vertices[ index2 ];
  20834. coords[ index + 1 ] = vertices[ index2 + 1 ];
  20835. coords[ index + 2 ] = vertices[ index2 + 2 ];
  20836. }
  20837. }
  20838. } else {
  20839. var vertices = object.geometry.attributes.position.array;
  20840. var numEdges = vertices.length / 3;
  20841. var numTris = numEdges / 3;
  20842. geometry.addAttribute( 'position', Float32Array, 2 * numEdges , 3 );
  20843. var coords = geometry.attributes.position.array;
  20844. for ( var i = 0, l = numTris; i < l; i ++ ) {
  20845. var index = i * 9;
  20846. for ( var j = 0; j < 3; j ++ ) {
  20847. var index2 = 2 * index + 6 * j;
  20848. var vertex1 = j * 3;
  20849. var vertex2 = ( ( j + 1 ) % 3 ) * 3;
  20850. coords[ index2 + 0 ] = vertices[ index + vertex1 ];
  20851. coords[ index2 + 1 ] = vertices[ index + vertex1 + 1 ];
  20852. coords[ index2 + 2 ] = vertices[ index + vertex1 + 2 ];
  20853. coords[ index2 + 3 ] = vertices[ index + vertex2 ];
  20854. coords[ index2 + 4 ] = vertices[ index + vertex2 + 1 ];
  20855. coords[ index2 + 5 ] = vertices[ index + vertex2 + 2 ];
  20856. }
  20857. }
  20858. }
  20859. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffffff } ), THREE.LinePieces );
  20860. this.matrixAutoUpdate = false;
  20861. this.matrixWorld = object.matrixWorld;
  20862. };
  20863. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  20864. /**
  20865. * @author alteredq / http://alteredqualia.com/
  20866. */
  20867. THREE.ImmediateRenderObject = function () {
  20868. THREE.Object3D.call( this );
  20869. this.render = function ( renderCallback ) { };
  20870. };
  20871. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20872. /**
  20873. * @author mikael emtinger / http://gomo.se/
  20874. * @author alteredq / http://alteredqualia.com/
  20875. */
  20876. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20877. THREE.Object3D.call( this );
  20878. this.lensFlares = [];
  20879. this.positionScreen = new THREE.Vector3();
  20880. this.customUpdateCallback = undefined;
  20881. if( texture !== undefined ) {
  20882. this.add( texture, size, distance, blending, color );
  20883. }
  20884. };
  20885. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20886. /*
  20887. * Add: adds another flare
  20888. */
  20889. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20890. if( size === undefined ) size = -1;
  20891. if( distance === undefined ) distance = 0;
  20892. if( opacity === undefined ) opacity = 1;
  20893. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20894. if( blending === undefined ) blending = THREE.NormalBlending;
  20895. distance = Math.min( distance, Math.max( 0, distance ) );
  20896. this.lensFlares.push( { texture: texture, // THREE.Texture
  20897. size: size, // size in pixels (-1 = use texture.width)
  20898. distance: distance, // distance (0-1) from light source (0=at light source)
  20899. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20900. scale: 1, // scale
  20901. rotation: 1, // rotation
  20902. opacity: opacity, // opacity
  20903. color: color, // color
  20904. blending: blending } ); // blending
  20905. };
  20906. /*
  20907. * Update lens flares update positions on all flares based on the screen position
  20908. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20909. */
  20910. THREE.LensFlare.prototype.updateLensFlares = function () {
  20911. var f, fl = this.lensFlares.length;
  20912. var flare;
  20913. var vecX = -this.positionScreen.x * 2;
  20914. var vecY = -this.positionScreen.y * 2;
  20915. for( f = 0; f < fl; f ++ ) {
  20916. flare = this.lensFlares[ f ];
  20917. flare.x = this.positionScreen.x + vecX * flare.distance;
  20918. flare.y = this.positionScreen.y + vecY * flare.distance;
  20919. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20920. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20921. }
  20922. };
  20923. /**
  20924. * @author alteredq / http://alteredqualia.com/
  20925. */
  20926. THREE.MorphBlendMesh = function( geometry, material ) {
  20927. THREE.Mesh.call( this, geometry, material );
  20928. this.animationsMap = {};
  20929. this.animationsList = [];
  20930. // prepare default animation
  20931. // (all frames played together in 1 second)
  20932. var numFrames = this.geometry.morphTargets.length;
  20933. var name = "__default";
  20934. var startFrame = 0;
  20935. var endFrame = numFrames - 1;
  20936. var fps = numFrames / 1;
  20937. this.createAnimation( name, startFrame, endFrame, fps );
  20938. this.setAnimationWeight( name, 1 );
  20939. };
  20940. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20941. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20942. var animation = {
  20943. startFrame: start,
  20944. endFrame: end,
  20945. length: end - start + 1,
  20946. fps: fps,
  20947. duration: ( end - start ) / fps,
  20948. lastFrame: 0,
  20949. currentFrame: 0,
  20950. active: false,
  20951. time: 0,
  20952. direction: 1,
  20953. weight: 1,
  20954. directionBackwards: false,
  20955. mirroredLoop: false
  20956. };
  20957. this.animationsMap[ name ] = animation;
  20958. this.animationsList.push( animation );
  20959. };
  20960. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20961. var pattern = /([a-z]+)(\d+)/;
  20962. var firstAnimation, frameRanges = {};
  20963. var geometry = this.geometry;
  20964. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20965. var morph = geometry.morphTargets[ i ];
  20966. var chunks = morph.name.match( pattern );
  20967. if ( chunks && chunks.length > 1 ) {
  20968. var name = chunks[ 1 ];
  20969. var num = chunks[ 2 ];
  20970. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20971. var range = frameRanges[ name ];
  20972. if ( i < range.start ) range.start = i;
  20973. if ( i > range.end ) range.end = i;
  20974. if ( ! firstAnimation ) firstAnimation = name;
  20975. }
  20976. }
  20977. for ( var name in frameRanges ) {
  20978. var range = frameRanges[ name ];
  20979. this.createAnimation( name, range.start, range.end, fps );
  20980. }
  20981. this.firstAnimation = firstAnimation;
  20982. };
  20983. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20984. var animation = this.animationsMap[ name ];
  20985. if ( animation ) {
  20986. animation.direction = 1;
  20987. animation.directionBackwards = false;
  20988. }
  20989. };
  20990. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20991. var animation = this.animationsMap[ name ];
  20992. if ( animation ) {
  20993. animation.direction = -1;
  20994. animation.directionBackwards = true;
  20995. }
  20996. };
  20997. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20998. var animation = this.animationsMap[ name ];
  20999. if ( animation ) {
  21000. animation.fps = fps;
  21001. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21002. }
  21003. };
  21004. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21005. var animation = this.animationsMap[ name ];
  21006. if ( animation ) {
  21007. animation.duration = duration;
  21008. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21009. }
  21010. };
  21011. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21012. var animation = this.animationsMap[ name ];
  21013. if ( animation ) {
  21014. animation.weight = weight;
  21015. }
  21016. };
  21017. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21018. var animation = this.animationsMap[ name ];
  21019. if ( animation ) {
  21020. animation.time = time;
  21021. }
  21022. };
  21023. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21024. var time = 0;
  21025. var animation = this.animationsMap[ name ];
  21026. if ( animation ) {
  21027. time = animation.time;
  21028. }
  21029. return time;
  21030. };
  21031. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21032. var duration = -1;
  21033. var animation = this.animationsMap[ name ];
  21034. if ( animation ) {
  21035. duration = animation.duration;
  21036. }
  21037. return duration;
  21038. };
  21039. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21040. var animation = this.animationsMap[ name ];
  21041. if ( animation ) {
  21042. animation.time = 0;
  21043. animation.active = true;
  21044. } else {
  21045. console.warn( "animation[" + name + "] undefined" );
  21046. }
  21047. };
  21048. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21049. var animation = this.animationsMap[ name ];
  21050. if ( animation ) {
  21051. animation.active = false;
  21052. }
  21053. };
  21054. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21055. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21056. var animation = this.animationsList[ i ];
  21057. if ( ! animation.active ) continue;
  21058. var frameTime = animation.duration / animation.length;
  21059. animation.time += animation.direction * delta;
  21060. if ( animation.mirroredLoop ) {
  21061. if ( animation.time > animation.duration || animation.time < 0 ) {
  21062. animation.direction *= -1;
  21063. if ( animation.time > animation.duration ) {
  21064. animation.time = animation.duration;
  21065. animation.directionBackwards = true;
  21066. }
  21067. if ( animation.time < 0 ) {
  21068. animation.time = 0;
  21069. animation.directionBackwards = false;
  21070. }
  21071. }
  21072. } else {
  21073. animation.time = animation.time % animation.duration;
  21074. if ( animation.time < 0 ) animation.time += animation.duration;
  21075. }
  21076. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21077. var weight = animation.weight;
  21078. if ( keyframe !== animation.currentFrame ) {
  21079. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21080. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21081. this.morphTargetInfluences[ keyframe ] = 0;
  21082. animation.lastFrame = animation.currentFrame;
  21083. animation.currentFrame = keyframe;
  21084. }
  21085. var mix = ( animation.time % frameTime ) / frameTime;
  21086. if ( animation.directionBackwards ) mix = 1 - mix;
  21087. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21088. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21089. }
  21090. };
  21091. /**
  21092. * @author mikael emtinger / http://gomo.se/
  21093. * @author alteredq / http://alteredqualia.com/
  21094. */
  21095. THREE.LensFlarePlugin = function () {
  21096. var _gl, _renderer, _precision, _lensFlare = {};
  21097. this.init = function ( renderer ) {
  21098. _gl = renderer.context;
  21099. _renderer = renderer;
  21100. _precision = renderer.getPrecision();
  21101. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21102. _lensFlare.faces = new Uint16Array( 6 );
  21103. var i = 0;
  21104. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21105. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21106. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21107. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21108. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21109. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21110. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21111. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21112. i = 0;
  21113. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21114. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21115. // buffers
  21116. _lensFlare.vertexBuffer = _gl.createBuffer();
  21117. _lensFlare.elementBuffer = _gl.createBuffer();
  21118. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21119. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21120. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21121. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21122. // textures
  21123. _lensFlare.tempTexture = _gl.createTexture();
  21124. _lensFlare.occlusionTexture = _gl.createTexture();
  21125. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21126. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21127. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21128. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21129. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21130. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21131. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21132. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21133. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21134. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21135. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21136. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21137. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21138. _lensFlare.hasVertexTexture = false;
  21139. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21140. } else {
  21141. _lensFlare.hasVertexTexture = true;
  21142. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21143. }
  21144. _lensFlare.attributes = {};
  21145. _lensFlare.uniforms = {};
  21146. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21147. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21148. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21149. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21150. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21151. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21152. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21153. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21154. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21155. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21156. };
  21157. /*
  21158. * Render lens flares
  21159. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21160. * reads these back and calculates occlusion.
  21161. * Then _lensFlare.update_lensFlares() is called to re-position and
  21162. * update transparency of flares. Then they are rendered.
  21163. *
  21164. */
  21165. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21166. var flares = scene.__webglFlares,
  21167. nFlares = flares.length;
  21168. if ( ! nFlares ) return;
  21169. var tempPosition = new THREE.Vector3();
  21170. var invAspect = viewportHeight / viewportWidth,
  21171. halfViewportWidth = viewportWidth * 0.5,
  21172. halfViewportHeight = viewportHeight * 0.5;
  21173. var size = 16 / viewportHeight,
  21174. scale = new THREE.Vector2( size * invAspect, size );
  21175. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21176. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21177. var uniforms = _lensFlare.uniforms,
  21178. attributes = _lensFlare.attributes;
  21179. // set _lensFlare program and reset blending
  21180. _gl.useProgram( _lensFlare.program );
  21181. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21182. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21183. // loop through all lens flares to update their occlusion and positions
  21184. // setup gl and common used attribs/unforms
  21185. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21186. _gl.uniform1i( uniforms.map, 1 );
  21187. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21188. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21189. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21190. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21191. _gl.disable( _gl.CULL_FACE );
  21192. _gl.depthMask( false );
  21193. var i, j, jl, flare, sprite;
  21194. for ( i = 0; i < nFlares; i ++ ) {
  21195. size = 16 / viewportHeight;
  21196. scale.set( size * invAspect, size );
  21197. // calc object screen position
  21198. flare = flares[ i ];
  21199. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21200. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21201. tempPosition.applyProjection( camera.projectionMatrix );
  21202. // setup arrays for gl programs
  21203. screenPosition.copy( tempPosition )
  21204. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21205. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21206. // screen cull
  21207. if ( _lensFlare.hasVertexTexture || (
  21208. screenPositionPixels.x > 0 &&
  21209. screenPositionPixels.x < viewportWidth &&
  21210. screenPositionPixels.y > 0 &&
  21211. screenPositionPixels.y < viewportHeight ) ) {
  21212. // save current RGB to temp texture
  21213. _gl.activeTexture( _gl.TEXTURE1 );
  21214. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21215. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21216. // render pink quad
  21217. _gl.uniform1i( uniforms.renderType, 0 );
  21218. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21219. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21220. _gl.disable( _gl.BLEND );
  21221. _gl.enable( _gl.DEPTH_TEST );
  21222. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21223. // copy result to occlusionMap
  21224. _gl.activeTexture( _gl.TEXTURE0 );
  21225. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21226. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21227. // restore graphics
  21228. _gl.uniform1i( uniforms.renderType, 1 );
  21229. _gl.disable( _gl.DEPTH_TEST );
  21230. _gl.activeTexture( _gl.TEXTURE1 );
  21231. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21232. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21233. // update object positions
  21234. flare.positionScreen.copy( screenPosition )
  21235. if ( flare.customUpdateCallback ) {
  21236. flare.customUpdateCallback( flare );
  21237. } else {
  21238. flare.updateLensFlares();
  21239. }
  21240. // render flares
  21241. _gl.uniform1i( uniforms.renderType, 2 );
  21242. _gl.enable( _gl.BLEND );
  21243. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21244. sprite = flare.lensFlares[ j ];
  21245. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21246. screenPosition.x = sprite.x;
  21247. screenPosition.y = sprite.y;
  21248. screenPosition.z = sprite.z;
  21249. size = sprite.size * sprite.scale / viewportHeight;
  21250. scale.x = size * invAspect;
  21251. scale.y = size;
  21252. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21253. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21254. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21255. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21256. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21257. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21258. _renderer.setTexture( sprite.texture, 1 );
  21259. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21260. }
  21261. }
  21262. }
  21263. }
  21264. // restore gl
  21265. _gl.enable( _gl.CULL_FACE );
  21266. _gl.enable( _gl.DEPTH_TEST );
  21267. _gl.depthMask( true );
  21268. };
  21269. function createProgram ( shader, precision ) {
  21270. var program = _gl.createProgram();
  21271. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21272. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21273. var prefix = "precision " + precision + " float;\n";
  21274. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21275. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21276. _gl.compileShader( fragmentShader );
  21277. _gl.compileShader( vertexShader );
  21278. _gl.attachShader( program, fragmentShader );
  21279. _gl.attachShader( program, vertexShader );
  21280. _gl.linkProgram( program );
  21281. return program;
  21282. };
  21283. };
  21284. /**
  21285. * @author alteredq / http://alteredqualia.com/
  21286. */
  21287. THREE.ShadowMapPlugin = function () {
  21288. var _gl,
  21289. _renderer,
  21290. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21291. _frustum = new THREE.Frustum(),
  21292. _projScreenMatrix = new THREE.Matrix4(),
  21293. _min = new THREE.Vector3(),
  21294. _max = new THREE.Vector3(),
  21295. _matrixPosition = new THREE.Vector3();
  21296. this.init = function ( renderer ) {
  21297. _gl = renderer.context;
  21298. _renderer = renderer;
  21299. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21300. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21301. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21302. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21303. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21304. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21305. _depthMaterial._shadowPass = true;
  21306. _depthMaterialMorph._shadowPass = true;
  21307. _depthMaterialSkin._shadowPass = true;
  21308. _depthMaterialMorphSkin._shadowPass = true;
  21309. };
  21310. this.render = function ( scene, camera ) {
  21311. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21312. this.update( scene, camera );
  21313. };
  21314. this.update = function ( scene, camera ) {
  21315. var i, il, j, jl, n,
  21316. shadowMap, shadowMatrix, shadowCamera,
  21317. program, buffer, material,
  21318. webglObject, object, light,
  21319. renderList,
  21320. lights = [],
  21321. k = 0,
  21322. fog = null;
  21323. // set GL state for depth map
  21324. _gl.clearColor( 1, 1, 1, 1 );
  21325. _gl.disable( _gl.BLEND );
  21326. _gl.enable( _gl.CULL_FACE );
  21327. _gl.frontFace( _gl.CCW );
  21328. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21329. _gl.cullFace( _gl.FRONT );
  21330. } else {
  21331. _gl.cullFace( _gl.BACK );
  21332. }
  21333. _renderer.setDepthTest( true );
  21334. // preprocess lights
  21335. // - skip lights that are not casting shadows
  21336. // - create virtual lights for cascaded shadow maps
  21337. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21338. light = scene.__lights[ i ];
  21339. if ( ! light.castShadow ) continue;
  21340. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21341. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21342. var virtualLight;
  21343. if ( ! light.shadowCascadeArray[ n ] ) {
  21344. virtualLight = createVirtualLight( light, n );
  21345. virtualLight.originalCamera = camera;
  21346. var gyro = new THREE.Gyroscope();
  21347. gyro.position = light.shadowCascadeOffset;
  21348. gyro.add( virtualLight );
  21349. gyro.add( virtualLight.target );
  21350. camera.add( gyro );
  21351. light.shadowCascadeArray[ n ] = virtualLight;
  21352. console.log( "Created virtualLight", virtualLight );
  21353. } else {
  21354. virtualLight = light.shadowCascadeArray[ n ];
  21355. }
  21356. updateVirtualLight( light, n );
  21357. lights[ k ] = virtualLight;
  21358. k ++;
  21359. }
  21360. } else {
  21361. lights[ k ] = light;
  21362. k ++;
  21363. }
  21364. }
  21365. // render depth map
  21366. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21367. light = lights[ i ];
  21368. if ( ! light.shadowMap ) {
  21369. var shadowFilter = THREE.LinearFilter;
  21370. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21371. shadowFilter = THREE.NearestFilter;
  21372. }
  21373. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21374. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21375. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21376. light.shadowMatrix = new THREE.Matrix4();
  21377. }
  21378. if ( ! light.shadowCamera ) {
  21379. if ( light instanceof THREE.SpotLight ) {
  21380. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21381. } else if ( light instanceof THREE.DirectionalLight ) {
  21382. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21383. } else {
  21384. console.error( "Unsupported light type for shadow" );
  21385. continue;
  21386. }
  21387. scene.add( light.shadowCamera );
  21388. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21389. }
  21390. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21391. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21392. light.shadowCamera.add( light.cameraHelper );
  21393. }
  21394. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21395. updateShadowCamera( camera, light );
  21396. }
  21397. shadowMap = light.shadowMap;
  21398. shadowMatrix = light.shadowMatrix;
  21399. shadowCamera = light.shadowCamera;
  21400. shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
  21401. _matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
  21402. shadowCamera.lookAt( _matrixPosition );
  21403. shadowCamera.updateMatrixWorld();
  21404. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21405. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21406. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21407. // compute shadow matrix
  21408. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21409. 0.0, 0.5, 0.0, 0.5,
  21410. 0.0, 0.0, 0.5, 0.5,
  21411. 0.0, 0.0, 0.0, 1.0 );
  21412. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21413. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21414. // update camera matrices and frustum
  21415. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21416. _frustum.setFromMatrix( _projScreenMatrix );
  21417. // render shadow map
  21418. _renderer.setRenderTarget( shadowMap );
  21419. _renderer.clear();
  21420. // set object matrices & frustum culling
  21421. renderList = scene.__webglObjects;
  21422. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21423. webglObject = renderList[ j ];
  21424. object = webglObject.object;
  21425. webglObject.render = false;
  21426. if ( object.visible && object.castShadow ) {
  21427. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21428. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21429. webglObject.render = true;
  21430. }
  21431. }
  21432. }
  21433. // render regular objects
  21434. var objectMaterial, useMorphing, useSkinning;
  21435. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21436. webglObject = renderList[ j ];
  21437. if ( webglObject.render ) {
  21438. object = webglObject.object;
  21439. buffer = webglObject.buffer;
  21440. // culling is overriden globally for all objects
  21441. // while rendering depth map
  21442. // need to deal with MeshFaceMaterial somehow
  21443. // in that case just use the first of material.materials for now
  21444. // (proper solution would require to break objects by materials
  21445. // similarly to regular rendering and then set corresponding
  21446. // depth materials per each chunk instead of just once per object)
  21447. objectMaterial = getObjectMaterial( object );
  21448. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21449. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21450. if ( object.customDepthMaterial ) {
  21451. material = object.customDepthMaterial;
  21452. } else if ( useSkinning ) {
  21453. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21454. } else if ( useMorphing ) {
  21455. material = _depthMaterialMorph;
  21456. } else {
  21457. material = _depthMaterial;
  21458. }
  21459. if ( buffer instanceof THREE.BufferGeometry ) {
  21460. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21461. } else {
  21462. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21463. }
  21464. }
  21465. }
  21466. // set matrices and render immediate objects
  21467. renderList = scene.__webglObjectsImmediate;
  21468. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21469. webglObject = renderList[ j ];
  21470. object = webglObject.object;
  21471. if ( object.visible && object.castShadow ) {
  21472. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21473. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21474. }
  21475. }
  21476. }
  21477. // restore GL state
  21478. var clearColor = _renderer.getClearColor(),
  21479. clearAlpha = _renderer.getClearAlpha();
  21480. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21481. _gl.enable( _gl.BLEND );
  21482. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21483. _gl.cullFace( _gl.BACK );
  21484. }
  21485. };
  21486. function createVirtualLight( light, cascade ) {
  21487. var virtualLight = new THREE.DirectionalLight();
  21488. virtualLight.isVirtual = true;
  21489. virtualLight.onlyShadow = true;
  21490. virtualLight.castShadow = true;
  21491. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21492. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21493. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21494. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21495. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21496. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21497. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21498. virtualLight.shadowDarkness = light.shadowDarkness;
  21499. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21500. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21501. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21502. virtualLight.pointsWorld = [];
  21503. virtualLight.pointsFrustum = [];
  21504. var pointsWorld = virtualLight.pointsWorld,
  21505. pointsFrustum = virtualLight.pointsFrustum;
  21506. for ( var i = 0; i < 8; i ++ ) {
  21507. pointsWorld[ i ] = new THREE.Vector3();
  21508. pointsFrustum[ i ] = new THREE.Vector3();
  21509. }
  21510. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21511. var farZ = light.shadowCascadeFarZ[ cascade ];
  21512. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21513. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21514. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21515. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21516. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21517. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21518. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21519. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21520. return virtualLight;
  21521. }
  21522. // Synchronize virtual light with the original light
  21523. function updateVirtualLight( light, cascade ) {
  21524. var virtualLight = light.shadowCascadeArray[ cascade ];
  21525. virtualLight.position.copy( light.position );
  21526. virtualLight.target.position.copy( light.target.position );
  21527. virtualLight.lookAt( virtualLight.target );
  21528. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21529. virtualLight.shadowDarkness = light.shadowDarkness;
  21530. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21531. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21532. var farZ = light.shadowCascadeFarZ[ cascade ];
  21533. var pointsFrustum = virtualLight.pointsFrustum;
  21534. pointsFrustum[ 0 ].z = nearZ;
  21535. pointsFrustum[ 1 ].z = nearZ;
  21536. pointsFrustum[ 2 ].z = nearZ;
  21537. pointsFrustum[ 3 ].z = nearZ;
  21538. pointsFrustum[ 4 ].z = farZ;
  21539. pointsFrustum[ 5 ].z = farZ;
  21540. pointsFrustum[ 6 ].z = farZ;
  21541. pointsFrustum[ 7 ].z = farZ;
  21542. }
  21543. // Fit shadow camera's ortho frustum to camera frustum
  21544. function updateShadowCamera( camera, light ) {
  21545. var shadowCamera = light.shadowCamera,
  21546. pointsFrustum = light.pointsFrustum,
  21547. pointsWorld = light.pointsWorld;
  21548. _min.set( Infinity, Infinity, Infinity );
  21549. _max.set( -Infinity, -Infinity, -Infinity );
  21550. for ( var i = 0; i < 8; i ++ ) {
  21551. var p = pointsWorld[ i ];
  21552. p.copy( pointsFrustum[ i ] );
  21553. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21554. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21555. if ( p.x < _min.x ) _min.x = p.x;
  21556. if ( p.x > _max.x ) _max.x = p.x;
  21557. if ( p.y < _min.y ) _min.y = p.y;
  21558. if ( p.y > _max.y ) _max.y = p.y;
  21559. if ( p.z < _min.z ) _min.z = p.z;
  21560. if ( p.z > _max.z ) _max.z = p.z;
  21561. }
  21562. shadowCamera.left = _min.x;
  21563. shadowCamera.right = _max.x;
  21564. shadowCamera.top = _max.y;
  21565. shadowCamera.bottom = _min.y;
  21566. // can't really fit near/far
  21567. //shadowCamera.near = _min.z;
  21568. //shadowCamera.far = _max.z;
  21569. shadowCamera.updateProjectionMatrix();
  21570. }
  21571. // For the moment just ignore objects that have multiple materials with different animation methods
  21572. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21573. function getObjectMaterial( object ) {
  21574. return object.material instanceof THREE.MeshFaceMaterial
  21575. ? object.material.materials[ 0 ]
  21576. : object.material;
  21577. };
  21578. };
  21579. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21580. /**
  21581. * @author mikael emtinger / http://gomo.se/
  21582. * @author alteredq / http://alteredqualia.com/
  21583. */
  21584. THREE.SpritePlugin = function () {
  21585. var _gl, _renderer, _texture;
  21586. var vertices, faces, vertexBuffer, elementBuffer;
  21587. var program, attributes, uniforms;
  21588. this.init = function ( renderer ) {
  21589. _gl = renderer.context;
  21590. _renderer = renderer;
  21591. vertices = new Float32Array( [
  21592. - 0.5, - 0.5, 0, 0,
  21593. 0.5, - 0.5, 1, 0,
  21594. 0.5, 0.5, 1, 1,
  21595. - 0.5, 0.5, 0, 1
  21596. ] );
  21597. faces = new Uint16Array( [
  21598. 0, 1, 2,
  21599. 0, 2, 3
  21600. ] );
  21601. vertexBuffer = _gl.createBuffer();
  21602. elementBuffer = _gl.createBuffer();
  21603. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  21604. _gl.bufferData( _gl.ARRAY_BUFFER, vertices, _gl.STATIC_DRAW );
  21605. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  21606. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faces, _gl.STATIC_DRAW );
  21607. program = createProgram();
  21608. attributes = {
  21609. position: _gl.getAttribLocation ( program, 'position' ),
  21610. uv: _gl.getAttribLocation ( program, 'uv' )
  21611. };
  21612. uniforms = {
  21613. uvOffset: _gl.getUniformLocation( program, 'uvOffset' ),
  21614. uvScale: _gl.getUniformLocation( program, 'uvScale' ),
  21615. rotation: _gl.getUniformLocation( program, 'rotation' ),
  21616. scale: _gl.getUniformLocation( program, 'scale' ),
  21617. color: _gl.getUniformLocation( program, 'color' ),
  21618. map: _gl.getUniformLocation( program, 'map' ),
  21619. opacity: _gl.getUniformLocation( program, 'opacity' ),
  21620. modelViewMatrix: _gl.getUniformLocation( program, 'modelViewMatrix' ),
  21621. projectionMatrix: _gl.getUniformLocation( program, 'projectionMatrix' ),
  21622. fogType: _gl.getUniformLocation( program, 'fogType' ),
  21623. fogDensity: _gl.getUniformLocation( program, 'fogDensity' ),
  21624. fogNear: _gl.getUniformLocation( program, 'fogNear' ),
  21625. fogFar: _gl.getUniformLocation( program, 'fogFar' ),
  21626. fogColor: _gl.getUniformLocation( program, 'fogColor' ),
  21627. alphaTest: _gl.getUniformLocation( program, 'alphaTest' )
  21628. };
  21629. var canvas = document.createElement( 'canvas' );
  21630. canvas.width = 8;
  21631. canvas.height = 8;
  21632. var context = canvas.getContext( '2d' );
  21633. context.fillStyle = '#ffffff';
  21634. context.fillRect( 0, 0, canvas.width, canvas.height );
  21635. _texture = new THREE.Texture( canvas );
  21636. _texture.needsUpdate = true;
  21637. };
  21638. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21639. var sprites = scene.__webglSprites,
  21640. nSprites = sprites.length;
  21641. if ( ! nSprites ) return;
  21642. // setup gl
  21643. _gl.useProgram( program );
  21644. _gl.enableVertexAttribArray( attributes.position );
  21645. _gl.enableVertexAttribArray( attributes.uv );
  21646. _gl.disable( _gl.CULL_FACE );
  21647. _gl.enable( _gl.BLEND );
  21648. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  21649. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21650. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21651. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  21652. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21653. _gl.activeTexture( _gl.TEXTURE0 );
  21654. _gl.uniform1i( uniforms.map, 0 );
  21655. var oldFogType = 0;
  21656. var sceneFogType = 0;
  21657. var fog = scene.fog;
  21658. if ( fog ) {
  21659. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21660. if ( fog instanceof THREE.Fog ) {
  21661. _gl.uniform1f( uniforms.fogNear, fog.near );
  21662. _gl.uniform1f( uniforms.fogFar, fog.far );
  21663. _gl.uniform1i( uniforms.fogType, 1 );
  21664. oldFogType = 1;
  21665. sceneFogType = 1;
  21666. } else if ( fog instanceof THREE.FogExp2 ) {
  21667. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21668. _gl.uniform1i( uniforms.fogType, 2 );
  21669. oldFogType = 2;
  21670. sceneFogType = 2;
  21671. }
  21672. } else {
  21673. _gl.uniform1i( uniforms.fogType, 0 );
  21674. oldFogType = 0;
  21675. sceneFogType = 0;
  21676. }
  21677. // update positions and sort
  21678. var i, sprite, material, fogType, scale = [];
  21679. for( i = 0; i < nSprites; i ++ ) {
  21680. sprite = sprites[ i ];
  21681. material = sprite.material;
  21682. if ( sprite.visible === false ) continue;
  21683. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21684. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21685. }
  21686. sprites.sort( painterSortStable );
  21687. // render all sprites
  21688. for( i = 0; i < nSprites; i ++ ) {
  21689. sprite = sprites[ i ];
  21690. if ( sprite.visible === false ) continue;
  21691. material = sprite.material;
  21692. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21693. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21694. scale[ 0 ] = sprite.scale.x;
  21695. scale[ 1 ] = sprite.scale.y;
  21696. if ( scene.fog && material.fog ) {
  21697. fogType = sceneFogType;
  21698. } else {
  21699. fogType = 0;
  21700. }
  21701. if ( oldFogType !== fogType ) {
  21702. _gl.uniform1i( uniforms.fogType, fogType );
  21703. oldFogType = fogType;
  21704. }
  21705. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21706. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21707. _gl.uniform1f( uniforms.opacity, material.opacity );
  21708. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21709. _gl.uniform1f( uniforms.rotation, material.rotation );
  21710. _gl.uniform2fv( uniforms.scale, scale );
  21711. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21712. _renderer.setDepthTest( material.depthTest );
  21713. _renderer.setDepthWrite( material.depthWrite );
  21714. if ( material.map && material.map.image && material.map.image.width ) {
  21715. _renderer.setTexture( material.map, 0 );
  21716. } else {
  21717. _renderer.setTexture( _texture, 0 );
  21718. }
  21719. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21720. }
  21721. // restore gl
  21722. _gl.enable( _gl.CULL_FACE );
  21723. };
  21724. function createProgram () {
  21725. var program = _gl.createProgram();
  21726. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21727. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21728. _gl.shaderSource( vertexShader, [
  21729. 'precision ' + _renderer.getPrecision() + ' float;',
  21730. 'uniform mat4 modelViewMatrix;',
  21731. 'uniform mat4 projectionMatrix;',
  21732. 'uniform float rotation;',
  21733. 'uniform vec2 scale;',
  21734. 'uniform vec2 uvOffset;',
  21735. 'uniform vec2 uvScale;',
  21736. 'attribute vec2 position;',
  21737. 'attribute vec2 uv;',
  21738. 'varying vec2 vUV;',
  21739. 'void main() {',
  21740. 'vUV = uvOffset + uv * uvScale;',
  21741. 'vec2 alignedPosition = position * scale;',
  21742. 'vec2 rotatedPosition;',
  21743. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  21744. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  21745. 'vec4 finalPosition;',
  21746. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  21747. 'finalPosition.xy += rotatedPosition;',
  21748. 'finalPosition = projectionMatrix * finalPosition;',
  21749. 'gl_Position = finalPosition;',
  21750. '}'
  21751. ].join( '\n' ) );
  21752. _gl.shaderSource( fragmentShader, [
  21753. 'precision ' + _renderer.getPrecision() + ' float;',
  21754. 'uniform vec3 color;',
  21755. 'uniform sampler2D map;',
  21756. 'uniform float opacity;',
  21757. 'uniform int fogType;',
  21758. 'uniform vec3 fogColor;',
  21759. 'uniform float fogDensity;',
  21760. 'uniform float fogNear;',
  21761. 'uniform float fogFar;',
  21762. 'uniform float alphaTest;',
  21763. 'varying vec2 vUV;',
  21764. 'void main() {',
  21765. 'vec4 texture = texture2D( map, vUV );',
  21766. 'if ( texture.a < alphaTest ) discard;',
  21767. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  21768. 'if ( fogType > 0 ) {',
  21769. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  21770. 'float fogFactor = 0.0;',
  21771. 'if ( fogType == 1 ) {',
  21772. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  21773. '} else {',
  21774. 'const float LOG2 = 1.442695;',
  21775. 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  21776. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  21777. '}',
  21778. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  21779. '}',
  21780. '}'
  21781. ].join( '\n' ) );
  21782. _gl.compileShader( vertexShader );
  21783. _gl.compileShader( fragmentShader );
  21784. _gl.attachShader( program, vertexShader );
  21785. _gl.attachShader( program, fragmentShader );
  21786. _gl.linkProgram( program );
  21787. return program;
  21788. };
  21789. function painterSortStable ( a, b ) {
  21790. if ( a.z !== b.z ) {
  21791. return b.z - a.z;
  21792. } else {
  21793. return b.id - a.id;
  21794. }
  21795. };
  21796. };
  21797. /**
  21798. * @author alteredq / http://alteredqualia.com/
  21799. */
  21800. THREE.DepthPassPlugin = function () {
  21801. this.enabled = false;
  21802. this.renderTarget = null;
  21803. var _gl,
  21804. _renderer,
  21805. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21806. _frustum = new THREE.Frustum(),
  21807. _projScreenMatrix = new THREE.Matrix4();
  21808. this.init = function ( renderer ) {
  21809. _gl = renderer.context;
  21810. _renderer = renderer;
  21811. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21812. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21813. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21814. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21815. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21816. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21817. _depthMaterial._shadowPass = true;
  21818. _depthMaterialMorph._shadowPass = true;
  21819. _depthMaterialSkin._shadowPass = true;
  21820. _depthMaterialMorphSkin._shadowPass = true;
  21821. };
  21822. this.render = function ( scene, camera ) {
  21823. if ( ! this.enabled ) return;
  21824. this.update( scene, camera );
  21825. };
  21826. this.update = function ( scene, camera ) {
  21827. var i, il, j, jl, n,
  21828. program, buffer, material,
  21829. webglObject, object, light,
  21830. renderList,
  21831. fog = null;
  21832. // set GL state for depth map
  21833. _gl.clearColor( 1, 1, 1, 1 );
  21834. _gl.disable( _gl.BLEND );
  21835. _renderer.setDepthTest( true );
  21836. // update scene
  21837. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21838. // update camera matrices and frustum
  21839. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21840. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21841. _frustum.setFromMatrix( _projScreenMatrix );
  21842. // render depth map
  21843. _renderer.setRenderTarget( this.renderTarget );
  21844. _renderer.clear();
  21845. // set object matrices & frustum culling
  21846. renderList = scene.__webglObjects;
  21847. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21848. webglObject = renderList[ j ];
  21849. object = webglObject.object;
  21850. webglObject.render = false;
  21851. if ( object.visible ) {
  21852. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21853. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21854. webglObject.render = true;
  21855. }
  21856. }
  21857. }
  21858. // render regular objects
  21859. var objectMaterial, useMorphing, useSkinning;
  21860. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21861. webglObject = renderList[ j ];
  21862. if ( webglObject.render ) {
  21863. object = webglObject.object;
  21864. buffer = webglObject.buffer;
  21865. // todo: create proper depth material for particles
  21866. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21867. objectMaterial = getObjectMaterial( object );
  21868. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21869. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21870. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21871. if ( object.customDepthMaterial ) {
  21872. material = object.customDepthMaterial;
  21873. } else if ( useSkinning ) {
  21874. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21875. } else if ( useMorphing ) {
  21876. material = _depthMaterialMorph;
  21877. } else {
  21878. material = _depthMaterial;
  21879. }
  21880. if ( buffer instanceof THREE.BufferGeometry ) {
  21881. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21882. } else {
  21883. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21884. }
  21885. }
  21886. }
  21887. // set matrices and render immediate objects
  21888. renderList = scene.__webglObjectsImmediate;
  21889. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21890. webglObject = renderList[ j ];
  21891. object = webglObject.object;
  21892. if ( object.visible ) {
  21893. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21894. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21895. }
  21896. }
  21897. // restore GL state
  21898. var clearColor = _renderer.getClearColor(),
  21899. clearAlpha = _renderer.getClearAlpha();
  21900. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21901. _gl.enable( _gl.BLEND );
  21902. };
  21903. // For the moment just ignore objects that have multiple materials with different animation methods
  21904. // Only the first material will be taken into account for deciding which depth material to use
  21905. function getObjectMaterial( object ) {
  21906. return object.material instanceof THREE.MeshFaceMaterial
  21907. ? object.material.materials[ 0 ]
  21908. : object.material;
  21909. };
  21910. };
  21911. /**
  21912. * @author mikael emtinger / http://gomo.se/
  21913. */
  21914. THREE.ShaderFlares = {
  21915. 'lensFlareVertexTexture': {
  21916. vertexShader: [
  21917. "uniform lowp int renderType;",
  21918. "uniform vec3 screenPosition;",
  21919. "uniform vec2 scale;",
  21920. "uniform float rotation;",
  21921. "uniform sampler2D occlusionMap;",
  21922. "attribute vec2 position;",
  21923. "attribute vec2 uv;",
  21924. "varying vec2 vUV;",
  21925. "varying float vVisibility;",
  21926. "void main() {",
  21927. "vUV = uv;",
  21928. "vec2 pos = position;",
  21929. "if( renderType == 2 ) {",
  21930. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  21931. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  21932. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  21933. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  21934. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  21935. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  21936. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  21937. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  21938. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21939. "vVisibility = visibility.r / 9.0;",
  21940. "vVisibility *= 1.0 - visibility.g / 9.0;",
  21941. "vVisibility *= visibility.b / 9.0;",
  21942. "vVisibility *= 1.0 - visibility.a / 9.0;",
  21943. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21944. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21945. "}",
  21946. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21947. "}"
  21948. ].join( "\n" ),
  21949. fragmentShader: [
  21950. "uniform lowp int renderType;",
  21951. "uniform sampler2D map;",
  21952. "uniform float opacity;",
  21953. "uniform vec3 color;",
  21954. "varying vec2 vUV;",
  21955. "varying float vVisibility;",
  21956. "void main() {",
  21957. // pink square
  21958. "if( renderType == 0 ) {",
  21959. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21960. // restore
  21961. "} else if( renderType == 1 ) {",
  21962. "gl_FragColor = texture2D( map, vUV );",
  21963. // flare
  21964. "} else {",
  21965. "vec4 texture = texture2D( map, vUV );",
  21966. "texture.a *= opacity * vVisibility;",
  21967. "gl_FragColor = texture;",
  21968. "gl_FragColor.rgb *= color;",
  21969. "}",
  21970. "}"
  21971. ].join( "\n" )
  21972. },
  21973. 'lensFlare': {
  21974. vertexShader: [
  21975. "uniform lowp int renderType;",
  21976. "uniform vec3 screenPosition;",
  21977. "uniform vec2 scale;",
  21978. "uniform float rotation;",
  21979. "attribute vec2 position;",
  21980. "attribute vec2 uv;",
  21981. "varying vec2 vUV;",
  21982. "void main() {",
  21983. "vUV = uv;",
  21984. "vec2 pos = position;",
  21985. "if( renderType == 2 ) {",
  21986. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21987. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21988. "}",
  21989. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21990. "}"
  21991. ].join( "\n" ),
  21992. fragmentShader: [
  21993. "precision mediump float;",
  21994. "uniform lowp int renderType;",
  21995. "uniform sampler2D map;",
  21996. "uniform sampler2D occlusionMap;",
  21997. "uniform float opacity;",
  21998. "uniform vec3 color;",
  21999. "varying vec2 vUV;",
  22000. "void main() {",
  22001. // pink square
  22002. "if( renderType == 0 ) {",
  22003. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  22004. // restore
  22005. "} else if( renderType == 1 ) {",
  22006. "gl_FragColor = texture2D( map, vUV );",
  22007. // flare
  22008. "} else {",
  22009. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  22010. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  22011. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  22012. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  22013. "visibility = ( 1.0 - visibility / 4.0 );",
  22014. "vec4 texture = texture2D( map, vUV );",
  22015. "texture.a *= opacity * visibility;",
  22016. "gl_FragColor = texture;",
  22017. "gl_FragColor.rgb *= color;",
  22018. "}",
  22019. "}"
  22020. ].join( "\n" )
  22021. }
  22022. };