three.js 791 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908
  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: '63' };
  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 () {
  295. var hsl = { h: 0, s: 0, l: 0 };
  296. return function () {
  297. // h,s,l ranges are in 0.0 - 1.0
  298. var r = this.r, g = this.g, b = this.b;
  299. var max = Math.max( r, g, b );
  300. var min = Math.min( r, g, b );
  301. var hue, saturation;
  302. var lightness = ( min + max ) / 2.0;
  303. if ( min === max ) {
  304. hue = 0;
  305. saturation = 0;
  306. } else {
  307. var delta = max - min;
  308. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  309. switch ( max ) {
  310. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  311. case g: hue = ( b - r ) / delta + 2; break;
  312. case b: hue = ( r - g ) / delta + 4; break;
  313. }
  314. hue /= 6;
  315. }
  316. hsl.h = hue;
  317. hsl.s = saturation;
  318. hsl.l = lightness;
  319. return hsl;
  320. };
  321. }(),
  322. getStyle: function () {
  323. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  324. },
  325. offsetHSL: function ( h, s, l ) {
  326. var hsl = this.getHSL();
  327. hsl.h += h; hsl.s += s; hsl.l += l;
  328. this.setHSL( hsl.h, hsl.s, hsl.l );
  329. return this;
  330. },
  331. add: function ( color ) {
  332. this.r += color.r;
  333. this.g += color.g;
  334. this.b += color.b;
  335. return this;
  336. },
  337. addColors: function ( color1, color2 ) {
  338. this.r = color1.r + color2.r;
  339. this.g = color1.g + color2.g;
  340. this.b = color1.b + color2.b;
  341. return this;
  342. },
  343. addScalar: function ( s ) {
  344. this.r += s;
  345. this.g += s;
  346. this.b += s;
  347. return this;
  348. },
  349. multiply: function ( color ) {
  350. this.r *= color.r;
  351. this.g *= color.g;
  352. this.b *= color.b;
  353. return this;
  354. },
  355. multiplyScalar: function ( s ) {
  356. this.r *= s;
  357. this.g *= s;
  358. this.b *= s;
  359. return this;
  360. },
  361. lerp: function ( color, alpha ) {
  362. this.r += ( color.r - this.r ) * alpha;
  363. this.g += ( color.g - this.g ) * alpha;
  364. this.b += ( color.b - this.b ) * alpha;
  365. return this;
  366. },
  367. equals: function ( c ) {
  368. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  369. },
  370. fromArray: function ( array ) {
  371. this.r = array[ 0 ];
  372. this.g = array[ 1 ];
  373. this.b = array[ 2 ];
  374. return this;
  375. },
  376. toArray: function () {
  377. return [ this.r, this.g, this.b ];
  378. },
  379. clone: function () {
  380. return new THREE.Color().setRGB( this.r, this.g, this.b );
  381. }
  382. };
  383. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  384. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  385. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  386. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  387. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  388. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  389. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  390. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  391. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  392. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  393. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  394. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  395. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  396. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  397. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  398. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  399. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  400. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  401. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  402. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  403. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  404. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  405. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  406. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  407. /**
  408. * @author mikael emtinger / http://gomo.se/
  409. * @author alteredq / http://alteredqualia.com/
  410. * @author WestLangley / http://github.com/WestLangley
  411. * @author bhouston / http://exocortex.com
  412. */
  413. THREE.Quaternion = function ( x, y, z, w ) {
  414. this._x = x || 0;
  415. this._y = y || 0;
  416. this._z = z || 0;
  417. this._w = ( w !== undefined ) ? w : 1;
  418. };
  419. THREE.Quaternion.prototype = {
  420. constructor: THREE.Quaternion,
  421. _x: 0,_y: 0, _z: 0, _w: 0,
  422. _euler: undefined,
  423. _updateEuler: function ( callback ) {
  424. if ( this._euler !== undefined ) {
  425. this._euler.setFromQuaternion( this, undefined, false );
  426. }
  427. },
  428. get x () {
  429. return this._x;
  430. },
  431. set x ( value ) {
  432. this._x = value;
  433. this._updateEuler();
  434. },
  435. get y () {
  436. return this._y;
  437. },
  438. set y ( value ) {
  439. this._y = value;
  440. this._updateEuler();
  441. },
  442. get z () {
  443. return this._z;
  444. },
  445. set z ( value ) {
  446. this._z = value;
  447. this._updateEuler();
  448. },
  449. get w () {
  450. return this._w;
  451. },
  452. set w ( value ) {
  453. this._w = value;
  454. this._updateEuler();
  455. },
  456. set: function ( x, y, z, w ) {
  457. this._x = x;
  458. this._y = y;
  459. this._z = z;
  460. this._w = w;
  461. this._updateEuler();
  462. return this;
  463. },
  464. copy: function ( quaternion ) {
  465. this._x = quaternion._x;
  466. this._y = quaternion._y;
  467. this._z = quaternion._z;
  468. this._w = quaternion._w;
  469. this._updateEuler();
  470. return this;
  471. },
  472. setFromEuler: function ( euler, update ) {
  473. if ( euler instanceof THREE.Euler === false ) {
  474. throw new Error( 'ERROR: Quaternion\'s .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  475. }
  476. // http://www.mathworks.com/matlabcentral/fileexchange/
  477. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  478. // content/SpinCalc.m
  479. var c1 = Math.cos( euler._x / 2 );
  480. var c2 = Math.cos( euler._y / 2 );
  481. var c3 = Math.cos( euler._z / 2 );
  482. var s1 = Math.sin( euler._x / 2 );
  483. var s2 = Math.sin( euler._y / 2 );
  484. var s3 = Math.sin( euler._z / 2 );
  485. if ( euler.order === 'XYZ' ) {
  486. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  487. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  488. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  489. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  490. } else if ( euler.order === 'YXZ' ) {
  491. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  492. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  493. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  494. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  495. } else if ( euler.order === 'ZXY' ) {
  496. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  497. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  498. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  499. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  500. } else if ( euler.order === 'ZYX' ) {
  501. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  502. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  503. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  504. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  505. } else if ( euler.order === 'YZX' ) {
  506. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  507. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  508. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  509. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  510. } else if ( euler.order === 'XZY' ) {
  511. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  512. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  513. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  514. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  515. }
  516. if ( update !== false ) this._updateEuler();
  517. return this;
  518. },
  519. setFromAxisAngle: function ( axis, angle ) {
  520. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  521. // axis have to be normalized
  522. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  523. this._x = axis.x * s;
  524. this._y = axis.y * s;
  525. this._z = axis.z * s;
  526. this._w = Math.cos( halfAngle );
  527. this._updateEuler();
  528. return this;
  529. },
  530. setFromRotationMatrix: function ( m ) {
  531. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  532. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  533. var te = m.elements,
  534. m11 = te[0], m12 = te[4], m13 = te[8],
  535. m21 = te[1], m22 = te[5], m23 = te[9],
  536. m31 = te[2], m32 = te[6], m33 = te[10],
  537. trace = m11 + m22 + m33,
  538. s;
  539. if ( trace > 0 ) {
  540. s = 0.5 / Math.sqrt( trace + 1.0 );
  541. this._w = 0.25 / s;
  542. this._x = ( m32 - m23 ) * s;
  543. this._y = ( m13 - m31 ) * s;
  544. this._z = ( m21 - m12 ) * s;
  545. } else if ( m11 > m22 && m11 > m33 ) {
  546. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  547. this._w = (m32 - m23 ) / s;
  548. this._x = 0.25 * s;
  549. this._y = (m12 + m21 ) / s;
  550. this._z = (m13 + m31 ) / s;
  551. } else if ( m22 > m33 ) {
  552. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  553. this._w = (m13 - m31 ) / s;
  554. this._x = (m12 + m21 ) / s;
  555. this._y = 0.25 * s;
  556. this._z = (m23 + m32 ) / s;
  557. } else {
  558. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  559. this._w = ( m21 - m12 ) / s;
  560. this._x = ( m13 + m31 ) / s;
  561. this._y = ( m23 + m32 ) / s;
  562. this._z = 0.25 * s;
  563. }
  564. this._updateEuler();
  565. return this;
  566. },
  567. inverse: function () {
  568. this.conjugate().normalize();
  569. return this;
  570. },
  571. conjugate: function () {
  572. this._x *= -1;
  573. this._y *= -1;
  574. this._z *= -1;
  575. this._updateEuler();
  576. return this;
  577. },
  578. lengthSq: function () {
  579. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  580. },
  581. length: function () {
  582. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  583. },
  584. normalize: function () {
  585. var l = this.length();
  586. if ( l === 0 ) {
  587. this._x = 0;
  588. this._y = 0;
  589. this._z = 0;
  590. this._w = 1;
  591. } else {
  592. l = 1 / l;
  593. this._x = this._x * l;
  594. this._y = this._y * l;
  595. this._z = this._z * l;
  596. this._w = this._w * l;
  597. }
  598. return this;
  599. },
  600. multiply: function ( q, p ) {
  601. if ( p !== undefined ) {
  602. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  603. return this.multiplyQuaternions( q, p );
  604. }
  605. return this.multiplyQuaternions( this, q );
  606. },
  607. multiplyQuaternions: function ( a, b ) {
  608. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  609. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  610. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  611. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  612. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  613. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  614. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  615. this._updateEuler();
  616. return this;
  617. },
  618. multiplyVector3: function ( vector ) {
  619. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  620. return vector.applyQuaternion( this );
  621. },
  622. slerp: function ( qb, t ) {
  623. var x = this._x, y = this._y, z = this._z, w = this._w;
  624. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  625. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  626. if ( cosHalfTheta < 0 ) {
  627. this._w = -qb._w;
  628. this._x = -qb._x;
  629. this._y = -qb._y;
  630. this._z = -qb._z;
  631. cosHalfTheta = -cosHalfTheta;
  632. } else {
  633. this.copy( qb );
  634. }
  635. if ( cosHalfTheta >= 1.0 ) {
  636. this._w = w;
  637. this._x = x;
  638. this._y = y;
  639. this._z = z;
  640. return this;
  641. }
  642. var halfTheta = Math.acos( cosHalfTheta );
  643. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  644. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  645. this._w = 0.5 * ( w + this._w );
  646. this._x = 0.5 * ( x + this._x );
  647. this._y = 0.5 * ( y + this._y );
  648. this._z = 0.5 * ( z + this._z );
  649. return this;
  650. }
  651. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  652. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  653. this._w = ( w * ratioA + this._w * ratioB );
  654. this._x = ( x * ratioA + this._x * ratioB );
  655. this._y = ( y * ratioA + this._y * ratioB );
  656. this._z = ( z * ratioA + this._z * ratioB );
  657. this._updateEuler();
  658. return this;
  659. },
  660. equals: function ( quaternion ) {
  661. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  662. },
  663. fromArray: function ( array ) {
  664. this._x = array[ 0 ];
  665. this._y = array[ 1 ];
  666. this._z = array[ 2 ];
  667. this._w = array[ 3 ];
  668. this._updateEuler();
  669. return this;
  670. },
  671. toArray: function () {
  672. return [ this._x, this._y, this._z, this._w ];
  673. },
  674. clone: function () {
  675. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  676. }
  677. };
  678. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  679. return qm.copy( qa ).slerp( qb, t );
  680. }
  681. /**
  682. * @author mrdoob / http://mrdoob.com/
  683. * @author philogb / http://blog.thejit.org/
  684. * @author egraether / http://egraether.com/
  685. * @author zz85 / http://www.lab4games.net/zz85/blog
  686. */
  687. THREE.Vector2 = function ( x, y ) {
  688. this.x = x || 0;
  689. this.y = y || 0;
  690. };
  691. THREE.Vector2.prototype = {
  692. constructor: THREE.Vector2,
  693. set: function ( x, y ) {
  694. this.x = x;
  695. this.y = y;
  696. return this;
  697. },
  698. setX: function ( x ) {
  699. this.x = x;
  700. return this;
  701. },
  702. setY: function ( y ) {
  703. this.y = y;
  704. return this;
  705. },
  706. setComponent: function ( index, value ) {
  707. switch ( index ) {
  708. case 0: this.x = value; break;
  709. case 1: this.y = value; break;
  710. default: throw new Error( "index is out of range: " + index );
  711. }
  712. },
  713. getComponent: function ( index ) {
  714. switch ( index ) {
  715. case 0: return this.x;
  716. case 1: return this.y;
  717. default: throw new Error( "index is out of range: " + index );
  718. }
  719. },
  720. copy: function ( v ) {
  721. this.x = v.x;
  722. this.y = v.y;
  723. return this;
  724. },
  725. add: function ( v, w ) {
  726. if ( w !== undefined ) {
  727. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  728. return this.addVectors( v, w );
  729. }
  730. this.x += v.x;
  731. this.y += v.y;
  732. return this;
  733. },
  734. addVectors: function ( a, b ) {
  735. this.x = a.x + b.x;
  736. this.y = a.y + b.y;
  737. return this;
  738. },
  739. addScalar: function ( s ) {
  740. this.x += s;
  741. this.y += s;
  742. return this;
  743. },
  744. sub: function ( v, w ) {
  745. if ( w !== undefined ) {
  746. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  747. return this.subVectors( v, w );
  748. }
  749. this.x -= v.x;
  750. this.y -= v.y;
  751. return this;
  752. },
  753. subVectors: function ( a, b ) {
  754. this.x = a.x - b.x;
  755. this.y = a.y - b.y;
  756. return this;
  757. },
  758. multiplyScalar: function ( s ) {
  759. this.x *= s;
  760. this.y *= s;
  761. return this;
  762. },
  763. divideScalar: function ( scalar ) {
  764. if ( scalar !== 0 ) {
  765. var invScalar = 1 / scalar;
  766. this.x *= invScalar;
  767. this.y *= invScalar;
  768. } else {
  769. this.x = 0;
  770. this.y = 0;
  771. }
  772. return this;
  773. },
  774. min: function ( v ) {
  775. if ( this.x > v.x ) {
  776. this.x = v.x;
  777. }
  778. if ( this.y > v.y ) {
  779. this.y = v.y;
  780. }
  781. return this;
  782. },
  783. max: function ( v ) {
  784. if ( this.x < v.x ) {
  785. this.x = v.x;
  786. }
  787. if ( this.y < v.y ) {
  788. this.y = v.y;
  789. }
  790. return this;
  791. },
  792. clamp: function ( min, max ) {
  793. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  794. if ( this.x < min.x ) {
  795. this.x = min.x;
  796. } else if ( this.x > max.x ) {
  797. this.x = max.x;
  798. }
  799. if ( this.y < min.y ) {
  800. this.y = min.y;
  801. } else if ( this.y > max.y ) {
  802. this.y = max.y;
  803. }
  804. return this;
  805. },
  806. negate: function() {
  807. return this.multiplyScalar( - 1 );
  808. },
  809. dot: function ( v ) {
  810. return this.x * v.x + this.y * v.y;
  811. },
  812. lengthSq: function () {
  813. return this.x * this.x + this.y * this.y;
  814. },
  815. length: function () {
  816. return Math.sqrt( this.x * this.x + this.y * this.y );
  817. },
  818. normalize: function () {
  819. return this.divideScalar( this.length() );
  820. },
  821. distanceTo: function ( v ) {
  822. return Math.sqrt( this.distanceToSquared( v ) );
  823. },
  824. distanceToSquared: function ( v ) {
  825. var dx = this.x - v.x, dy = this.y - v.y;
  826. return dx * dx + dy * dy;
  827. },
  828. setLength: function ( l ) {
  829. var oldLength = this.length();
  830. if ( oldLength !== 0 && l !== oldLength ) {
  831. this.multiplyScalar( l / oldLength );
  832. }
  833. return this;
  834. },
  835. lerp: function ( v, alpha ) {
  836. this.x += ( v.x - this.x ) * alpha;
  837. this.y += ( v.y - this.y ) * alpha;
  838. return this;
  839. },
  840. equals: function( v ) {
  841. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  842. },
  843. fromArray: function ( array ) {
  844. this.x = array[ 0 ];
  845. this.y = array[ 1 ];
  846. return this;
  847. },
  848. toArray: function () {
  849. return [ this.x, this.y ];
  850. },
  851. clone: function () {
  852. return new THREE.Vector2( this.x, this.y );
  853. }
  854. };
  855. /**
  856. * @author mrdoob / http://mrdoob.com/
  857. * @author *kile / http://kile.stravaganza.org/
  858. * @author philogb / http://blog.thejit.org/
  859. * @author mikael emtinger / http://gomo.se/
  860. * @author egraether / http://egraether.com/
  861. * @author WestLangley / http://github.com/WestLangley
  862. */
  863. THREE.Vector3 = function ( x, y, z ) {
  864. this.x = x || 0;
  865. this.y = y || 0;
  866. this.z = z || 0;
  867. };
  868. THREE.Vector3.prototype = {
  869. constructor: THREE.Vector3,
  870. set: function ( x, y, z ) {
  871. this.x = x;
  872. this.y = y;
  873. this.z = z;
  874. return this;
  875. },
  876. setX: function ( x ) {
  877. this.x = x;
  878. return this;
  879. },
  880. setY: function ( y ) {
  881. this.y = y;
  882. return this;
  883. },
  884. setZ: function ( z ) {
  885. this.z = z;
  886. return this;
  887. },
  888. setComponent: function ( index, value ) {
  889. switch ( index ) {
  890. case 0: this.x = value; break;
  891. case 1: this.y = value; break;
  892. case 2: this.z = value; break;
  893. default: throw new Error( "index is out of range: " + index );
  894. }
  895. },
  896. getComponent: function ( index ) {
  897. switch ( index ) {
  898. case 0: return this.x;
  899. case 1: return this.y;
  900. case 2: return this.z;
  901. default: throw new Error( "index is out of range: " + index );
  902. }
  903. },
  904. copy: function ( v ) {
  905. this.x = v.x;
  906. this.y = v.y;
  907. this.z = v.z;
  908. return this;
  909. },
  910. add: function ( v, w ) {
  911. if ( w !== undefined ) {
  912. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  913. return this.addVectors( v, w );
  914. }
  915. this.x += v.x;
  916. this.y += v.y;
  917. this.z += v.z;
  918. return this;
  919. },
  920. addScalar: function ( s ) {
  921. this.x += s;
  922. this.y += s;
  923. this.z += s;
  924. return this;
  925. },
  926. addVectors: function ( a, b ) {
  927. this.x = a.x + b.x;
  928. this.y = a.y + b.y;
  929. this.z = a.z + b.z;
  930. return this;
  931. },
  932. sub: function ( v, w ) {
  933. if ( w !== undefined ) {
  934. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  935. return this.subVectors( v, w );
  936. }
  937. this.x -= v.x;
  938. this.y -= v.y;
  939. this.z -= v.z;
  940. return this;
  941. },
  942. subVectors: function ( a, b ) {
  943. this.x = a.x - b.x;
  944. this.y = a.y - b.y;
  945. this.z = a.z - b.z;
  946. return this;
  947. },
  948. multiply: function ( v, w ) {
  949. if ( w !== undefined ) {
  950. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  951. return this.multiplyVectors( v, w );
  952. }
  953. this.x *= v.x;
  954. this.y *= v.y;
  955. this.z *= v.z;
  956. return this;
  957. },
  958. multiplyScalar: function ( scalar ) {
  959. this.x *= scalar;
  960. this.y *= scalar;
  961. this.z *= scalar;
  962. return this;
  963. },
  964. multiplyVectors: function ( a, b ) {
  965. this.x = a.x * b.x;
  966. this.y = a.y * b.y;
  967. this.z = a.z * b.z;
  968. return this;
  969. },
  970. applyMatrix3: function ( m ) {
  971. var x = this.x;
  972. var y = this.y;
  973. var z = this.z;
  974. var e = m.elements;
  975. this.x = e[0] * x + e[3] * y + e[6] * z;
  976. this.y = e[1] * x + e[4] * y + e[7] * z;
  977. this.z = e[2] * x + e[5] * y + e[8] * z;
  978. return this;
  979. },
  980. applyMatrix4: function ( m ) {
  981. // input: THREE.Matrix4 affine matrix
  982. var x = this.x, y = this.y, z = this.z;
  983. var e = m.elements;
  984. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  985. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  986. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  987. return this;
  988. },
  989. applyProjection: function ( m ) {
  990. // input: THREE.Matrix4 projection matrix
  991. var x = this.x, y = this.y, z = this.z;
  992. var e = m.elements;
  993. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  994. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  995. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  996. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  997. return this;
  998. },
  999. applyQuaternion: function ( q ) {
  1000. var x = this.x;
  1001. var y = this.y;
  1002. var z = this.z;
  1003. var qx = q.x;
  1004. var qy = q.y;
  1005. var qz = q.z;
  1006. var qw = q.w;
  1007. // calculate quat * vector
  1008. var ix = qw * x + qy * z - qz * y;
  1009. var iy = qw * y + qz * x - qx * z;
  1010. var iz = qw * z + qx * y - qy * x;
  1011. var iw = -qx * x - qy * y - qz * z;
  1012. // calculate result * inverse quat
  1013. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1014. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1015. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1016. return this;
  1017. },
  1018. transformDirection: function ( m ) {
  1019. // input: THREE.Matrix4 affine matrix
  1020. // vector interpreted as a direction
  1021. var x = this.x, y = this.y, z = this.z;
  1022. var e = m.elements;
  1023. this.x = e[0] * x + e[4] * y + e[8] * z;
  1024. this.y = e[1] * x + e[5] * y + e[9] * z;
  1025. this.z = e[2] * x + e[6] * y + e[10] * z;
  1026. this.normalize();
  1027. return this;
  1028. },
  1029. divide: function ( v ) {
  1030. this.x /= v.x;
  1031. this.y /= v.y;
  1032. this.z /= v.z;
  1033. return this;
  1034. },
  1035. divideScalar: function ( scalar ) {
  1036. if ( scalar !== 0 ) {
  1037. var invScalar = 1 / scalar;
  1038. this.x *= invScalar;
  1039. this.y *= invScalar;
  1040. this.z *= invScalar;
  1041. } else {
  1042. this.x = 0;
  1043. this.y = 0;
  1044. this.z = 0;
  1045. }
  1046. return this;
  1047. },
  1048. min: function ( v ) {
  1049. if ( this.x > v.x ) {
  1050. this.x = v.x;
  1051. }
  1052. if ( this.y > v.y ) {
  1053. this.y = v.y;
  1054. }
  1055. if ( this.z > v.z ) {
  1056. this.z = v.z;
  1057. }
  1058. return this;
  1059. },
  1060. max: function ( v ) {
  1061. if ( this.x < v.x ) {
  1062. this.x = v.x;
  1063. }
  1064. if ( this.y < v.y ) {
  1065. this.y = v.y;
  1066. }
  1067. if ( this.z < v.z ) {
  1068. this.z = v.z;
  1069. }
  1070. return this;
  1071. },
  1072. clamp: function ( min, max ) {
  1073. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1074. if ( this.x < min.x ) {
  1075. this.x = min.x;
  1076. } else if ( this.x > max.x ) {
  1077. this.x = max.x;
  1078. }
  1079. if ( this.y < min.y ) {
  1080. this.y = min.y;
  1081. } else if ( this.y > max.y ) {
  1082. this.y = max.y;
  1083. }
  1084. if ( this.z < min.z ) {
  1085. this.z = min.z;
  1086. } else if ( this.z > max.z ) {
  1087. this.z = max.z;
  1088. }
  1089. return this;
  1090. },
  1091. negate: function () {
  1092. return this.multiplyScalar( - 1 );
  1093. },
  1094. dot: function ( v ) {
  1095. return this.x * v.x + this.y * v.y + this.z * v.z;
  1096. },
  1097. lengthSq: function () {
  1098. return this.x * this.x + this.y * this.y + this.z * this.z;
  1099. },
  1100. length: function () {
  1101. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1102. },
  1103. lengthManhattan: function () {
  1104. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1105. },
  1106. normalize: function () {
  1107. return this.divideScalar( this.length() );
  1108. },
  1109. setLength: function ( l ) {
  1110. var oldLength = this.length();
  1111. if ( oldLength !== 0 && l !== oldLength ) {
  1112. this.multiplyScalar( l / oldLength );
  1113. }
  1114. return this;
  1115. },
  1116. lerp: function ( v, alpha ) {
  1117. this.x += ( v.x - this.x ) * alpha;
  1118. this.y += ( v.y - this.y ) * alpha;
  1119. this.z += ( v.z - this.z ) * alpha;
  1120. return this;
  1121. },
  1122. cross: function ( v, w ) {
  1123. if ( w !== undefined ) {
  1124. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1125. return this.crossVectors( v, w );
  1126. }
  1127. var x = this.x, y = this.y, z = this.z;
  1128. this.x = y * v.z - z * v.y;
  1129. this.y = z * v.x - x * v.z;
  1130. this.z = x * v.y - y * v.x;
  1131. return this;
  1132. },
  1133. crossVectors: function ( a, b ) {
  1134. var ax = a.x, ay = a.y, az = a.z;
  1135. var bx = b.x, by = b.y, bz = b.z;
  1136. this.x = ay * bz - az * by;
  1137. this.y = az * bx - ax * bz;
  1138. this.z = ax * by - ay * bx;
  1139. return this;
  1140. },
  1141. angleTo: function ( v ) {
  1142. var theta = this.dot( v ) / ( this.length() * v.length() );
  1143. // clamp, to handle numerical problems
  1144. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1145. },
  1146. distanceTo: function ( v ) {
  1147. return Math.sqrt( this.distanceToSquared( v ) );
  1148. },
  1149. distanceToSquared: function ( v ) {
  1150. var dx = this.x - v.x;
  1151. var dy = this.y - v.y;
  1152. var dz = this.z - v.z;
  1153. return dx * dx + dy * dy + dz * dz;
  1154. },
  1155. setEulerFromRotationMatrix: function ( m, order ) {
  1156. console.error( "REMOVED: Vector3\'s setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code.");
  1157. },
  1158. setEulerFromQuaternion: function ( q, order ) {
  1159. console.error( "REMOVED: Vector3\'s setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code.");
  1160. },
  1161. getPositionFromMatrix: function ( m ) {
  1162. this.x = m.elements[12];
  1163. this.y = m.elements[13];
  1164. this.z = m.elements[14];
  1165. return this;
  1166. },
  1167. getScaleFromMatrix: function ( m ) {
  1168. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  1169. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  1170. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  1171. this.x = sx;
  1172. this.y = sy;
  1173. this.z = sz;
  1174. return this;
  1175. },
  1176. getColumnFromMatrix: function ( index, matrix ) {
  1177. var offset = index * 4;
  1178. var me = matrix.elements;
  1179. this.x = me[ offset ];
  1180. this.y = me[ offset + 1 ];
  1181. this.z = me[ offset + 2 ];
  1182. return this;
  1183. },
  1184. equals: function ( v ) {
  1185. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1186. },
  1187. fromArray: function ( array ) {
  1188. this.x = array[ 0 ];
  1189. this.y = array[ 1 ];
  1190. this.z = array[ 2 ];
  1191. return this;
  1192. },
  1193. toArray: function () {
  1194. return [ this.x, this.y, this.z ];
  1195. },
  1196. clone: function () {
  1197. return new THREE.Vector3( this.x, this.y, this.z );
  1198. }
  1199. };
  1200. THREE.extend( THREE.Vector3.prototype, {
  1201. applyEuler: function () {
  1202. var quaternion = new THREE.Quaternion();
  1203. return function ( euler ) {
  1204. if ( euler instanceof THREE.Euler === false ) {
  1205. console.error( 'ERROR: Vector3\'s .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  1206. }
  1207. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1208. return this;
  1209. };
  1210. }(),
  1211. applyAxisAngle: function () {
  1212. var quaternion = new THREE.Quaternion();
  1213. return function ( axis, angle ) {
  1214. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1215. return this;
  1216. };
  1217. }(),
  1218. projectOnVector: function () {
  1219. var v1 = new THREE.Vector3();
  1220. return function ( vector ) {
  1221. v1.copy( vector ).normalize();
  1222. var d = this.dot( v1 );
  1223. return this.copy( v1 ).multiplyScalar( d );
  1224. };
  1225. }(),
  1226. projectOnPlane: function () {
  1227. var v1 = new THREE.Vector3();
  1228. return function ( planeNormal ) {
  1229. v1.copy( this ).projectOnVector( planeNormal );
  1230. return this.sub( v1 );
  1231. }
  1232. }(),
  1233. reflect: function () {
  1234. var v1 = new THREE.Vector3();
  1235. return function ( vector ) {
  1236. v1.copy( this ).projectOnVector( vector ).multiplyScalar( 2 );
  1237. return this.subVectors( v1, this );
  1238. }
  1239. }()
  1240. } );
  1241. /**
  1242. * @author supereggbert / http://www.paulbrunt.co.uk/
  1243. * @author philogb / http://blog.thejit.org/
  1244. * @author mikael emtinger / http://gomo.se/
  1245. * @author egraether / http://egraether.com/
  1246. * @author WestLangley / http://github.com/WestLangley
  1247. */
  1248. THREE.Vector4 = function ( x, y, z, w ) {
  1249. this.x = x || 0;
  1250. this.y = y || 0;
  1251. this.z = z || 0;
  1252. this.w = ( w !== undefined ) ? w : 1;
  1253. };
  1254. THREE.Vector4.prototype = {
  1255. constructor: THREE.Vector4,
  1256. set: function ( x, y, z, w ) {
  1257. this.x = x;
  1258. this.y = y;
  1259. this.z = z;
  1260. this.w = w;
  1261. return this;
  1262. },
  1263. setX: function ( x ) {
  1264. this.x = x;
  1265. return this;
  1266. },
  1267. setY: function ( y ) {
  1268. this.y = y;
  1269. return this;
  1270. },
  1271. setZ: function ( z ) {
  1272. this.z = z;
  1273. return this;
  1274. },
  1275. setW: function ( w ) {
  1276. this.w = w;
  1277. return this;
  1278. },
  1279. setComponent: function ( index, value ) {
  1280. switch ( index ) {
  1281. case 0: this.x = value; break;
  1282. case 1: this.y = value; break;
  1283. case 2: this.z = value; break;
  1284. case 3: this.w = value; break;
  1285. default: throw new Error( "index is out of range: " + index );
  1286. }
  1287. },
  1288. getComponent: function ( index ) {
  1289. switch ( index ) {
  1290. case 0: return this.x;
  1291. case 1: return this.y;
  1292. case 2: return this.z;
  1293. case 3: return this.w;
  1294. default: throw new Error( "index is out of range: " + index );
  1295. }
  1296. },
  1297. copy: function ( v ) {
  1298. this.x = v.x;
  1299. this.y = v.y;
  1300. this.z = v.z;
  1301. this.w = ( v.w !== undefined ) ? v.w : 1;
  1302. return this;
  1303. },
  1304. add: function ( v, w ) {
  1305. if ( w !== undefined ) {
  1306. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1307. return this.addVectors( v, w );
  1308. }
  1309. this.x += v.x;
  1310. this.y += v.y;
  1311. this.z += v.z;
  1312. this.w += v.w;
  1313. return this;
  1314. },
  1315. addScalar: function ( s ) {
  1316. this.x += s;
  1317. this.y += s;
  1318. this.z += s;
  1319. this.w += s;
  1320. return this;
  1321. },
  1322. addVectors: function ( a, b ) {
  1323. this.x = a.x + b.x;
  1324. this.y = a.y + b.y;
  1325. this.z = a.z + b.z;
  1326. this.w = a.w + b.w;
  1327. return this;
  1328. },
  1329. sub: function ( v, w ) {
  1330. if ( w !== undefined ) {
  1331. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1332. return this.subVectors( v, w );
  1333. }
  1334. this.x -= v.x;
  1335. this.y -= v.y;
  1336. this.z -= v.z;
  1337. this.w -= v.w;
  1338. return this;
  1339. },
  1340. subVectors: function ( a, b ) {
  1341. this.x = a.x - b.x;
  1342. this.y = a.y - b.y;
  1343. this.z = a.z - b.z;
  1344. this.w = a.w - b.w;
  1345. return this;
  1346. },
  1347. multiplyScalar: function ( scalar ) {
  1348. this.x *= scalar;
  1349. this.y *= scalar;
  1350. this.z *= scalar;
  1351. this.w *= scalar;
  1352. return this;
  1353. },
  1354. applyMatrix4: function ( m ) {
  1355. var x = this.x;
  1356. var y = this.y;
  1357. var z = this.z;
  1358. var w = this.w;
  1359. var e = m.elements;
  1360. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1361. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1362. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1363. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1364. return this;
  1365. },
  1366. divideScalar: function ( scalar ) {
  1367. if ( scalar !== 0 ) {
  1368. var invScalar = 1 / scalar;
  1369. this.x *= invScalar;
  1370. this.y *= invScalar;
  1371. this.z *= invScalar;
  1372. this.w *= invScalar;
  1373. } else {
  1374. this.x = 0;
  1375. this.y = 0;
  1376. this.z = 0;
  1377. this.w = 1;
  1378. }
  1379. return this;
  1380. },
  1381. setAxisAngleFromQuaternion: function ( q ) {
  1382. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1383. // q is assumed to be normalized
  1384. this.w = 2 * Math.acos( q.w );
  1385. var s = Math.sqrt( 1 - q.w * q.w );
  1386. if ( s < 0.0001 ) {
  1387. this.x = 1;
  1388. this.y = 0;
  1389. this.z = 0;
  1390. } else {
  1391. this.x = q.x / s;
  1392. this.y = q.y / s;
  1393. this.z = q.z / s;
  1394. }
  1395. return this;
  1396. },
  1397. setAxisAngleFromRotationMatrix: function ( m ) {
  1398. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1399. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1400. var angle, x, y, z, // variables for result
  1401. epsilon = 0.01, // margin to allow for rounding errors
  1402. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1403. te = m.elements,
  1404. m11 = te[0], m12 = te[4], m13 = te[8],
  1405. m21 = te[1], m22 = te[5], m23 = te[9],
  1406. m31 = te[2], m32 = te[6], m33 = te[10];
  1407. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1408. && ( Math.abs( m13 - m31 ) < epsilon )
  1409. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1410. // singularity found
  1411. // first check for identity matrix which must have +1 for all terms
  1412. // in leading diagonal and zero in other terms
  1413. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1414. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1415. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1416. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1417. // this singularity is identity matrix so angle = 0
  1418. this.set( 1, 0, 0, 0 );
  1419. return this; // zero angle, arbitrary axis
  1420. }
  1421. // otherwise this singularity is angle = 180
  1422. angle = Math.PI;
  1423. var xx = ( m11 + 1 ) / 2;
  1424. var yy = ( m22 + 1 ) / 2;
  1425. var zz = ( m33 + 1 ) / 2;
  1426. var xy = ( m12 + m21 ) / 4;
  1427. var xz = ( m13 + m31 ) / 4;
  1428. var yz = ( m23 + m32 ) / 4;
  1429. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1430. if ( xx < epsilon ) {
  1431. x = 0;
  1432. y = 0.707106781;
  1433. z = 0.707106781;
  1434. } else {
  1435. x = Math.sqrt( xx );
  1436. y = xy / x;
  1437. z = xz / x;
  1438. }
  1439. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1440. if ( yy < epsilon ) {
  1441. x = 0.707106781;
  1442. y = 0;
  1443. z = 0.707106781;
  1444. } else {
  1445. y = Math.sqrt( yy );
  1446. x = xy / y;
  1447. z = yz / y;
  1448. }
  1449. } else { // m33 is the largest diagonal term so base result on this
  1450. if ( zz < epsilon ) {
  1451. x = 0.707106781;
  1452. y = 0.707106781;
  1453. z = 0;
  1454. } else {
  1455. z = Math.sqrt( zz );
  1456. x = xz / z;
  1457. y = yz / z;
  1458. }
  1459. }
  1460. this.set( x, y, z, angle );
  1461. return this; // return 180 deg rotation
  1462. }
  1463. // as we have reached here there are no singularities so we can handle normally
  1464. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1465. + ( m13 - m31 ) * ( m13 - m31 )
  1466. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1467. if ( Math.abs( s ) < 0.001 ) s = 1;
  1468. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1469. // caught by singularity test above, but I've left it in just in case
  1470. this.x = ( m32 - m23 ) / s;
  1471. this.y = ( m13 - m31 ) / s;
  1472. this.z = ( m21 - m12 ) / s;
  1473. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1474. return this;
  1475. },
  1476. min: function ( v ) {
  1477. if ( this.x > v.x ) {
  1478. this.x = v.x;
  1479. }
  1480. if ( this.y > v.y ) {
  1481. this.y = v.y;
  1482. }
  1483. if ( this.z > v.z ) {
  1484. this.z = v.z;
  1485. }
  1486. if ( this.w > v.w ) {
  1487. this.w = v.w;
  1488. }
  1489. return this;
  1490. },
  1491. max: function ( v ) {
  1492. if ( this.x < v.x ) {
  1493. this.x = v.x;
  1494. }
  1495. if ( this.y < v.y ) {
  1496. this.y = v.y;
  1497. }
  1498. if ( this.z < v.z ) {
  1499. this.z = v.z;
  1500. }
  1501. if ( this.w < v.w ) {
  1502. this.w = v.w;
  1503. }
  1504. return this;
  1505. },
  1506. clamp: function ( min, max ) {
  1507. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1508. if ( this.x < min.x ) {
  1509. this.x = min.x;
  1510. } else if ( this.x > max.x ) {
  1511. this.x = max.x;
  1512. }
  1513. if ( this.y < min.y ) {
  1514. this.y = min.y;
  1515. } else if ( this.y > max.y ) {
  1516. this.y = max.y;
  1517. }
  1518. if ( this.z < min.z ) {
  1519. this.z = min.z;
  1520. } else if ( this.z > max.z ) {
  1521. this.z = max.z;
  1522. }
  1523. if ( this.w < min.w ) {
  1524. this.w = min.w;
  1525. } else if ( this.w > max.w ) {
  1526. this.w = max.w;
  1527. }
  1528. return this;
  1529. },
  1530. negate: function() {
  1531. return this.multiplyScalar( -1 );
  1532. },
  1533. dot: function ( v ) {
  1534. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1535. },
  1536. lengthSq: function () {
  1537. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1538. },
  1539. length: function () {
  1540. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1541. },
  1542. lengthManhattan: function () {
  1543. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1544. },
  1545. normalize: function () {
  1546. return this.divideScalar( this.length() );
  1547. },
  1548. setLength: function ( l ) {
  1549. var oldLength = this.length();
  1550. if ( oldLength !== 0 && l !== oldLength ) {
  1551. this.multiplyScalar( l / oldLength );
  1552. }
  1553. return this;
  1554. },
  1555. lerp: function ( v, alpha ) {
  1556. this.x += ( v.x - this.x ) * alpha;
  1557. this.y += ( v.y - this.y ) * alpha;
  1558. this.z += ( v.z - this.z ) * alpha;
  1559. this.w += ( v.w - this.w ) * alpha;
  1560. return this;
  1561. },
  1562. equals: function ( v ) {
  1563. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1564. },
  1565. fromArray: function ( array ) {
  1566. this.x = array[ 0 ];
  1567. this.y = array[ 1 ];
  1568. this.z = array[ 2 ];
  1569. this.w = array[ 3 ];
  1570. return this;
  1571. },
  1572. toArray: function () {
  1573. return [ this.x, this.y, this.z, this.w ];
  1574. },
  1575. clone: function () {
  1576. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1577. }
  1578. };
  1579. /**
  1580. * @author mrdoob / http://mrdoob.com/
  1581. * @author WestLangley / http://github.com/WestLangley
  1582. * @author bhouston / http://exocortex.com
  1583. */
  1584. THREE.Euler = function ( x, y, z, order ) {
  1585. this._x = x || 0;
  1586. this._y = y || 0;
  1587. this._z = z || 0;
  1588. this._order = order || THREE.Euler.DefaultOrder;
  1589. };
  1590. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1591. THREE.Euler.DefaultOrder = 'XYZ';
  1592. THREE.Euler.prototype = {
  1593. constructor: THREE.Euler,
  1594. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1595. _quaternion: undefined,
  1596. _updateQuaternion: function () {
  1597. if ( this._quaternion !== undefined ) {
  1598. this._quaternion.setFromEuler( this, false );
  1599. }
  1600. },
  1601. get x () {
  1602. return this._x;
  1603. },
  1604. set x ( value ) {
  1605. this._x = value;
  1606. this._updateQuaternion();
  1607. },
  1608. get y () {
  1609. return this._y;
  1610. },
  1611. set y ( value ) {
  1612. this._y = value;
  1613. this._updateQuaternion();
  1614. },
  1615. get z () {
  1616. return this._z;
  1617. },
  1618. set z ( value ) {
  1619. this._z = value;
  1620. this._updateQuaternion();
  1621. },
  1622. get order () {
  1623. return this._order;
  1624. },
  1625. set order ( value ) {
  1626. this._order = value;
  1627. this._updateQuaternion();
  1628. },
  1629. set: function ( x, y, z, order ) {
  1630. this._x = x;
  1631. this._y = y;
  1632. this._z = z;
  1633. this._order = order || this._order;
  1634. this._updateQuaternion();
  1635. return this;
  1636. },
  1637. copy: function ( euler ) {
  1638. this._x = euler._x;
  1639. this._y = euler._y;
  1640. this._z = euler._z;
  1641. this._order = euler._order;
  1642. this._updateQuaternion();
  1643. return this;
  1644. },
  1645. setFromRotationMatrix: function ( m, order ) {
  1646. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1647. // clamp, to handle numerical problems
  1648. function clamp( x ) {
  1649. return Math.min( Math.max( x, -1 ), 1 );
  1650. }
  1651. var te = m.elements;
  1652. var m11 = te[0], m12 = te[4], m13 = te[8];
  1653. var m21 = te[1], m22 = te[5], m23 = te[9];
  1654. var m31 = te[2], m32 = te[6], m33 = te[10];
  1655. order = order || this._order;
  1656. if ( order === 'XYZ' ) {
  1657. this._y = Math.asin( clamp( m13 ) );
  1658. if ( Math.abs( m13 ) < 0.99999 ) {
  1659. this._x = Math.atan2( - m23, m33 );
  1660. this._z = Math.atan2( - m12, m11 );
  1661. } else {
  1662. this._x = Math.atan2( m32, m22 );
  1663. this._z = 0;
  1664. }
  1665. } else if ( order === 'YXZ' ) {
  1666. this._x = Math.asin( - clamp( m23 ) );
  1667. if ( Math.abs( m23 ) < 0.99999 ) {
  1668. this._y = Math.atan2( m13, m33 );
  1669. this._z = Math.atan2( m21, m22 );
  1670. } else {
  1671. this._y = Math.atan2( - m31, m11 );
  1672. this._z = 0;
  1673. }
  1674. } else if ( order === 'ZXY' ) {
  1675. this._x = Math.asin( clamp( m32 ) );
  1676. if ( Math.abs( m32 ) < 0.99999 ) {
  1677. this._y = Math.atan2( - m31, m33 );
  1678. this._z = Math.atan2( - m12, m22 );
  1679. } else {
  1680. this._y = 0;
  1681. this._z = Math.atan2( m21, m11 );
  1682. }
  1683. } else if ( order === 'ZYX' ) {
  1684. this._y = Math.asin( - clamp( m31 ) );
  1685. if ( Math.abs( m31 ) < 0.99999 ) {
  1686. this._x = Math.atan2( m32, m33 );
  1687. this._z = Math.atan2( m21, m11 );
  1688. } else {
  1689. this._x = 0;
  1690. this._z = Math.atan2( - m12, m22 );
  1691. }
  1692. } else if ( order === 'YZX' ) {
  1693. this._z = Math.asin( clamp( m21 ) );
  1694. if ( Math.abs( m21 ) < 0.99999 ) {
  1695. this._x = Math.atan2( - m23, m22 );
  1696. this._y = Math.atan2( - m31, m11 );
  1697. } else {
  1698. this._x = 0;
  1699. this._y = Math.atan2( m13, m33 );
  1700. }
  1701. } else if ( order === 'XZY' ) {
  1702. this._z = Math.asin( - clamp( m12 ) );
  1703. if ( Math.abs( m12 ) < 0.99999 ) {
  1704. this._x = Math.atan2( m32, m22 );
  1705. this._y = Math.atan2( m13, m11 );
  1706. } else {
  1707. this._x = Math.atan2( - m23, m33 );
  1708. this._y = 0;
  1709. }
  1710. } else {
  1711. console.warn( 'WARNING: Euler.setFromRotationMatrix() given unsupported order: ' + order )
  1712. }
  1713. this._order = order;
  1714. this._updateQuaternion();
  1715. return this;
  1716. },
  1717. setFromQuaternion: function ( q, order, update ) {
  1718. // q is assumed to be normalized
  1719. // clamp, to handle numerical problems
  1720. function clamp( x ) {
  1721. return Math.min( Math.max( x, -1 ), 1 );
  1722. }
  1723. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1724. var sqx = q.x * q.x;
  1725. var sqy = q.y * q.y;
  1726. var sqz = q.z * q.z;
  1727. var sqw = q.w * q.w;
  1728. order = order || this._order;
  1729. if ( order === 'XYZ' ) {
  1730. this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1731. this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1732. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1733. } else if ( order === 'YXZ' ) {
  1734. this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1735. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1736. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1737. } else if ( order === 'ZXY' ) {
  1738. this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1739. this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1740. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1741. } else if ( order === 'ZYX' ) {
  1742. this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1743. this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1744. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1745. } else if ( order === 'YZX' ) {
  1746. this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1747. this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1748. this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1749. } else if ( order === 'XZY' ) {
  1750. this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1751. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1752. this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1753. } else {
  1754. console.warn( 'WARNING: Euler.setFromQuaternion() given unsupported order: ' + order )
  1755. }
  1756. this._order = order;
  1757. if ( update !== false ) this._updateQuaternion();
  1758. return this;
  1759. },
  1760. reorder: function () {
  1761. // WARNING: this discards revolution information -bhouston
  1762. var q = new THREE.Quaternion();
  1763. return function ( newOrder ) {
  1764. q.setFromEuler( this );
  1765. this.setFromQuaternion( q, newOrder );
  1766. };
  1767. }(),
  1768. fromArray: function ( array ) {
  1769. this._x = array[ 0 ];
  1770. this._y = array[ 1 ];
  1771. this._z = array[ 2 ];
  1772. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1773. this._updateQuaternion();
  1774. return this;
  1775. },
  1776. toArray: function () {
  1777. return [ this._x, this._y, this._z, this._order ];
  1778. },
  1779. equals: function ( euler ) {
  1780. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1781. },
  1782. clone: function () {
  1783. return new THREE.Euler( this._x, this._y, this._z, this._order );
  1784. }
  1785. };
  1786. /**
  1787. * @author bhouston / http://exocortex.com
  1788. */
  1789. THREE.Line3 = function ( start, end ) {
  1790. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1791. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1792. };
  1793. THREE.Line3.prototype = {
  1794. constructor: THREE.Line3,
  1795. set: function ( start, end ) {
  1796. this.start.copy( start );
  1797. this.end.copy( end );
  1798. return this;
  1799. },
  1800. copy: function ( line ) {
  1801. this.start.copy( line.start );
  1802. this.end.copy( line.end );
  1803. return this;
  1804. },
  1805. center: function ( optionalTarget ) {
  1806. var result = optionalTarget || new THREE.Vector3();
  1807. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1808. },
  1809. delta: function ( optionalTarget ) {
  1810. var result = optionalTarget || new THREE.Vector3();
  1811. return result.subVectors( this.end, this.start );
  1812. },
  1813. distanceSq: function () {
  1814. return this.start.distanceToSquared( this.end );
  1815. },
  1816. distance: function () {
  1817. return this.start.distanceTo( this.end );
  1818. },
  1819. at: function ( t, optionalTarget ) {
  1820. var result = optionalTarget || new THREE.Vector3();
  1821. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1822. },
  1823. closestPointToPointParameter: function() {
  1824. var startP = new THREE.Vector3();
  1825. var startEnd = new THREE.Vector3();
  1826. return function ( point, clampToLine ) {
  1827. startP.subVectors( point, this.start );
  1828. startEnd.subVectors( this.end, this.start );
  1829. var startEnd2 = startEnd.dot( startEnd );
  1830. var startEnd_startP = startEnd.dot( startP );
  1831. var t = startEnd_startP / startEnd2;
  1832. if ( clampToLine ) {
  1833. t = THREE.Math.clamp( t, 0, 1 );
  1834. }
  1835. return t;
  1836. };
  1837. }(),
  1838. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1839. var t = this.closestPointToPointParameter( point, clampToLine );
  1840. var result = optionalTarget || new THREE.Vector3();
  1841. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1842. },
  1843. applyMatrix4: function ( matrix ) {
  1844. this.start.applyMatrix4( matrix );
  1845. this.end.applyMatrix4( matrix );
  1846. return this;
  1847. },
  1848. equals: function ( line ) {
  1849. return line.start.equals( this.start ) && line.end.equals( this.end );
  1850. },
  1851. clone: function () {
  1852. return new THREE.Line3().copy( this );
  1853. }
  1854. };
  1855. /**
  1856. * @author bhouston / http://exocortex.com
  1857. */
  1858. THREE.Box2 = function ( min, max ) {
  1859. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1860. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1861. };
  1862. THREE.Box2.prototype = {
  1863. constructor: THREE.Box2,
  1864. set: function ( min, max ) {
  1865. this.min.copy( min );
  1866. this.max.copy( max );
  1867. return this;
  1868. },
  1869. setFromPoints: function ( points ) {
  1870. if ( points.length > 0 ) {
  1871. var point = points[ 0 ];
  1872. this.min.copy( point );
  1873. this.max.copy( point );
  1874. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1875. point = points[ i ];
  1876. if ( point.x < this.min.x ) {
  1877. this.min.x = point.x;
  1878. } else if ( point.x > this.max.x ) {
  1879. this.max.x = point.x;
  1880. }
  1881. if ( point.y < this.min.y ) {
  1882. this.min.y = point.y;
  1883. } else if ( point.y > this.max.y ) {
  1884. this.max.y = point.y;
  1885. }
  1886. }
  1887. } else {
  1888. this.makeEmpty();
  1889. }
  1890. return this;
  1891. },
  1892. setFromCenterAndSize: function () {
  1893. var v1 = new THREE.Vector2();
  1894. return function ( center, size ) {
  1895. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1896. this.min.copy( center ).sub( halfSize );
  1897. this.max.copy( center ).add( halfSize );
  1898. return this;
  1899. };
  1900. }(),
  1901. copy: function ( box ) {
  1902. this.min.copy( box.min );
  1903. this.max.copy( box.max );
  1904. return this;
  1905. },
  1906. makeEmpty: function () {
  1907. this.min.x = this.min.y = Infinity;
  1908. this.max.x = this.max.y = -Infinity;
  1909. return this;
  1910. },
  1911. empty: function () {
  1912. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1913. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1914. },
  1915. center: function ( optionalTarget ) {
  1916. var result = optionalTarget || new THREE.Vector2();
  1917. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1918. },
  1919. size: function ( optionalTarget ) {
  1920. var result = optionalTarget || new THREE.Vector2();
  1921. return result.subVectors( this.max, this.min );
  1922. },
  1923. expandByPoint: function ( point ) {
  1924. this.min.min( point );
  1925. this.max.max( point );
  1926. return this;
  1927. },
  1928. expandByVector: function ( vector ) {
  1929. this.min.sub( vector );
  1930. this.max.add( vector );
  1931. return this;
  1932. },
  1933. expandByScalar: function ( scalar ) {
  1934. this.min.addScalar( -scalar );
  1935. this.max.addScalar( scalar );
  1936. return this;
  1937. },
  1938. containsPoint: function ( point ) {
  1939. if ( point.x < this.min.x || point.x > this.max.x ||
  1940. point.y < this.min.y || point.y > this.max.y ) {
  1941. return false;
  1942. }
  1943. return true;
  1944. },
  1945. containsBox: function ( box ) {
  1946. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1947. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1948. return true;
  1949. }
  1950. return false;
  1951. },
  1952. getParameter: function ( point ) {
  1953. // This can potentially have a divide by zero if the box
  1954. // has a size dimension of 0.
  1955. return new THREE.Vector2(
  1956. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1957. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1958. );
  1959. },
  1960. isIntersectionBox: function ( box ) {
  1961. // using 6 splitting planes to rule out intersections.
  1962. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1963. box.max.y < this.min.y || box.min.y > this.max.y ) {
  1964. return false;
  1965. }
  1966. return true;
  1967. },
  1968. clampPoint: function ( point, optionalTarget ) {
  1969. var result = optionalTarget || new THREE.Vector2();
  1970. return result.copy( point ).clamp( this.min, this.max );
  1971. },
  1972. distanceToPoint: function () {
  1973. var v1 = new THREE.Vector2();
  1974. return function ( point ) {
  1975. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1976. return clampedPoint.sub( point ).length();
  1977. };
  1978. }(),
  1979. intersect: function ( box ) {
  1980. this.min.max( box.min );
  1981. this.max.min( box.max );
  1982. return this;
  1983. },
  1984. union: function ( box ) {
  1985. this.min.min( box.min );
  1986. this.max.max( box.max );
  1987. return this;
  1988. },
  1989. translate: function ( offset ) {
  1990. this.min.add( offset );
  1991. this.max.add( offset );
  1992. return this;
  1993. },
  1994. equals: function ( box ) {
  1995. return box.min.equals( this.min ) && box.max.equals( this.max );
  1996. },
  1997. clone: function () {
  1998. return new THREE.Box2().copy( this );
  1999. }
  2000. };
  2001. /**
  2002. * @author bhouston / http://exocortex.com
  2003. * @author WestLangley / http://github.com/WestLangley
  2004. */
  2005. THREE.Box3 = function ( min, max ) {
  2006. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2007. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  2008. };
  2009. THREE.Box3.prototype = {
  2010. constructor: THREE.Box3,
  2011. set: function ( min, max ) {
  2012. this.min.copy( min );
  2013. this.max.copy( max );
  2014. return this;
  2015. },
  2016. addPoint: function ( point ) {
  2017. if ( point.x < this.min.x ) {
  2018. this.min.x = point.x;
  2019. } else if ( point.x > this.max.x ) {
  2020. this.max.x = point.x;
  2021. }
  2022. if ( point.y < this.min.y ) {
  2023. this.min.y = point.y;
  2024. } else if ( point.y > this.max.y ) {
  2025. this.max.y = point.y;
  2026. }
  2027. if ( point.z < this.min.z ) {
  2028. this.min.z = point.z;
  2029. } else if ( point.z > this.max.z ) {
  2030. this.max.z = point.z;
  2031. }
  2032. },
  2033. setFromPoints: function ( points ) {
  2034. if ( points.length > 0 ) {
  2035. var point = points[ 0 ];
  2036. this.min.copy( point );
  2037. this.max.copy( point );
  2038. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2039. this.addPoint( points[ i ] )
  2040. }
  2041. } else {
  2042. this.makeEmpty();
  2043. }
  2044. return this;
  2045. },
  2046. setFromCenterAndSize: function() {
  2047. var v1 = new THREE.Vector3();
  2048. return function ( center, size ) {
  2049. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2050. this.min.copy( center ).sub( halfSize );
  2051. this.max.copy( center ).add( halfSize );
  2052. return this;
  2053. };
  2054. }(),
  2055. setFromObject: function() {
  2056. // Computes the world-axis-aligned bounding box of an object (including its children),
  2057. // accounting for both the object's, and childrens', world transforms
  2058. var v1 = new THREE.Vector3();
  2059. return function( object ) {
  2060. var scope = this;
  2061. object.updateMatrixWorld( true );
  2062. this.makeEmpty();
  2063. object.traverse( function ( node ) {
  2064. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2065. var vertices = node.geometry.vertices;
  2066. for ( var i = 0, il = vertices.length; i < il; i++ ) {
  2067. v1.copy( vertices[ i ] );
  2068. v1.applyMatrix4( node.matrixWorld );
  2069. scope.expandByPoint( v1 );
  2070. }
  2071. }
  2072. } );
  2073. return this;
  2074. };
  2075. }(),
  2076. copy: function ( box ) {
  2077. this.min.copy( box.min );
  2078. this.max.copy( box.max );
  2079. return this;
  2080. },
  2081. makeEmpty: function () {
  2082. this.min.x = this.min.y = this.min.z = Infinity;
  2083. this.max.x = this.max.y = this.max.z = -Infinity;
  2084. return this;
  2085. },
  2086. empty: function () {
  2087. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2088. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2089. },
  2090. center: function ( optionalTarget ) {
  2091. var result = optionalTarget || new THREE.Vector3();
  2092. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2093. },
  2094. size: function ( optionalTarget ) {
  2095. var result = optionalTarget || new THREE.Vector3();
  2096. return result.subVectors( this.max, this.min );
  2097. },
  2098. expandByPoint: function ( point ) {
  2099. this.min.min( point );
  2100. this.max.max( point );
  2101. return this;
  2102. },
  2103. expandByVector: function ( vector ) {
  2104. this.min.sub( vector );
  2105. this.max.add( vector );
  2106. return this;
  2107. },
  2108. expandByScalar: function ( scalar ) {
  2109. this.min.addScalar( -scalar );
  2110. this.max.addScalar( scalar );
  2111. return this;
  2112. },
  2113. containsPoint: function ( point ) {
  2114. if ( point.x < this.min.x || point.x > this.max.x ||
  2115. point.y < this.min.y || point.y > this.max.y ||
  2116. point.z < this.min.z || point.z > this.max.z ) {
  2117. return false;
  2118. }
  2119. return true;
  2120. },
  2121. containsBox: function ( box ) {
  2122. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2123. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2124. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2125. return true;
  2126. }
  2127. return false;
  2128. },
  2129. getParameter: function ( point ) {
  2130. // This can potentially have a divide by zero if the box
  2131. // has a size dimension of 0.
  2132. return new THREE.Vector3(
  2133. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2134. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2135. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2136. );
  2137. },
  2138. isIntersectionBox: function ( box ) {
  2139. // using 6 splitting planes to rule out intersections.
  2140. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2141. box.max.y < this.min.y || box.min.y > this.max.y ||
  2142. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2143. return false;
  2144. }
  2145. return true;
  2146. },
  2147. clampPoint: function ( point, optionalTarget ) {
  2148. var result = optionalTarget || new THREE.Vector3();
  2149. return result.copy( point ).clamp( this.min, this.max );
  2150. },
  2151. distanceToPoint: function() {
  2152. var v1 = new THREE.Vector3();
  2153. return function ( point ) {
  2154. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2155. return clampedPoint.sub( point ).length();
  2156. };
  2157. }(),
  2158. getBoundingSphere: function() {
  2159. var v1 = new THREE.Vector3();
  2160. return function ( optionalTarget ) {
  2161. var result = optionalTarget || new THREE.Sphere();
  2162. result.center = this.center();
  2163. result.radius = this.size( v1 ).length() * 0.5;
  2164. return result;
  2165. };
  2166. }(),
  2167. intersect: function ( box ) {
  2168. this.min.max( box.min );
  2169. this.max.min( box.max );
  2170. return this;
  2171. },
  2172. union: function ( box ) {
  2173. this.min.min( box.min );
  2174. this.max.max( box.max );
  2175. return this;
  2176. },
  2177. applyMatrix4: function() {
  2178. var points = [
  2179. new THREE.Vector3(),
  2180. new THREE.Vector3(),
  2181. new THREE.Vector3(),
  2182. new THREE.Vector3(),
  2183. new THREE.Vector3(),
  2184. new THREE.Vector3(),
  2185. new THREE.Vector3(),
  2186. new THREE.Vector3()
  2187. ];
  2188. return function ( matrix ) {
  2189. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2190. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2191. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2192. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2193. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2194. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2195. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2196. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2197. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2198. this.makeEmpty();
  2199. this.setFromPoints( points );
  2200. return this;
  2201. };
  2202. }(),
  2203. translate: function ( offset ) {
  2204. this.min.add( offset );
  2205. this.max.add( offset );
  2206. return this;
  2207. },
  2208. equals: function ( box ) {
  2209. return box.min.equals( this.min ) && box.max.equals( this.max );
  2210. },
  2211. clone: function () {
  2212. return new THREE.Box3().copy( this );
  2213. }
  2214. };
  2215. /**
  2216. * @author alteredq / http://alteredqualia.com/
  2217. * @author WestLangley / http://github.com/WestLangley
  2218. * @author bhouston / http://exocortex.com
  2219. */
  2220. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2221. this.elements = new Float32Array(9);
  2222. this.set(
  2223. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2224. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2225. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2226. );
  2227. };
  2228. THREE.Matrix3.prototype = {
  2229. constructor: THREE.Matrix3,
  2230. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2231. var te = this.elements;
  2232. te[0] = n11; te[3] = n12; te[6] = n13;
  2233. te[1] = n21; te[4] = n22; te[7] = n23;
  2234. te[2] = n31; te[5] = n32; te[8] = n33;
  2235. return this;
  2236. },
  2237. identity: function () {
  2238. this.set(
  2239. 1, 0, 0,
  2240. 0, 1, 0,
  2241. 0, 0, 1
  2242. );
  2243. return this;
  2244. },
  2245. copy: function ( m ) {
  2246. var me = m.elements;
  2247. this.set(
  2248. me[0], me[3], me[6],
  2249. me[1], me[4], me[7],
  2250. me[2], me[5], me[8]
  2251. );
  2252. return this;
  2253. },
  2254. multiplyVector3: function ( vector ) {
  2255. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2256. return vector.applyMatrix3( this );
  2257. },
  2258. multiplyVector3Array: function() {
  2259. var v1 = new THREE.Vector3();
  2260. return function ( a ) {
  2261. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2262. v1.x = a[ i ];
  2263. v1.y = a[ i + 1 ];
  2264. v1.z = a[ i + 2 ];
  2265. v1.applyMatrix3(this);
  2266. a[ i ] = v1.x;
  2267. a[ i + 1 ] = v1.y;
  2268. a[ i + 2 ] = v1.z;
  2269. }
  2270. return a;
  2271. };
  2272. }(),
  2273. multiplyScalar: function ( s ) {
  2274. var te = this.elements;
  2275. te[0] *= s; te[3] *= s; te[6] *= s;
  2276. te[1] *= s; te[4] *= s; te[7] *= s;
  2277. te[2] *= s; te[5] *= s; te[8] *= s;
  2278. return this;
  2279. },
  2280. determinant: function () {
  2281. var te = this.elements;
  2282. var a = te[0], b = te[1], c = te[2],
  2283. d = te[3], e = te[4], f = te[5],
  2284. g = te[6], h = te[7], i = te[8];
  2285. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2286. },
  2287. getInverse: function ( matrix, throwOnInvertible ) {
  2288. // input: THREE.Matrix4
  2289. // ( based on http://code.google.com/p/webgl-mjs/ )
  2290. var me = matrix.elements;
  2291. var te = this.elements;
  2292. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2293. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2294. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2295. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2296. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2297. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2298. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2299. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2300. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2301. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2302. // no inverse
  2303. if ( det === 0 ) {
  2304. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2305. if ( throwOnInvertible || false ) {
  2306. throw new Error( msg );
  2307. } else {
  2308. console.warn( msg );
  2309. }
  2310. this.identity();
  2311. return this;
  2312. }
  2313. this.multiplyScalar( 1.0 / det );
  2314. return this;
  2315. },
  2316. transpose: function () {
  2317. var tmp, m = this.elements;
  2318. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2319. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2320. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2321. return this;
  2322. },
  2323. getNormalMatrix: function ( m ) {
  2324. // input: THREE.Matrix4
  2325. this.getInverse( m ).transpose();
  2326. return this;
  2327. },
  2328. transposeIntoArray: function ( r ) {
  2329. var m = this.elements;
  2330. r[ 0 ] = m[ 0 ];
  2331. r[ 1 ] = m[ 3 ];
  2332. r[ 2 ] = m[ 6 ];
  2333. r[ 3 ] = m[ 1 ];
  2334. r[ 4 ] = m[ 4 ];
  2335. r[ 5 ] = m[ 7 ];
  2336. r[ 6 ] = m[ 2 ];
  2337. r[ 7 ] = m[ 5 ];
  2338. r[ 8 ] = m[ 8 ];
  2339. return this;
  2340. },
  2341. clone: function () {
  2342. var te = this.elements;
  2343. return new THREE.Matrix3(
  2344. te[0], te[3], te[6],
  2345. te[1], te[4], te[7],
  2346. te[2], te[5], te[8]
  2347. );
  2348. }
  2349. };
  2350. /**
  2351. * @author mrdoob / http://mrdoob.com/
  2352. * @author supereggbert / http://www.paulbrunt.co.uk/
  2353. * @author philogb / http://blog.thejit.org/
  2354. * @author jordi_ros / http://plattsoft.com
  2355. * @author D1plo1d / http://github.com/D1plo1d
  2356. * @author alteredq / http://alteredqualia.com/
  2357. * @author mikael emtinger / http://gomo.se/
  2358. * @author timknip / http://www.floorplanner.com/
  2359. * @author bhouston / http://exocortex.com
  2360. * @author WestLangley / http://github.com/WestLangley
  2361. */
  2362. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2363. this.elements = new Float32Array( 16 );
  2364. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2365. // we should not support semi specification of Matrix4, it is just weird.
  2366. var te = this.elements;
  2367. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2368. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2369. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2370. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2371. };
  2372. THREE.Matrix4.prototype = {
  2373. constructor: THREE.Matrix4,
  2374. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2375. var te = this.elements;
  2376. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2377. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2378. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2379. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2380. return this;
  2381. },
  2382. identity: function () {
  2383. this.set(
  2384. 1, 0, 0, 0,
  2385. 0, 1, 0, 0,
  2386. 0, 0, 1, 0,
  2387. 0, 0, 0, 1
  2388. );
  2389. return this;
  2390. },
  2391. copy: function ( m ) {
  2392. this.elements.set( m.elements );
  2393. return this;
  2394. },
  2395. extractPosition: function ( m ) {
  2396. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2397. return this.copyPosition( m );
  2398. },
  2399. copyPosition: function ( m ) {
  2400. var te = this.elements;
  2401. var me = m.elements;
  2402. te[12] = me[12];
  2403. te[13] = me[13];
  2404. te[14] = me[14];
  2405. return this;
  2406. },
  2407. extractRotation: function () {
  2408. var v1 = new THREE.Vector3();
  2409. return function ( m ) {
  2410. var te = this.elements;
  2411. var me = m.elements;
  2412. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2413. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2414. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2415. te[0] = me[0] * scaleX;
  2416. te[1] = me[1] * scaleX;
  2417. te[2] = me[2] * scaleX;
  2418. te[4] = me[4] * scaleY;
  2419. te[5] = me[5] * scaleY;
  2420. te[6] = me[6] * scaleY;
  2421. te[8] = me[8] * scaleZ;
  2422. te[9] = me[9] * scaleZ;
  2423. te[10] = me[10] * scaleZ;
  2424. return this;
  2425. };
  2426. }(),
  2427. makeRotationFromEuler: function ( euler ) {
  2428. if ( euler instanceof THREE.Euler === false ) {
  2429. console.error( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  2430. }
  2431. var te = this.elements;
  2432. var x = euler.x, y = euler.y, z = euler.z;
  2433. var a = Math.cos( x ), b = Math.sin( x );
  2434. var c = Math.cos( y ), d = Math.sin( y );
  2435. var e = Math.cos( z ), f = Math.sin( z );
  2436. if ( euler.order === 'XYZ' ) {
  2437. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2438. te[0] = c * e;
  2439. te[4] = - c * f;
  2440. te[8] = d;
  2441. te[1] = af + be * d;
  2442. te[5] = ae - bf * d;
  2443. te[9] = - b * c;
  2444. te[2] = bf - ae * d;
  2445. te[6] = be + af * d;
  2446. te[10] = a * c;
  2447. } else if ( euler.order === 'YXZ' ) {
  2448. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2449. te[0] = ce + df * b;
  2450. te[4] = de * b - cf;
  2451. te[8] = a * d;
  2452. te[1] = a * f;
  2453. te[5] = a * e;
  2454. te[9] = - b;
  2455. te[2] = cf * b - de;
  2456. te[6] = df + ce * b;
  2457. te[10] = a * c;
  2458. } else if ( euler.order === 'ZXY' ) {
  2459. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2460. te[0] = ce - df * b;
  2461. te[4] = - a * f;
  2462. te[8] = de + cf * b;
  2463. te[1] = cf + de * b;
  2464. te[5] = a * e;
  2465. te[9] = df - ce * b;
  2466. te[2] = - a * d;
  2467. te[6] = b;
  2468. te[10] = a * c;
  2469. } else if ( euler.order === 'ZYX' ) {
  2470. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2471. te[0] = c * e;
  2472. te[4] = be * d - af;
  2473. te[8] = ae * d + bf;
  2474. te[1] = c * f;
  2475. te[5] = bf * d + ae;
  2476. te[9] = af * d - be;
  2477. te[2] = - d;
  2478. te[6] = b * c;
  2479. te[10] = a * c;
  2480. } else if ( euler.order === 'YZX' ) {
  2481. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2482. te[0] = c * e;
  2483. te[4] = bd - ac * f;
  2484. te[8] = bc * f + ad;
  2485. te[1] = f;
  2486. te[5] = a * e;
  2487. te[9] = - b * e;
  2488. te[2] = - d * e;
  2489. te[6] = ad * f + bc;
  2490. te[10] = ac - bd * f;
  2491. } else if ( euler.order === 'XZY' ) {
  2492. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2493. te[0] = c * e;
  2494. te[4] = - f;
  2495. te[8] = d * e;
  2496. te[1] = ac * f + bd;
  2497. te[5] = a * e;
  2498. te[9] = ad * f - bc;
  2499. te[2] = bc * f - ad;
  2500. te[6] = b * e;
  2501. te[10] = bd * f + ac;
  2502. }
  2503. // last column
  2504. te[3] = 0;
  2505. te[7] = 0;
  2506. te[11] = 0;
  2507. // bottom row
  2508. te[12] = 0;
  2509. te[13] = 0;
  2510. te[14] = 0;
  2511. te[15] = 1;
  2512. return this;
  2513. },
  2514. setRotationFromQuaternion: function ( q ) {
  2515. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2516. return this.makeRotationFromQuaternion( q );
  2517. },
  2518. makeRotationFromQuaternion: function ( q ) {
  2519. var te = this.elements;
  2520. var x = q.x, y = q.y, z = q.z, w = q.w;
  2521. var x2 = x + x, y2 = y + y, z2 = z + z;
  2522. var xx = x * x2, xy = x * y2, xz = x * z2;
  2523. var yy = y * y2, yz = y * z2, zz = z * z2;
  2524. var wx = w * x2, wy = w * y2, wz = w * z2;
  2525. te[0] = 1 - ( yy + zz );
  2526. te[4] = xy - wz;
  2527. te[8] = xz + wy;
  2528. te[1] = xy + wz;
  2529. te[5] = 1 - ( xx + zz );
  2530. te[9] = yz - wx;
  2531. te[2] = xz - wy;
  2532. te[6] = yz + wx;
  2533. te[10] = 1 - ( xx + yy );
  2534. // last column
  2535. te[3] = 0;
  2536. te[7] = 0;
  2537. te[11] = 0;
  2538. // bottom row
  2539. te[12] = 0;
  2540. te[13] = 0;
  2541. te[14] = 0;
  2542. te[15] = 1;
  2543. return this;
  2544. },
  2545. lookAt: function() {
  2546. var x = new THREE.Vector3();
  2547. var y = new THREE.Vector3();
  2548. var z = new THREE.Vector3();
  2549. return function ( eye, target, up ) {
  2550. var te = this.elements;
  2551. z.subVectors( eye, target ).normalize();
  2552. if ( z.length() === 0 ) {
  2553. z.z = 1;
  2554. }
  2555. x.crossVectors( up, z ).normalize();
  2556. if ( x.length() === 0 ) {
  2557. z.x += 0.0001;
  2558. x.crossVectors( up, z ).normalize();
  2559. }
  2560. y.crossVectors( z, x );
  2561. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2562. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2563. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2564. return this;
  2565. };
  2566. }(),
  2567. multiply: function ( m, n ) {
  2568. if ( n !== undefined ) {
  2569. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2570. return this.multiplyMatrices( m, n );
  2571. }
  2572. return this.multiplyMatrices( this, m );
  2573. },
  2574. multiplyMatrices: function ( a, b ) {
  2575. var ae = a.elements;
  2576. var be = b.elements;
  2577. var te = this.elements;
  2578. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2579. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2580. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2581. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2582. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2583. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2584. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2585. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2586. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2587. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2588. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2589. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2590. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2591. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2592. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2593. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2594. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2595. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2596. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2597. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2598. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2599. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2600. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2601. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2602. return this;
  2603. },
  2604. multiplyToArray: function ( a, b, r ) {
  2605. var te = this.elements;
  2606. this.multiplyMatrices( a, b );
  2607. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2608. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2609. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2610. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2611. return this;
  2612. },
  2613. multiplyScalar: function ( s ) {
  2614. var te = this.elements;
  2615. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2616. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2617. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2618. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2619. return this;
  2620. },
  2621. multiplyVector3: function ( vector ) {
  2622. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2623. return vector.applyProjection( this );
  2624. },
  2625. multiplyVector4: function ( vector ) {
  2626. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2627. return vector.applyMatrix4( this );
  2628. },
  2629. multiplyVector3Array: function() {
  2630. var v1 = new THREE.Vector3();
  2631. return function ( a ) {
  2632. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2633. v1.x = a[ i ];
  2634. v1.y = a[ i + 1 ];
  2635. v1.z = a[ i + 2 ];
  2636. v1.applyProjection( this );
  2637. a[ i ] = v1.x;
  2638. a[ i + 1 ] = v1.y;
  2639. a[ i + 2 ] = v1.z;
  2640. }
  2641. return a;
  2642. };
  2643. }(),
  2644. rotateAxis: function ( v ) {
  2645. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2646. v.transformDirection( this );
  2647. },
  2648. crossVector: function ( vector ) {
  2649. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2650. return vector.applyMatrix4( this );
  2651. },
  2652. determinant: function () {
  2653. var te = this.elements;
  2654. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2655. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2656. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2657. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2658. //TODO: make this more efficient
  2659. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2660. return (
  2661. n41 * (
  2662. +n14 * n23 * n32
  2663. -n13 * n24 * n32
  2664. -n14 * n22 * n33
  2665. +n12 * n24 * n33
  2666. +n13 * n22 * n34
  2667. -n12 * n23 * n34
  2668. ) +
  2669. n42 * (
  2670. +n11 * n23 * n34
  2671. -n11 * n24 * n33
  2672. +n14 * n21 * n33
  2673. -n13 * n21 * n34
  2674. +n13 * n24 * n31
  2675. -n14 * n23 * n31
  2676. ) +
  2677. n43 * (
  2678. +n11 * n24 * n32
  2679. -n11 * n22 * n34
  2680. -n14 * n21 * n32
  2681. +n12 * n21 * n34
  2682. +n14 * n22 * n31
  2683. -n12 * n24 * n31
  2684. ) +
  2685. n44 * (
  2686. -n13 * n22 * n31
  2687. -n11 * n23 * n32
  2688. +n11 * n22 * n33
  2689. +n13 * n21 * n32
  2690. -n12 * n21 * n33
  2691. +n12 * n23 * n31
  2692. )
  2693. );
  2694. },
  2695. transpose: function () {
  2696. var te = this.elements;
  2697. var tmp;
  2698. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2699. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2700. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2701. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2702. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2703. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2704. return this;
  2705. },
  2706. flattenToArray: function ( flat ) {
  2707. var te = this.elements;
  2708. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2709. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2710. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2711. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2712. return flat;
  2713. },
  2714. flattenToArrayOffset: function( flat, offset ) {
  2715. var te = this.elements;
  2716. flat[ offset ] = te[0];
  2717. flat[ offset + 1 ] = te[1];
  2718. flat[ offset + 2 ] = te[2];
  2719. flat[ offset + 3 ] = te[3];
  2720. flat[ offset + 4 ] = te[4];
  2721. flat[ offset + 5 ] = te[5];
  2722. flat[ offset + 6 ] = te[6];
  2723. flat[ offset + 7 ] = te[7];
  2724. flat[ offset + 8 ] = te[8];
  2725. flat[ offset + 9 ] = te[9];
  2726. flat[ offset + 10 ] = te[10];
  2727. flat[ offset + 11 ] = te[11];
  2728. flat[ offset + 12 ] = te[12];
  2729. flat[ offset + 13 ] = te[13];
  2730. flat[ offset + 14 ] = te[14];
  2731. flat[ offset + 15 ] = te[15];
  2732. return flat;
  2733. },
  2734. getPosition: function() {
  2735. var v1 = new THREE.Vector3();
  2736. return function () {
  2737. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.getPositionFromMatrix( matrix ) instead.' );
  2738. var te = this.elements;
  2739. return v1.set( te[12], te[13], te[14] );
  2740. };
  2741. }(),
  2742. setPosition: function ( v ) {
  2743. var te = this.elements;
  2744. te[12] = v.x;
  2745. te[13] = v.y;
  2746. te[14] = v.z;
  2747. return this;
  2748. },
  2749. getInverse: function ( m, throwOnInvertible ) {
  2750. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2751. var te = this.elements;
  2752. var me = m.elements;
  2753. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2754. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2755. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2756. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2757. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2758. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2759. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2760. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2761. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2762. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2763. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2764. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2765. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2766. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2767. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2768. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2769. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2770. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2771. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2772. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2773. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2774. if ( det == 0 ) {
  2775. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2776. if ( throwOnInvertible || false ) {
  2777. throw new Error( msg );
  2778. } else {
  2779. console.warn( msg );
  2780. }
  2781. this.identity();
  2782. return this;
  2783. }
  2784. this.multiplyScalar( 1 / det );
  2785. return this;
  2786. },
  2787. translate: function ( v ) {
  2788. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2789. },
  2790. rotateX: function ( angle ) {
  2791. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2792. },
  2793. rotateY: function ( angle ) {
  2794. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2795. },
  2796. rotateZ: function ( angle ) {
  2797. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2798. },
  2799. rotateByAxis: function ( axis, angle ) {
  2800. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2801. },
  2802. scale: function ( v ) {
  2803. var te = this.elements;
  2804. var x = v.x, y = v.y, z = v.z;
  2805. te[0] *= x; te[4] *= y; te[8] *= z;
  2806. te[1] *= x; te[5] *= y; te[9] *= z;
  2807. te[2] *= x; te[6] *= y; te[10] *= z;
  2808. te[3] *= x; te[7] *= y; te[11] *= z;
  2809. return this;
  2810. },
  2811. getMaxScaleOnAxis: function () {
  2812. var te = this.elements;
  2813. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2814. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2815. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2816. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2817. },
  2818. makeTranslation: function ( x, y, z ) {
  2819. this.set(
  2820. 1, 0, 0, x,
  2821. 0, 1, 0, y,
  2822. 0, 0, 1, z,
  2823. 0, 0, 0, 1
  2824. );
  2825. return this;
  2826. },
  2827. makeRotationX: function ( theta ) {
  2828. var c = Math.cos( theta ), s = Math.sin( theta );
  2829. this.set(
  2830. 1, 0, 0, 0,
  2831. 0, c, -s, 0,
  2832. 0, s, c, 0,
  2833. 0, 0, 0, 1
  2834. );
  2835. return this;
  2836. },
  2837. makeRotationY: function ( theta ) {
  2838. var c = Math.cos( theta ), s = Math.sin( theta );
  2839. this.set(
  2840. c, 0, s, 0,
  2841. 0, 1, 0, 0,
  2842. -s, 0, c, 0,
  2843. 0, 0, 0, 1
  2844. );
  2845. return this;
  2846. },
  2847. makeRotationZ: function ( theta ) {
  2848. var c = Math.cos( theta ), s = Math.sin( theta );
  2849. this.set(
  2850. c, -s, 0, 0,
  2851. s, c, 0, 0,
  2852. 0, 0, 1, 0,
  2853. 0, 0, 0, 1
  2854. );
  2855. return this;
  2856. },
  2857. makeRotationAxis: function ( axis, angle ) {
  2858. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2859. var c = Math.cos( angle );
  2860. var s = Math.sin( angle );
  2861. var t = 1 - c;
  2862. var x = axis.x, y = axis.y, z = axis.z;
  2863. var tx = t * x, ty = t * y;
  2864. this.set(
  2865. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2866. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2867. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2868. 0, 0, 0, 1
  2869. );
  2870. return this;
  2871. },
  2872. makeScale: function ( x, y, z ) {
  2873. this.set(
  2874. x, 0, 0, 0,
  2875. 0, y, 0, 0,
  2876. 0, 0, z, 0,
  2877. 0, 0, 0, 1
  2878. );
  2879. return this;
  2880. },
  2881. compose: function ( position, quaternion, scale ) {
  2882. this.makeRotationFromQuaternion( quaternion );
  2883. this.scale( scale );
  2884. this.setPosition( position );
  2885. return this;
  2886. },
  2887. decompose: function () {
  2888. var vector = new THREE.Vector3();
  2889. var matrix = new THREE.Matrix4();
  2890. return function ( position, quaternion, scale ) {
  2891. var te = this.elements;
  2892. var sx = vector.set( te[0], te[1], te[2] ).length();
  2893. var sy = vector.set( te[4], te[5], te[6] ).length();
  2894. var sz = vector.set( te[8], te[9], te[10] ).length();
  2895. position.x = te[12];
  2896. position.y = te[13];
  2897. position.z = te[14];
  2898. // scale the rotation part
  2899. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  2900. var invSX = 1 / sx;
  2901. var invSY = 1 / sy;
  2902. var invSZ = 1 / sz;
  2903. matrix.elements[0] *= invSX;
  2904. matrix.elements[1] *= invSX;
  2905. matrix.elements[2] *= invSX;
  2906. matrix.elements[4] *= invSY;
  2907. matrix.elements[5] *= invSY;
  2908. matrix.elements[6] *= invSY;
  2909. matrix.elements[8] *= invSZ;
  2910. matrix.elements[9] *= invSZ;
  2911. matrix.elements[10] *= invSZ;
  2912. quaternion.setFromRotationMatrix( matrix );
  2913. scale.x = sx;
  2914. scale.y = sy;
  2915. scale.z = sz;
  2916. return this;
  2917. };
  2918. }(),
  2919. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2920. var te = this.elements;
  2921. var x = 2 * near / ( right - left );
  2922. var y = 2 * near / ( top - bottom );
  2923. var a = ( right + left ) / ( right - left );
  2924. var b = ( top + bottom ) / ( top - bottom );
  2925. var c = - ( far + near ) / ( far - near );
  2926. var d = - 2 * far * near / ( far - near );
  2927. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2928. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2929. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2930. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2931. return this;
  2932. },
  2933. makePerspective: function ( fov, aspect, near, far ) {
  2934. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2935. var ymin = - ymax;
  2936. var xmin = ymin * aspect;
  2937. var xmax = ymax * aspect;
  2938. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2939. },
  2940. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2941. var te = this.elements;
  2942. var w = right - left;
  2943. var h = top - bottom;
  2944. var p = far - near;
  2945. var x = ( right + left ) / w;
  2946. var y = ( top + bottom ) / h;
  2947. var z = ( far + near ) / p;
  2948. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2949. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2950. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2951. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2952. return this;
  2953. },
  2954. fromArray: function ( array ) {
  2955. this.elements.set( array );
  2956. return this;
  2957. },
  2958. toArray: function () {
  2959. var te = this.elements;
  2960. return [
  2961. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  2962. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  2963. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  2964. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  2965. ];
  2966. },
  2967. clone: function () {
  2968. var te = this.elements;
  2969. return new THREE.Matrix4(
  2970. te[0], te[4], te[8], te[12],
  2971. te[1], te[5], te[9], te[13],
  2972. te[2], te[6], te[10], te[14],
  2973. te[3], te[7], te[11], te[15]
  2974. );
  2975. }
  2976. };
  2977. /**
  2978. * @author bhouston / http://exocortex.com
  2979. */
  2980. THREE.Ray = function ( origin, direction ) {
  2981. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  2982. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  2983. };
  2984. THREE.Ray.prototype = {
  2985. constructor: THREE.Ray,
  2986. set: function ( origin, direction ) {
  2987. this.origin.copy( origin );
  2988. this.direction.copy( direction );
  2989. return this;
  2990. },
  2991. copy: function ( ray ) {
  2992. this.origin.copy( ray.origin );
  2993. this.direction.copy( ray.direction );
  2994. return this;
  2995. },
  2996. at: function ( t, optionalTarget ) {
  2997. var result = optionalTarget || new THREE.Vector3();
  2998. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2999. },
  3000. recast: function () {
  3001. var v1 = new THREE.Vector3();
  3002. return function ( t ) {
  3003. this.origin.copy( this.at( t, v1 ) );
  3004. return this;
  3005. };
  3006. }(),
  3007. closestPointToPoint: function ( point, optionalTarget ) {
  3008. var result = optionalTarget || new THREE.Vector3();
  3009. result.subVectors( point, this.origin );
  3010. var directionDistance = result.dot( this.direction );
  3011. if ( directionDistance < 0 ) {
  3012. return result.copy( this.origin );
  3013. }
  3014. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3015. },
  3016. distanceToPoint: function () {
  3017. var v1 = new THREE.Vector3();
  3018. return function ( point ) {
  3019. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3020. // point behind the ray
  3021. if ( directionDistance < 0 ) {
  3022. return this.origin.distanceTo( point );
  3023. }
  3024. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3025. return v1.distanceTo( point );
  3026. };
  3027. }(),
  3028. distanceSqToSegment: function( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3029. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3030. // It returns the min distance between the ray and the segment
  3031. // defined by v0 and v1
  3032. // It can also set two optional targets :
  3033. // - The closest point on the ray
  3034. // - The closest point on the segment
  3035. var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 );
  3036. var segDir = v1.clone().sub( v0 ).normalize();
  3037. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3038. var diff = this.origin.clone().sub( segCenter );
  3039. var a01 = - this.direction.dot( segDir );
  3040. var b0 = diff.dot( this.direction );
  3041. var b1 = - diff.dot( segDir );
  3042. var c = diff.lengthSq();
  3043. var det = Math.abs( 1 - a01 * a01 );
  3044. var s0, s1, sqrDist, extDet;
  3045. if ( det >= 0 ) {
  3046. // The ray and segment are not parallel.
  3047. s0 = a01 * b1 - b0;
  3048. s1 = a01 * b0 - b1;
  3049. extDet = segExtent * det;
  3050. if ( s0 >= 0 ) {
  3051. if ( s1 >= - extDet ) {
  3052. if ( s1 <= extDet ) {
  3053. // region 0
  3054. // Minimum at interior points of ray and segment.
  3055. var invDet = 1 / det;
  3056. s0 *= invDet;
  3057. s1 *= invDet;
  3058. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3059. } else {
  3060. // region 1
  3061. s1 = segExtent;
  3062. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3063. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3064. }
  3065. } else {
  3066. // region 5
  3067. s1 = - segExtent;
  3068. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3069. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3070. }
  3071. } else {
  3072. if ( s1 <= - extDet) {
  3073. // region 4
  3074. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3075. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3076. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3077. } else if ( s1 <= extDet ) {
  3078. // region 3
  3079. s0 = 0;
  3080. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3081. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3082. } else {
  3083. // region 2
  3084. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3085. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3086. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3087. }
  3088. }
  3089. } else {
  3090. // Ray and segment are parallel.
  3091. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3092. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3093. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3094. }
  3095. if ( optionalPointOnRay ) {
  3096. optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) );
  3097. }
  3098. if ( optionalPointOnSegment ) {
  3099. optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) );
  3100. }
  3101. return sqrDist;
  3102. },
  3103. isIntersectionSphere: function ( sphere ) {
  3104. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3105. },
  3106. isIntersectionPlane: function ( plane ) {
  3107. // check if the ray lies on the plane first
  3108. var distToPoint = plane.distanceToPoint( this.origin );
  3109. if ( distToPoint === 0 ) {
  3110. return true;
  3111. }
  3112. var denominator = plane.normal.dot( this.direction );
  3113. if ( denominator * distToPoint < 0 ) {
  3114. return true
  3115. }
  3116. // ray origin is behind the plane (and is pointing behind it)
  3117. return false;
  3118. },
  3119. distanceToPlane: function ( plane ) {
  3120. var denominator = plane.normal.dot( this.direction );
  3121. if ( denominator == 0 ) {
  3122. // line is coplanar, return origin
  3123. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3124. return 0;
  3125. }
  3126. // Null is preferable to undefined since undefined means.... it is undefined
  3127. return null;
  3128. }
  3129. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3130. // Return if the ray never intersects the plane
  3131. return t >= 0 ? t : null;
  3132. },
  3133. intersectPlane: function ( plane, optionalTarget ) {
  3134. var t = this.distanceToPlane( plane );
  3135. if ( t === null ) {
  3136. return null;
  3137. }
  3138. return this.at( t, optionalTarget );
  3139. },
  3140. isIntersectionBox: function () {
  3141. var v = new THREE.Vector3();
  3142. return function ( box ) {
  3143. return this.intersectBox( box, v ) !== null;
  3144. }
  3145. }(),
  3146. intersectBox: function ( box , optionalTarget ) {
  3147. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3148. var tmin,tmax,tymin,tymax,tzmin,tzmax;
  3149. var invdirx = 1/this.direction.x,
  3150. invdiry = 1/this.direction.y,
  3151. invdirz = 1/this.direction.z;
  3152. var origin = this.origin;
  3153. if (invdirx >= 0) {
  3154. tmin = (box.min.x - origin.x) * invdirx;
  3155. tmax = (box.max.x - origin.x) * invdirx;
  3156. } else {
  3157. tmin = (box.max.x - origin.x) * invdirx;
  3158. tmax = (box.min.x - origin.x) * invdirx;
  3159. }
  3160. if (invdiry >= 0) {
  3161. tymin = (box.min.y - origin.y) * invdiry;
  3162. tymax = (box.max.y - origin.y) * invdiry;
  3163. } else {
  3164. tymin = (box.max.y - origin.y) * invdiry;
  3165. tymax = (box.min.y - origin.y) * invdiry;
  3166. }
  3167. if ((tmin > tymax) || (tymin > tmax)) return null;
  3168. // These lines also handle the case where tmin or tmax is NaN
  3169. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3170. if (tymin > tmin || tmin !== tmin ) tmin = tymin;
  3171. if (tymax < tmax || tmax !== tmax ) tmax = tymax;
  3172. if (invdirz >= 0) {
  3173. tzmin = (box.min.z - origin.z) * invdirz;
  3174. tzmax = (box.max.z - origin.z) * invdirz;
  3175. } else {
  3176. tzmin = (box.max.z - origin.z) * invdirz;
  3177. tzmax = (box.min.z - origin.z) * invdirz;
  3178. }
  3179. if ((tmin > tzmax) || (tzmin > tmax)) return null;
  3180. if (tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3181. if (tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3182. //return point closest to the ray (positive side)
  3183. if ( tmax < 0 ) return null;
  3184. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3185. },
  3186. intersectTriangle: function() {
  3187. // Compute the offset origin, edges, and normal.
  3188. var diff = new THREE.Vector3();
  3189. var edge1 = new THREE.Vector3();
  3190. var edge2 = new THREE.Vector3();
  3191. var normal = new THREE.Vector3();
  3192. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3193. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3194. edge1.subVectors( b, a );
  3195. edge2.subVectors( c, a );
  3196. normal.crossVectors( edge1, edge2 );
  3197. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3198. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3199. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3200. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3201. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3202. var DdN = this.direction.dot( normal );
  3203. var sign;
  3204. if ( DdN > 0 ) {
  3205. if ( backfaceCulling ) return null;
  3206. sign = 1;
  3207. } else if ( DdN < 0 ) {
  3208. sign = - 1;
  3209. DdN = - DdN;
  3210. } else {
  3211. return null;
  3212. }
  3213. diff.subVectors( this.origin, a );
  3214. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3215. // b1 < 0, no intersection
  3216. if ( DdQxE2 < 0 ) {
  3217. return null;
  3218. }
  3219. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3220. // b2 < 0, no intersection
  3221. if ( DdE1xQ < 0 ) {
  3222. return null;
  3223. }
  3224. // b1+b2 > 1, no intersection
  3225. if ( DdQxE2 + DdE1xQ > DdN ) {
  3226. return null;
  3227. }
  3228. // Line intersects triangle, check if ray does.
  3229. var QdN = - sign * diff.dot( normal );
  3230. // t < 0, no intersection
  3231. if ( QdN < 0 ) {
  3232. return null;
  3233. }
  3234. // Ray intersects triangle.
  3235. return this.at( QdN / DdN, optionalTarget );
  3236. }
  3237. }(),
  3238. applyMatrix4: function ( matrix4 ) {
  3239. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3240. this.origin.applyMatrix4( matrix4 );
  3241. this.direction.sub( this.origin );
  3242. this.direction.normalize();
  3243. return this;
  3244. },
  3245. equals: function ( ray ) {
  3246. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3247. },
  3248. clone: function () {
  3249. return new THREE.Ray().copy( this );
  3250. }
  3251. };
  3252. /**
  3253. * @author bhouston / http://exocortex.com
  3254. * @author mrdoob / http://mrdoob.com/
  3255. */
  3256. THREE.Sphere = function ( center, radius ) {
  3257. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3258. this.radius = ( radius !== undefined ) ? radius : 0;
  3259. };
  3260. THREE.Sphere.prototype = {
  3261. constructor: THREE.Sphere,
  3262. set: function ( center, radius ) {
  3263. this.center.copy( center );
  3264. this.radius = radius;
  3265. return this;
  3266. },
  3267. setFromPoints: function () {
  3268. var box = new THREE.Box3();
  3269. return function ( points, optionalCenter ) {
  3270. var center = this.center;
  3271. if ( optionalCenter !== undefined ) {
  3272. center.copy( optionalCenter );
  3273. } else {
  3274. box.setFromPoints( points ).center( center );
  3275. }
  3276. var maxRadiusSq = 0;
  3277. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3278. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3279. }
  3280. this.radius = Math.sqrt( maxRadiusSq );
  3281. return this;
  3282. };
  3283. }(),
  3284. copy: function ( sphere ) {
  3285. this.center.copy( sphere.center );
  3286. this.radius = sphere.radius;
  3287. return this;
  3288. },
  3289. empty: function () {
  3290. return ( this.radius <= 0 );
  3291. },
  3292. containsPoint: function ( point ) {
  3293. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3294. },
  3295. distanceToPoint: function ( point ) {
  3296. return ( point.distanceTo( this.center ) - this.radius );
  3297. },
  3298. intersectsSphere: function ( sphere ) {
  3299. var radiusSum = this.radius + sphere.radius;
  3300. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3301. },
  3302. clampPoint: function ( point, optionalTarget ) {
  3303. var deltaLengthSq = this.center.distanceToSquared( point );
  3304. var result = optionalTarget || new THREE.Vector3();
  3305. result.copy( point );
  3306. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3307. result.sub( this.center ).normalize();
  3308. result.multiplyScalar( this.radius ).add( this.center );
  3309. }
  3310. return result;
  3311. },
  3312. getBoundingBox: function ( optionalTarget ) {
  3313. var box = optionalTarget || new THREE.Box3();
  3314. box.set( this.center, this.center );
  3315. box.expandByScalar( this.radius );
  3316. return box;
  3317. },
  3318. applyMatrix4: function ( matrix ) {
  3319. this.center.applyMatrix4( matrix );
  3320. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3321. return this;
  3322. },
  3323. translate: function ( offset ) {
  3324. this.center.add( offset );
  3325. return this;
  3326. },
  3327. equals: function ( sphere ) {
  3328. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3329. },
  3330. clone: function () {
  3331. return new THREE.Sphere().copy( this );
  3332. }
  3333. };
  3334. /**
  3335. * @author mrdoob / http://mrdoob.com/
  3336. * @author alteredq / http://alteredqualia.com/
  3337. * @author bhouston / http://exocortex.com
  3338. */
  3339. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3340. this.planes = [
  3341. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3342. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3343. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3344. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3345. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3346. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3347. ];
  3348. };
  3349. THREE.Frustum.prototype = {
  3350. constructor: THREE.Frustum,
  3351. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3352. var planes = this.planes;
  3353. planes[0].copy( p0 );
  3354. planes[1].copy( p1 );
  3355. planes[2].copy( p2 );
  3356. planes[3].copy( p3 );
  3357. planes[4].copy( p4 );
  3358. planes[5].copy( p5 );
  3359. return this;
  3360. },
  3361. copy: function ( frustum ) {
  3362. var planes = this.planes;
  3363. for( var i = 0; i < 6; i ++ ) {
  3364. planes[i].copy( frustum.planes[i] );
  3365. }
  3366. return this;
  3367. },
  3368. setFromMatrix: function ( m ) {
  3369. var planes = this.planes;
  3370. var me = m.elements;
  3371. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3372. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3373. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3374. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3375. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3376. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3377. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3378. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3379. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3380. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3381. return this;
  3382. },
  3383. intersectsObject: function () {
  3384. var sphere = new THREE.Sphere();
  3385. return function ( object ) {
  3386. var geometry = object.geometry;
  3387. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3388. sphere.copy( geometry.boundingSphere );
  3389. sphere.applyMatrix4( object.matrixWorld );
  3390. return this.intersectsSphere( sphere );
  3391. };
  3392. }(),
  3393. intersectsSphere: function ( sphere ) {
  3394. var planes = this.planes;
  3395. var center = sphere.center;
  3396. var negRadius = -sphere.radius;
  3397. for ( var i = 0; i < 6; i ++ ) {
  3398. var distance = planes[ i ].distanceToPoint( center );
  3399. if ( distance < negRadius ) {
  3400. return false;
  3401. }
  3402. }
  3403. return true;
  3404. },
  3405. intersectsBox : function() {
  3406. var p1 = new THREE.Vector3(),
  3407. p2 = new THREE.Vector3();
  3408. return function( box ) {
  3409. var planes = this.planes;
  3410. for ( var i = 0; i < 6 ; i ++ ) {
  3411. var plane = planes[i];
  3412. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3413. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3414. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3415. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3416. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3417. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3418. var d1 = plane.distanceToPoint( p1 );
  3419. var d2 = plane.distanceToPoint( p2 );
  3420. // if both outside plane, no intersection
  3421. if ( d1 < 0 && d2 < 0 ) {
  3422. return false;
  3423. }
  3424. }
  3425. return true;
  3426. };
  3427. }(),
  3428. containsPoint: function ( point ) {
  3429. var planes = this.planes;
  3430. for ( var i = 0; i < 6; i ++ ) {
  3431. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3432. return false;
  3433. }
  3434. }
  3435. return true;
  3436. },
  3437. clone: function () {
  3438. return new THREE.Frustum().copy( this );
  3439. }
  3440. };
  3441. /**
  3442. * @author bhouston / http://exocortex.com
  3443. */
  3444. THREE.Plane = function ( normal, constant ) {
  3445. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3446. this.constant = ( constant !== undefined ) ? constant : 0;
  3447. };
  3448. THREE.Plane.prototype = {
  3449. constructor: THREE.Plane,
  3450. set: function ( normal, constant ) {
  3451. this.normal.copy( normal );
  3452. this.constant = constant;
  3453. return this;
  3454. },
  3455. setComponents: function ( x, y, z, w ) {
  3456. this.normal.set( x, y, z );
  3457. this.constant = w;
  3458. return this;
  3459. },
  3460. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3461. this.normal.copy( normal );
  3462. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3463. return this;
  3464. },
  3465. setFromCoplanarPoints: function() {
  3466. var v1 = new THREE.Vector3();
  3467. var v2 = new THREE.Vector3();
  3468. return function ( a, b, c ) {
  3469. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3470. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3471. this.setFromNormalAndCoplanarPoint( normal, a );
  3472. return this;
  3473. };
  3474. }(),
  3475. copy: function ( plane ) {
  3476. this.normal.copy( plane.normal );
  3477. this.constant = plane.constant;
  3478. return this;
  3479. },
  3480. normalize: function () {
  3481. // Note: will lead to a divide by zero if the plane is invalid.
  3482. var inverseNormalLength = 1.0 / this.normal.length();
  3483. this.normal.multiplyScalar( inverseNormalLength );
  3484. this.constant *= inverseNormalLength;
  3485. return this;
  3486. },
  3487. negate: function () {
  3488. this.constant *= -1;
  3489. this.normal.negate();
  3490. return this;
  3491. },
  3492. distanceToPoint: function ( point ) {
  3493. return this.normal.dot( point ) + this.constant;
  3494. },
  3495. distanceToSphere: function ( sphere ) {
  3496. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3497. },
  3498. projectPoint: function ( point, optionalTarget ) {
  3499. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3500. },
  3501. orthoPoint: function ( point, optionalTarget ) {
  3502. var perpendicularMagnitude = this.distanceToPoint( point );
  3503. var result = optionalTarget || new THREE.Vector3();
  3504. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3505. },
  3506. isIntersectionLine: function ( line ) {
  3507. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3508. var startSign = this.distanceToPoint( line.start );
  3509. var endSign = this.distanceToPoint( line.end );
  3510. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3511. },
  3512. intersectLine: function() {
  3513. var v1 = new THREE.Vector3();
  3514. return function ( line, optionalTarget ) {
  3515. var result = optionalTarget || new THREE.Vector3();
  3516. var direction = line.delta( v1 );
  3517. var denominator = this.normal.dot( direction );
  3518. if ( denominator == 0 ) {
  3519. // line is coplanar, return origin
  3520. if( this.distanceToPoint( line.start ) == 0 ) {
  3521. return result.copy( line.start );
  3522. }
  3523. // Unsure if this is the correct method to handle this case.
  3524. return undefined;
  3525. }
  3526. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3527. if( t < 0 || t > 1 ) {
  3528. return undefined;
  3529. }
  3530. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3531. };
  3532. }(),
  3533. coplanarPoint: function ( optionalTarget ) {
  3534. var result = optionalTarget || new THREE.Vector3();
  3535. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3536. },
  3537. applyMatrix4: function() {
  3538. var v1 = new THREE.Vector3();
  3539. var v2 = new THREE.Vector3();
  3540. return function ( matrix, optionalNormalMatrix ) {
  3541. // compute new normal based on theory here:
  3542. // http://www.songho.ca/opengl/gl_normaltransform.html
  3543. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getNormalMatrix( matrix );
  3544. var newNormal = v1.copy( this.normal ).applyMatrix3( optionalNormalMatrix );
  3545. var newCoplanarPoint = this.coplanarPoint( v2 );
  3546. newCoplanarPoint.applyMatrix4( matrix );
  3547. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3548. return this;
  3549. };
  3550. }(),
  3551. translate: function ( offset ) {
  3552. this.constant = this.constant - offset.dot( this.normal );
  3553. return this;
  3554. },
  3555. equals: function ( plane ) {
  3556. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3557. },
  3558. clone: function () {
  3559. return new THREE.Plane().copy( this );
  3560. }
  3561. };
  3562. /**
  3563. * @author alteredq / http://alteredqualia.com/
  3564. * @author mrdoob / http://mrdoob.com/
  3565. */
  3566. THREE.Math = {
  3567. PI2: Math.PI * 2,
  3568. generateUUID: function () {
  3569. // http://www.broofa.com/Tools/Math.uuid.htm
  3570. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3571. var uuid = new Array(36);
  3572. var rnd = 0, r;
  3573. return function () {
  3574. for ( var i = 0; i < 36; i ++ ) {
  3575. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3576. uuid[ i ] = '-';
  3577. } else if ( i == 14 ) {
  3578. uuid[ i ] = '4';
  3579. } else {
  3580. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3581. r = rnd & 0xf;
  3582. rnd = rnd >> 4;
  3583. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3584. }
  3585. }
  3586. return uuid.join('');
  3587. };
  3588. }(),
  3589. // Clamp value to range <a, b>
  3590. clamp: function ( x, a, b ) {
  3591. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3592. },
  3593. // Clamp value to range <a, inf)
  3594. clampBottom: function ( x, a ) {
  3595. return x < a ? a : x;
  3596. },
  3597. // Linear mapping from range <a1, a2> to range <b1, b2>
  3598. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3599. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3600. },
  3601. // http://en.wikipedia.org/wiki/Smoothstep
  3602. smoothstep: function ( x, min, max ) {
  3603. if ( x <= min ) return 0;
  3604. if ( x >= max ) return 1;
  3605. x = ( x - min )/( max - min );
  3606. return x*x*(3 - 2*x);
  3607. },
  3608. smootherstep: function ( x, min, max ) {
  3609. if ( x <= min ) return 0;
  3610. if ( x >= max ) return 1;
  3611. x = ( x - min )/( max - min );
  3612. return x*x*x*(x*(x*6 - 15) + 10);
  3613. },
  3614. // Random float from <0, 1> with 16 bits of randomness
  3615. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3616. random16: function () {
  3617. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3618. },
  3619. // Random integer from <low, high> interval
  3620. randInt: function ( low, high ) {
  3621. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3622. },
  3623. // Random float from <low, high> interval
  3624. randFloat: function ( low, high ) {
  3625. return low + Math.random() * ( high - low );
  3626. },
  3627. // Random float from <-range/2, range/2> interval
  3628. randFloatSpread: function ( range ) {
  3629. return range * ( 0.5 - Math.random() );
  3630. },
  3631. sign: function ( x ) {
  3632. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  3633. },
  3634. degToRad: function() {
  3635. var degreeToRadiansFactor = Math.PI / 180;
  3636. return function ( degrees ) {
  3637. return degrees * degreeToRadiansFactor;
  3638. };
  3639. }(),
  3640. radToDeg: function() {
  3641. var radianToDegreesFactor = 180 / Math.PI;
  3642. return function ( radians ) {
  3643. return radians * radianToDegreesFactor;
  3644. };
  3645. }()
  3646. };
  3647. /**
  3648. * Spline from Tween.js, slightly optimized (and trashed)
  3649. * http://sole.github.com/tween.js/examples/05_spline.html
  3650. *
  3651. * @author mrdoob / http://mrdoob.com/
  3652. * @author alteredq / http://alteredqualia.com/
  3653. */
  3654. THREE.Spline = function ( points ) {
  3655. this.points = points;
  3656. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3657. point, intPoint, weight, w2, w3,
  3658. pa, pb, pc, pd;
  3659. this.initFromArray = function( a ) {
  3660. this.points = [];
  3661. for ( var i = 0; i < a.length; i++ ) {
  3662. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3663. }
  3664. };
  3665. this.getPoint = function ( k ) {
  3666. point = ( this.points.length - 1 ) * k;
  3667. intPoint = Math.floor( point );
  3668. weight = point - intPoint;
  3669. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3670. c[ 1 ] = intPoint;
  3671. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3672. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3673. pa = this.points[ c[ 0 ] ];
  3674. pb = this.points[ c[ 1 ] ];
  3675. pc = this.points[ c[ 2 ] ];
  3676. pd = this.points[ c[ 3 ] ];
  3677. w2 = weight * weight;
  3678. w3 = weight * w2;
  3679. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3680. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3681. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3682. return v3;
  3683. };
  3684. this.getControlPointsArray = function () {
  3685. var i, p, l = this.points.length,
  3686. coords = [];
  3687. for ( i = 0; i < l; i ++ ) {
  3688. p = this.points[ i ];
  3689. coords[ i ] = [ p.x, p.y, p.z ];
  3690. }
  3691. return coords;
  3692. };
  3693. // approximate length by summing linear segments
  3694. this.getLength = function ( nSubDivisions ) {
  3695. var i, index, nSamples, position,
  3696. point = 0, intPoint = 0, oldIntPoint = 0,
  3697. oldPosition = new THREE.Vector3(),
  3698. tmpVec = new THREE.Vector3(),
  3699. chunkLengths = [],
  3700. totalLength = 0;
  3701. // first point has 0 length
  3702. chunkLengths[ 0 ] = 0;
  3703. if ( !nSubDivisions ) nSubDivisions = 100;
  3704. nSamples = this.points.length * nSubDivisions;
  3705. oldPosition.copy( this.points[ 0 ] );
  3706. for ( i = 1; i < nSamples; i ++ ) {
  3707. index = i / nSamples;
  3708. position = this.getPoint( index );
  3709. tmpVec.copy( position );
  3710. totalLength += tmpVec.distanceTo( oldPosition );
  3711. oldPosition.copy( position );
  3712. point = ( this.points.length - 1 ) * index;
  3713. intPoint = Math.floor( point );
  3714. if ( intPoint != oldIntPoint ) {
  3715. chunkLengths[ intPoint ] = totalLength;
  3716. oldIntPoint = intPoint;
  3717. }
  3718. }
  3719. // last point ends with total length
  3720. chunkLengths[ chunkLengths.length ] = totalLength;
  3721. return { chunks: chunkLengths, total: totalLength };
  3722. };
  3723. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3724. var i, j,
  3725. index, indexCurrent, indexNext,
  3726. linearDistance, realDistance,
  3727. sampling, position,
  3728. newpoints = [],
  3729. tmpVec = new THREE.Vector3(),
  3730. sl = this.getLength();
  3731. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3732. for ( i = 1; i < this.points.length; i++ ) {
  3733. //tmpVec.copy( this.points[ i - 1 ] );
  3734. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3735. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3736. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3737. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3738. indexNext = i / ( this.points.length - 1 );
  3739. for ( j = 1; j < sampling - 1; j++ ) {
  3740. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3741. position = this.getPoint( index );
  3742. newpoints.push( tmpVec.copy( position ).clone() );
  3743. }
  3744. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3745. }
  3746. this.points = newpoints;
  3747. };
  3748. // Catmull-Rom
  3749. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3750. var v0 = ( p2 - p0 ) * 0.5,
  3751. v1 = ( p3 - p1 ) * 0.5;
  3752. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3753. };
  3754. };
  3755. /**
  3756. * @author bhouston / http://exocortex.com
  3757. * @author mrdoob / http://mrdoob.com/
  3758. */
  3759. THREE.Triangle = function ( a, b, c ) {
  3760. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3761. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3762. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3763. };
  3764. THREE.Triangle.normal = function() {
  3765. var v0 = new THREE.Vector3();
  3766. return function ( a, b, c, optionalTarget ) {
  3767. var result = optionalTarget || new THREE.Vector3();
  3768. result.subVectors( c, b );
  3769. v0.subVectors( a, b );
  3770. result.cross( v0 );
  3771. var resultLengthSq = result.lengthSq();
  3772. if( resultLengthSq > 0 ) {
  3773. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3774. }
  3775. return result.set( 0, 0, 0 );
  3776. };
  3777. }();
  3778. // static/instance method to calculate barycoordinates
  3779. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3780. THREE.Triangle.barycoordFromPoint = function() {
  3781. var v0 = new THREE.Vector3();
  3782. var v1 = new THREE.Vector3();
  3783. var v2 = new THREE.Vector3();
  3784. return function ( point, a, b, c, optionalTarget ) {
  3785. v0.subVectors( c, a );
  3786. v1.subVectors( b, a );
  3787. v2.subVectors( point, a );
  3788. var dot00 = v0.dot( v0 );
  3789. var dot01 = v0.dot( v1 );
  3790. var dot02 = v0.dot( v2 );
  3791. var dot11 = v1.dot( v1 );
  3792. var dot12 = v1.dot( v2 );
  3793. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3794. var result = optionalTarget || new THREE.Vector3();
  3795. // colinear or singular triangle
  3796. if( denom == 0 ) {
  3797. // arbitrary location outside of triangle?
  3798. // not sure if this is the best idea, maybe should be returning undefined
  3799. return result.set( -2, -1, -1 );
  3800. }
  3801. var invDenom = 1 / denom;
  3802. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3803. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3804. // barycoordinates must always sum to 1
  3805. return result.set( 1 - u - v, v, u );
  3806. };
  3807. }();
  3808. THREE.Triangle.containsPoint = function() {
  3809. var v1 = new THREE.Vector3();
  3810. return function ( point, a, b, c ) {
  3811. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3812. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3813. };
  3814. }();
  3815. THREE.Triangle.prototype = {
  3816. constructor: THREE.Triangle,
  3817. set: function ( a, b, c ) {
  3818. this.a.copy( a );
  3819. this.b.copy( b );
  3820. this.c.copy( c );
  3821. return this;
  3822. },
  3823. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3824. this.a.copy( points[i0] );
  3825. this.b.copy( points[i1] );
  3826. this.c.copy( points[i2] );
  3827. return this;
  3828. },
  3829. copy: function ( triangle ) {
  3830. this.a.copy( triangle.a );
  3831. this.b.copy( triangle.b );
  3832. this.c.copy( triangle.c );
  3833. return this;
  3834. },
  3835. area: function() {
  3836. var v0 = new THREE.Vector3();
  3837. var v1 = new THREE.Vector3();
  3838. return function () {
  3839. v0.subVectors( this.c, this.b );
  3840. v1.subVectors( this.a, this.b );
  3841. return v0.cross( v1 ).length() * 0.5;
  3842. };
  3843. }(),
  3844. midpoint: function ( optionalTarget ) {
  3845. var result = optionalTarget || new THREE.Vector3();
  3846. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3847. },
  3848. normal: function ( optionalTarget ) {
  3849. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3850. },
  3851. plane: function ( optionalTarget ) {
  3852. var result = optionalTarget || new THREE.Plane();
  3853. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3854. },
  3855. barycoordFromPoint: function ( point, optionalTarget ) {
  3856. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3857. },
  3858. containsPoint: function ( point ) {
  3859. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3860. },
  3861. equals: function ( triangle ) {
  3862. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3863. },
  3864. clone: function () {
  3865. return new THREE.Triangle().copy( this );
  3866. }
  3867. };
  3868. /**
  3869. * @author mrdoob / http://mrdoob.com/
  3870. */
  3871. THREE.Vertex = function ( v ) {
  3872. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3873. return v;
  3874. };
  3875. /**
  3876. * @author mrdoob / http://mrdoob.com/
  3877. */
  3878. THREE.UV = function ( u, v ) {
  3879. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3880. return new THREE.Vector2( u, v );
  3881. };
  3882. /**
  3883. * @author alteredq / http://alteredqualia.com/
  3884. */
  3885. THREE.Clock = function ( autoStart ) {
  3886. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3887. this.startTime = 0;
  3888. this.oldTime = 0;
  3889. this.elapsedTime = 0;
  3890. this.running = false;
  3891. };
  3892. THREE.Clock.prototype = {
  3893. constructor: THREE.Clock,
  3894. start: function () {
  3895. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  3896. ? self.performance.now()
  3897. : Date.now();
  3898. this.oldTime = this.startTime;
  3899. this.running = true;
  3900. },
  3901. stop: function () {
  3902. this.getElapsedTime();
  3903. this.running = false;
  3904. },
  3905. getElapsedTime: function () {
  3906. this.getDelta();
  3907. return this.elapsedTime;
  3908. },
  3909. getDelta: function () {
  3910. var diff = 0;
  3911. if ( this.autoStart && ! this.running ) {
  3912. this.start();
  3913. }
  3914. if ( this.running ) {
  3915. var newTime = self.performance !== undefined && self.performance.now !== undefined
  3916. ? self.performance.now()
  3917. : Date.now();
  3918. diff = 0.001 * ( newTime - this.oldTime );
  3919. this.oldTime = newTime;
  3920. this.elapsedTime += diff;
  3921. }
  3922. return diff;
  3923. }
  3924. };
  3925. /**
  3926. * https://github.com/mrdoob/eventdispatcher.js/
  3927. */
  3928. THREE.EventDispatcher = function () {}
  3929. THREE.EventDispatcher.prototype = {
  3930. constructor: THREE.EventDispatcher,
  3931. apply: function ( object ) {
  3932. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  3933. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  3934. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  3935. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  3936. },
  3937. addEventListener: function ( type, listener ) {
  3938. if ( this._listeners === undefined ) this._listeners = {};
  3939. var listeners = this._listeners;
  3940. if ( listeners[ type ] === undefined ) {
  3941. listeners[ type ] = [];
  3942. }
  3943. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3944. listeners[ type ].push( listener );
  3945. }
  3946. },
  3947. hasEventListener: function ( type, listener ) {
  3948. if ( this._listeners === undefined ) return false;
  3949. var listeners = this._listeners;
  3950. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  3951. return true;
  3952. }
  3953. return false;
  3954. },
  3955. removeEventListener: function ( type, listener ) {
  3956. if ( this._listeners === undefined ) return;
  3957. var listeners = this._listeners;
  3958. var index = listeners[ type ].indexOf( listener );
  3959. if ( index !== - 1 ) {
  3960. listeners[ type ].splice( index, 1 );
  3961. }
  3962. },
  3963. dispatchEvent: function () {
  3964. var array = [];
  3965. return function ( event ) {
  3966. if ( this._listeners === undefined ) return;
  3967. var listeners = this._listeners;
  3968. var listenerArray = listeners[ event.type ];
  3969. if ( listenerArray !== undefined ) {
  3970. event.target = this;
  3971. var length = listenerArray.length;
  3972. for ( var i = 0; i < length; i ++ ) {
  3973. array[ i ] = listenerArray[ i ];
  3974. }
  3975. for ( var i = 0; i < length; i ++ ) {
  3976. array[ i ].call( this, event );
  3977. }
  3978. }
  3979. };
  3980. }()
  3981. };
  3982. /**
  3983. * @author mrdoob / http://mrdoob.com/
  3984. * @author bhouston / http://exocortex.com/
  3985. * @author stephomi / http://stephaneginier.com/
  3986. */
  3987. ( function ( THREE ) {
  3988. THREE.Raycaster = function ( origin, direction, near, far ) {
  3989. this.ray = new THREE.Ray( origin, direction );
  3990. // direction is assumed to be normalized (for accurate distance calculations)
  3991. this.near = near || 0;
  3992. this.far = far || Infinity;
  3993. };
  3994. var sphere = new THREE.Sphere();
  3995. var localRay = new THREE.Ray();
  3996. var facePlane = new THREE.Plane();
  3997. var intersectPoint = new THREE.Vector3();
  3998. var matrixPosition = new THREE.Vector3();
  3999. var inverseMatrix = new THREE.Matrix4();
  4000. var descSort = function ( a, b ) {
  4001. return a.distance - b.distance;
  4002. };
  4003. var vA = new THREE.Vector3();
  4004. var vB = new THREE.Vector3();
  4005. var vC = new THREE.Vector3();
  4006. var intersectObject = function ( object, raycaster, intersects ) {
  4007. if ( object instanceof THREE.Sprite ) {
  4008. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  4009. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  4010. if ( distance > object.scale.x ) {
  4011. return intersects;
  4012. }
  4013. intersects.push( {
  4014. distance: distance,
  4015. point: object.position,
  4016. face: null,
  4017. object: object
  4018. } );
  4019. } else if ( object instanceof THREE.LOD ) {
  4020. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  4021. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  4022. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  4023. } else if ( object instanceof THREE.Mesh ) {
  4024. var geometry = object.geometry;
  4025. // Checking boundingSphere distance to ray
  4026. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4027. sphere.copy( geometry.boundingSphere );
  4028. sphere.applyMatrix4( object.matrixWorld );
  4029. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4030. return intersects;
  4031. }
  4032. // Check boundingBox before continuing
  4033. inverseMatrix.getInverse( object.matrixWorld );
  4034. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4035. if ( geometry.boundingBox !== null ) {
  4036. if ( localRay.isIntersectionBox( geometry.boundingBox ) === false ) {
  4037. return intersects;
  4038. }
  4039. }
  4040. if ( geometry instanceof THREE.BufferGeometry ) {
  4041. var material = object.material;
  4042. if ( material === undefined ) return intersects;
  4043. if ( geometry.dynamic === false ) return intersects;
  4044. var a, b, c;
  4045. var precision = raycaster.precision;
  4046. if ( geometry.attributes.index !== undefined ) {
  4047. var offsets = geometry.offsets;
  4048. var indices = geometry.attributes.index.array;
  4049. var positions = geometry.attributes.position.array;
  4050. var offLength = geometry.offsets.length;
  4051. var fl = geometry.attributes.index.array.length / 3;
  4052. for ( var oi = 0; oi < offLength; ++oi ) {
  4053. var start = offsets[ oi ].start;
  4054. var count = offsets[ oi ].count;
  4055. var index = offsets[ oi ].index;
  4056. for ( var i = start, il = start + count; i < il; i += 3 ) {
  4057. a = index + indices[ i ];
  4058. b = index + indices[ i + 1 ];
  4059. c = index + indices[ i + 2 ];
  4060. vA.set(
  4061. positions[ a * 3 ],
  4062. positions[ a * 3 + 1 ],
  4063. positions[ a * 3 + 2 ]
  4064. );
  4065. vB.set(
  4066. positions[ b * 3 ],
  4067. positions[ b * 3 + 1 ],
  4068. positions[ b * 3 + 2 ]
  4069. );
  4070. vC.set(
  4071. positions[ c * 3 ],
  4072. positions[ c * 3 + 1 ],
  4073. positions[ c * 3 + 2 ]
  4074. );
  4075. if ( material.side === THREE.BackSide ) {
  4076. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4077. } else {
  4078. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4079. }
  4080. if ( intersectionPoint === null ) continue;
  4081. intersectionPoint.applyMatrix4( object.matrixWorld );
  4082. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4083. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4084. intersects.push( {
  4085. distance: distance,
  4086. point: intersectionPoint,
  4087. face: null,
  4088. faceIndex: null,
  4089. object: object
  4090. } );
  4091. }
  4092. }
  4093. } else {
  4094. var offsets = geometry.offsets;
  4095. var positions = geometry.attributes.position.array;
  4096. var offLength = geometry.offsets.length;
  4097. var fl = geometry.attributes.position.array.length;
  4098. for ( var i = 0; i < fl; i += 3 ) {
  4099. a = i;
  4100. b = i + 1;
  4101. c = i + 2;
  4102. vA.set(
  4103. positions[ a * 3 ],
  4104. positions[ a * 3 + 1 ],
  4105. positions[ a * 3 + 2 ]
  4106. );
  4107. vB.set(
  4108. positions[ b * 3 ],
  4109. positions[ b * 3 + 1 ],
  4110. positions[ b * 3 + 2 ]
  4111. );
  4112. vC.set(
  4113. positions[ c * 3 ],
  4114. positions[ c * 3 + 1 ],
  4115. positions[ c * 3 + 2 ]
  4116. );
  4117. if ( material.side === THREE.BackSide ) {
  4118. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4119. } else {
  4120. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4121. }
  4122. if ( intersectionPoint === null ) continue;
  4123. intersectionPoint.applyMatrix4( object.matrixWorld );
  4124. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4125. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4126. intersects.push( {
  4127. distance: distance,
  4128. point: intersectionPoint,
  4129. face: null,
  4130. faceIndex: null,
  4131. object: object
  4132. } );
  4133. }
  4134. }
  4135. } else if ( geometry instanceof THREE.Geometry ) {
  4136. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4137. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  4138. var a, b, c, d;
  4139. var precision = raycaster.precision;
  4140. var vertices = geometry.vertices;
  4141. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  4142. var face = geometry.faces[ f ];
  4143. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  4144. if ( material === undefined ) continue;
  4145. a = vertices[ face.a ];
  4146. b = vertices[ face.b ];
  4147. c = vertices[ face.c ];
  4148. if ( material.side === THREE.BackSide ) {
  4149. var intersectionPoint = localRay.intersectTriangle( c, b, a, true );
  4150. } else {
  4151. var intersectionPoint = localRay.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
  4152. }
  4153. if ( intersectionPoint === null ) continue;
  4154. intersectionPoint.applyMatrix4( object.matrixWorld );
  4155. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4156. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4157. intersects.push( {
  4158. distance: distance,
  4159. point: intersectionPoint,
  4160. face: face,
  4161. faceIndex: f,
  4162. object: object
  4163. } );
  4164. }
  4165. }
  4166. } else if ( object instanceof THREE.Line ) {
  4167. var precision = raycaster.linePrecision;
  4168. var precisionSq = precision * precision;
  4169. var geometry = object.geometry;
  4170. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4171. // Checking boundingSphere distance to ray
  4172. sphere.copy( geometry.boundingSphere );
  4173. sphere.applyMatrix4( object.matrixWorld );
  4174. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4175. return intersects;
  4176. }
  4177. inverseMatrix.getInverse( object.matrixWorld );
  4178. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4179. /* if ( geometry instanceof THREE.BufferGeometry ) {
  4180. } else */ if ( geometry instanceof THREE.Geometry ) {
  4181. var vertices = geometry.vertices;
  4182. var nbVertices = vertices.length;
  4183. var interSegment = new THREE.Vector3();
  4184. var interRay = new THREE.Vector3();
  4185. var step = object.type === THREE.LineStrip ? 1 : 2;
  4186. for ( var i = 0; i < nbVertices - 1; i = i + step ) {
  4187. var distSq = localRay.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  4188. if ( distSq > precisionSq ) continue;
  4189. var distance = localRay.origin.distanceTo( interRay );
  4190. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  4191. intersects.push( {
  4192. distance: distance,
  4193. // What do we want? intersection point on the ray or on the segment??
  4194. // point: raycaster.ray.at( distance ),
  4195. point: interSegment.clone().applyMatrix4( object.matrixWorld ),
  4196. face: null,
  4197. faceIndex: null,
  4198. object: object
  4199. } );
  4200. }
  4201. }
  4202. }
  4203. };
  4204. var intersectDescendants = function ( object, raycaster, intersects ) {
  4205. var descendants = object.getDescendants();
  4206. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  4207. intersectObject( descendants[ i ], raycaster, intersects );
  4208. }
  4209. };
  4210. //
  4211. THREE.Raycaster.prototype.precision = 0.0001;
  4212. THREE.Raycaster.prototype.linePrecision = 1;
  4213. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  4214. this.ray.set( origin, direction );
  4215. // direction is assumed to be normalized (for accurate distance calculations)
  4216. };
  4217. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  4218. var intersects = [];
  4219. if ( recursive === true ) {
  4220. intersectDescendants( object, this, intersects );
  4221. }
  4222. intersectObject( object, this, intersects );
  4223. intersects.sort( descSort );
  4224. return intersects;
  4225. };
  4226. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  4227. var intersects = [];
  4228. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4229. intersectObject( objects[ i ], this, intersects );
  4230. if ( recursive === true ) {
  4231. intersectDescendants( objects[ i ], this, intersects );
  4232. }
  4233. }
  4234. intersects.sort( descSort );
  4235. return intersects;
  4236. };
  4237. }( THREE ) );
  4238. /**
  4239. * @author mrdoob / http://mrdoob.com/
  4240. * @author mikael emtinger / http://gomo.se/
  4241. * @author alteredq / http://alteredqualia.com/
  4242. * @author WestLangley / http://github.com/WestLangley
  4243. */
  4244. THREE.Object3D = function () {
  4245. this.id = THREE.Object3DIdCount ++;
  4246. this.uuid = THREE.Math.generateUUID();
  4247. this.name = '';
  4248. this.parent = undefined;
  4249. this.children = [];
  4250. this.up = new THREE.Vector3( 0, 1, 0 );
  4251. this.position = new THREE.Vector3();
  4252. this._rotation = new THREE.Euler();
  4253. this._quaternion = new THREE.Quaternion();
  4254. this.scale = new THREE.Vector3( 1, 1, 1 );
  4255. // keep rotation and quaternion in sync
  4256. this._rotation._quaternion = this.quaternion;
  4257. this._quaternion._euler = this.rotation;
  4258. this.renderDepth = null;
  4259. this.rotationAutoUpdate = true;
  4260. this.matrix = new THREE.Matrix4();
  4261. this.matrixWorld = new THREE.Matrix4();
  4262. this.matrixAutoUpdate = true;
  4263. this.matrixWorldNeedsUpdate = true;
  4264. this.visible = true;
  4265. this.castShadow = false;
  4266. this.receiveShadow = false;
  4267. this.frustumCulled = true;
  4268. this.userData = {};
  4269. };
  4270. THREE.Object3D.prototype = {
  4271. constructor: THREE.Object3D,
  4272. get rotation () {
  4273. return this._rotation;
  4274. },
  4275. set rotation ( value ) {
  4276. this._rotation = value;
  4277. this._rotation._quaternion = this._quaternion;
  4278. this._quaternion._euler = this._rotation;
  4279. this._rotation._updateQuaternion();
  4280. },
  4281. get quaternion () {
  4282. return this._quaternion;
  4283. },
  4284. set quaternion ( value ) {
  4285. this._quaternion = value;
  4286. this._quaternion._euler = this._rotation;
  4287. this._rotation._quaternion = this._quaternion;
  4288. this._quaternion._updateEuler();
  4289. },
  4290. get eulerOrder () {
  4291. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4292. return this.rotation.order;
  4293. },
  4294. set eulerOrder ( value ) {
  4295. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4296. this.rotation.order = value;
  4297. },
  4298. get useQuaternion () {
  4299. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4300. },
  4301. set useQuaternion ( value ) {
  4302. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4303. },
  4304. applyMatrix: function () {
  4305. var m1 = new THREE.Matrix4();
  4306. return function ( matrix ) {
  4307. this.matrix.multiplyMatrices( matrix, this.matrix );
  4308. this.position.getPositionFromMatrix( this.matrix );
  4309. this.scale.getScaleFromMatrix( this.matrix );
  4310. m1.extractRotation( this.matrix );
  4311. this.quaternion.setFromRotationMatrix( m1 );
  4312. }
  4313. }(),
  4314. setRotationFromAxisAngle: function ( axis, angle ) {
  4315. // assumes axis is normalized
  4316. this.quaternion.setFromAxisAngle( axis, angle );
  4317. },
  4318. setRotationFromEuler: function ( euler ) {
  4319. this.quaternion.setFromEuler( euler, true );
  4320. },
  4321. setRotationFromMatrix: function ( m ) {
  4322. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4323. this.quaternion.setFromRotationMatrix( m );
  4324. },
  4325. setRotationFromQuaternion: function ( q ) {
  4326. // assumes q is normalized
  4327. this.quaternion.copy( q );
  4328. },
  4329. rotateOnAxis: function() {
  4330. // rotate object on axis in object space
  4331. // axis is assumed to be normalized
  4332. var q1 = new THREE.Quaternion();
  4333. return function ( axis, angle ) {
  4334. q1.setFromAxisAngle( axis, angle );
  4335. this.quaternion.multiply( q1 );
  4336. return this;
  4337. }
  4338. }(),
  4339. rotateX: function () {
  4340. var v1 = new THREE.Vector3( 1, 0, 0 );
  4341. return function ( angle ) {
  4342. return this.rotateOnAxis( v1, angle );
  4343. };
  4344. }(),
  4345. rotateY: function () {
  4346. var v1 = new THREE.Vector3( 0, 1, 0 );
  4347. return function ( angle ) {
  4348. return this.rotateOnAxis( v1, angle );
  4349. };
  4350. }(),
  4351. rotateZ: function () {
  4352. var v1 = new THREE.Vector3( 0, 0, 1 );
  4353. return function ( angle ) {
  4354. return this.rotateOnAxis( v1, angle );
  4355. };
  4356. }(),
  4357. translateOnAxis: function () {
  4358. // translate object by distance along axis in object space
  4359. // axis is assumed to be normalized
  4360. var v1 = new THREE.Vector3();
  4361. return function ( axis, distance ) {
  4362. v1.copy( axis );
  4363. v1.applyQuaternion( this.quaternion );
  4364. this.position.add( v1.multiplyScalar( distance ) );
  4365. return this;
  4366. }
  4367. }(),
  4368. translate: function ( distance, axis ) {
  4369. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  4370. return this.translateOnAxis( axis, distance );
  4371. },
  4372. translateX: function () {
  4373. var v1 = new THREE.Vector3( 1, 0, 0 );
  4374. return function ( distance ) {
  4375. return this.translateOnAxis( v1, distance );
  4376. };
  4377. }(),
  4378. translateY: function () {
  4379. var v1 = new THREE.Vector3( 0, 1, 0 );
  4380. return function ( distance ) {
  4381. return this.translateOnAxis( v1, distance );
  4382. };
  4383. }(),
  4384. translateZ: function () {
  4385. var v1 = new THREE.Vector3( 0, 0, 1 );
  4386. return function ( distance ) {
  4387. return this.translateOnAxis( v1, distance );
  4388. };
  4389. }(),
  4390. localToWorld: function ( vector ) {
  4391. return vector.applyMatrix4( this.matrixWorld );
  4392. },
  4393. worldToLocal: function () {
  4394. var m1 = new THREE.Matrix4();
  4395. return function ( vector ) {
  4396. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4397. };
  4398. }(),
  4399. lookAt: function () {
  4400. // This routine does not support objects with rotated and/or translated parent(s)
  4401. var m1 = new THREE.Matrix4();
  4402. return function ( vector ) {
  4403. m1.lookAt( vector, this.position, this.up );
  4404. this.quaternion.setFromRotationMatrix( m1 );
  4405. };
  4406. }(),
  4407. add: function ( object ) {
  4408. if ( object === this ) {
  4409. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  4410. return;
  4411. }
  4412. if ( object instanceof THREE.Object3D ) {
  4413. if ( object.parent !== undefined ) {
  4414. object.parent.remove( object );
  4415. }
  4416. object.parent = this;
  4417. object.dispatchEvent( { type: 'added' } );
  4418. this.children.push( object );
  4419. // add to scene
  4420. var scene = this;
  4421. while ( scene.parent !== undefined ) {
  4422. scene = scene.parent;
  4423. }
  4424. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4425. scene.__addObject( object );
  4426. }
  4427. }
  4428. },
  4429. remove: function ( object ) {
  4430. var index = this.children.indexOf( object );
  4431. if ( index !== - 1 ) {
  4432. object.parent = undefined;
  4433. object.dispatchEvent( { type: 'removed' } );
  4434. this.children.splice( index, 1 );
  4435. // remove from 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.__removeObject( object );
  4442. }
  4443. }
  4444. },
  4445. traverse: function ( callback ) {
  4446. callback( this );
  4447. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4448. this.children[ i ].traverse( callback );
  4449. }
  4450. },
  4451. getObjectById: function ( id, recursive ) {
  4452. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4453. var child = this.children[ i ];
  4454. if ( child.id === id ) {
  4455. return child;
  4456. }
  4457. if ( recursive === true ) {
  4458. child = child.getObjectById( id, recursive );
  4459. if ( child !== undefined ) {
  4460. return child;
  4461. }
  4462. }
  4463. }
  4464. return undefined;
  4465. },
  4466. getObjectByName: function ( name, recursive ) {
  4467. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4468. var child = this.children[ i ];
  4469. if ( child.name === name ) {
  4470. return child;
  4471. }
  4472. if ( recursive === true ) {
  4473. child = child.getObjectByName( name, recursive );
  4474. if ( child !== undefined ) {
  4475. return child;
  4476. }
  4477. }
  4478. }
  4479. return undefined;
  4480. },
  4481. getChildByName: function ( name, recursive ) {
  4482. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  4483. return this.getObjectByName( name, recursive );
  4484. },
  4485. getDescendants: function ( array ) {
  4486. if ( array === undefined ) array = [];
  4487. Array.prototype.push.apply( array, this.children );
  4488. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4489. this.children[ i ].getDescendants( array );
  4490. }
  4491. return array;
  4492. },
  4493. updateMatrix: function () {
  4494. this.matrix.compose( this.position, this.quaternion, this.scale );
  4495. this.matrixWorldNeedsUpdate = true;
  4496. },
  4497. updateMatrixWorld: function ( force ) {
  4498. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4499. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4500. if ( this.parent === undefined ) {
  4501. this.matrixWorld.copy( this.matrix );
  4502. } else {
  4503. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4504. }
  4505. this.matrixWorldNeedsUpdate = false;
  4506. force = true;
  4507. }
  4508. // update children
  4509. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4510. this.children[ i ].updateMatrixWorld( force );
  4511. }
  4512. },
  4513. clone: function ( object, recursive ) {
  4514. if ( object === undefined ) object = new THREE.Object3D();
  4515. if ( recursive === undefined ) recursive = true;
  4516. object.name = this.name;
  4517. object.up.copy( this.up );
  4518. object.position.copy( this.position );
  4519. object.quaternion.copy( this.quaternion );
  4520. object.scale.copy( this.scale );
  4521. object.renderDepth = this.renderDepth;
  4522. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4523. object.matrix.copy( this.matrix );
  4524. object.matrixWorld.copy( this.matrixWorld );
  4525. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4526. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4527. object.visible = this.visible;
  4528. object.castShadow = this.castShadow;
  4529. object.receiveShadow = this.receiveShadow;
  4530. object.frustumCulled = this.frustumCulled;
  4531. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4532. if ( recursive === true ) {
  4533. for ( var i = 0; i < this.children.length; i ++ ) {
  4534. var child = this.children[ i ];
  4535. object.add( child.clone() );
  4536. }
  4537. }
  4538. return object;
  4539. }
  4540. };
  4541. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4542. THREE.Object3DIdCount = 0;
  4543. /**
  4544. * @author mrdoob / http://mrdoob.com/
  4545. * @author supereggbert / http://www.paulbrunt.co.uk/
  4546. * @author julianwa / https://github.com/julianwa
  4547. */
  4548. THREE.Projector = function () {
  4549. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4550. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4551. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  4552. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4553. _sprite, _spriteCount, _spritePool = [], _spritePoolLength = 0,
  4554. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  4555. _vector3 = new THREE.Vector3(),
  4556. _vector4 = new THREE.Vector4(),
  4557. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4558. _boundingBox = new THREE.Box3(),
  4559. _points3 = new Array( 3 ),
  4560. _points4 = new Array( 4 ),
  4561. _viewMatrix = new THREE.Matrix4(),
  4562. _viewProjectionMatrix = new THREE.Matrix4(),
  4563. _modelMatrix,
  4564. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4565. _normalMatrix = new THREE.Matrix3(),
  4566. _normalViewMatrix = new THREE.Matrix3(),
  4567. _centroid = new THREE.Vector3(),
  4568. _frustum = new THREE.Frustum(),
  4569. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4570. _clippedVertex2PositionScreen = new THREE.Vector4();
  4571. this.projectVector = function ( vector, camera ) {
  4572. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4573. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4574. return vector.applyProjection( _viewProjectionMatrix );
  4575. };
  4576. this.unprojectVector = function ( vector, camera ) {
  4577. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4578. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  4579. return vector.applyProjection( _viewProjectionMatrix );
  4580. };
  4581. this.pickingRay = function ( vector, camera ) {
  4582. // set two vectors with opposing z values
  4583. vector.z = -1.0;
  4584. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4585. this.unprojectVector( vector, camera );
  4586. this.unprojectVector( end, camera );
  4587. // find direction from vector to end
  4588. end.sub( vector ).normalize();
  4589. return new THREE.Raycaster( vector, end );
  4590. };
  4591. var getObject = function ( object ) {
  4592. _object = getNextObjectInPool();
  4593. _object.id = object.id;
  4594. _object.object = object;
  4595. if ( object.renderDepth !== null ) {
  4596. _object.z = object.renderDepth;
  4597. } else {
  4598. _vector3.getPositionFromMatrix( object.matrixWorld );
  4599. _vector3.applyProjection( _viewProjectionMatrix );
  4600. _object.z = _vector3.z;
  4601. }
  4602. return _object;
  4603. };
  4604. var projectObject = function ( object ) {
  4605. if ( object.visible === false ) return;
  4606. if ( object instanceof THREE.Light ) {
  4607. _renderData.lights.push( object );
  4608. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  4609. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4610. _renderData.objects.push( getObject( object ) );
  4611. }
  4612. } else if ( object instanceof THREE.Sprite ) {
  4613. _renderData.sprites.push( getObject( object ) );
  4614. }
  4615. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4616. projectObject( object.children[ i ] );
  4617. }
  4618. };
  4619. var projectGraph = function ( root, sortObjects ) {
  4620. _objectCount = 0;
  4621. _renderData.objects.length = 0;
  4622. _renderData.sprites.length = 0;
  4623. _renderData.lights.length = 0;
  4624. projectObject( root );
  4625. if ( sortObjects === true ) {
  4626. _renderData.objects.sort( painterSort );
  4627. }
  4628. };
  4629. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4630. var visible = false,
  4631. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  4632. geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  4633. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  4634. _face3Count = 0;
  4635. _lineCount = 0;
  4636. _spriteCount = 0;
  4637. _renderData.elements.length = 0;
  4638. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4639. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4640. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4641. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4642. _normalViewMatrix.getNormalMatrix( _viewMatrix );
  4643. _frustum.setFromMatrix( _viewProjectionMatrix );
  4644. projectGraph( scene, sortObjects );
  4645. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4646. object = _renderData.objects[ o ].object;
  4647. _modelMatrix = object.matrixWorld;
  4648. _vertexCount = 0;
  4649. if ( object instanceof THREE.Mesh ) {
  4650. geometry = object.geometry;
  4651. vertices = geometry.vertices;
  4652. faces = geometry.faces;
  4653. faceVertexUvs = geometry.faceVertexUvs;
  4654. _normalMatrix.getNormalMatrix( _modelMatrix );
  4655. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4656. objectMaterials = isFaceMaterial === true ? object.material : null;
  4657. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  4658. _vertex = getNextVertexInPool();
  4659. _vertex.positionWorld.copy( vertices[ v ] ).applyMatrix4( _modelMatrix );
  4660. _vertex.positionScreen.copy( _vertex.positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4661. var invW = 1 / _vertex.positionScreen.w;
  4662. _vertex.positionScreen.x *= invW;
  4663. _vertex.positionScreen.y *= invW;
  4664. _vertex.positionScreen.z *= invW;
  4665. _vertex.visible = ! ( _vertex.positionScreen.x < -1 || _vertex.positionScreen.x > 1 ||
  4666. _vertex.positionScreen.y < -1 || _vertex.positionScreen.y > 1 ||
  4667. _vertex.positionScreen.z < -1 || _vertex.positionScreen.z > 1 );
  4668. }
  4669. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  4670. face = faces[ f ];
  4671. var material = isFaceMaterial === true
  4672. ? objectMaterials.materials[ face.materialIndex ]
  4673. : object.material;
  4674. if ( material === undefined ) continue;
  4675. var side = material.side;
  4676. v1 = _vertexPool[ face.a ];
  4677. v2 = _vertexPool[ face.b ];
  4678. v3 = _vertexPool[ face.c ];
  4679. _points3[ 0 ] = v1.positionScreen;
  4680. _points3[ 1 ] = v2.positionScreen;
  4681. _points3[ 2 ] = v3.positionScreen;
  4682. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4683. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4684. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) *
  4685. ( v2.positionScreen.y - v1.positionScreen.y ) -
  4686. ( v3.positionScreen.y - v1.positionScreen.y ) *
  4687. ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4688. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4689. _face = getNextFace3InPool();
  4690. _face.id = object.id;
  4691. _face.v1.copy( v1 );
  4692. _face.v2.copy( v2 );
  4693. _face.v3.copy( v3 );
  4694. } else {
  4695. continue;
  4696. }
  4697. } else {
  4698. continue;
  4699. }
  4700. _face.normalModel.copy( face.normal );
  4701. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4702. _face.normalModel.negate();
  4703. }
  4704. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4705. _face.normalModelView.copy( _face.normalModel ).applyMatrix3( _normalViewMatrix );
  4706. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4707. faceVertexNormals = face.vertexNormals;
  4708. for ( n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) {
  4709. var normalModel = _face.vertexNormalsModel[ n ];
  4710. normalModel.copy( faceVertexNormals[ n ] );
  4711. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4712. normalModel.negate();
  4713. }
  4714. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4715. var normalModelView = _face.vertexNormalsModelView[ n ];
  4716. normalModelView.copy( normalModel ).applyMatrix3( _normalViewMatrix );
  4717. }
  4718. _face.vertexNormalsLength = faceVertexNormals.length;
  4719. for ( c = 0, cl = Math.min( faceVertexUvs.length, 3 ); c < cl; c ++ ) {
  4720. uvs = faceVertexUvs[ c ][ f ];
  4721. if ( uvs === undefined ) continue;
  4722. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  4723. _face.uvs[ c ][ u ] = uvs[ u ];
  4724. }
  4725. }
  4726. _face.color = face.color;
  4727. _face.material = material;
  4728. _centroid.copy( _face.centroidModel ).applyProjection( _viewProjectionMatrix );
  4729. _face.z = _centroid.z;
  4730. _renderData.elements.push( _face );
  4731. }
  4732. } else if ( object instanceof THREE.Line ) {
  4733. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4734. vertices = object.geometry.vertices;
  4735. v1 = getNextVertexInPool();
  4736. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4737. // Handle LineStrip and LinePieces
  4738. var step = object.type === THREE.LinePieces ? 2 : 1;
  4739. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  4740. v1 = getNextVertexInPool();
  4741. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4742. if ( ( v + 1 ) % step > 0 ) continue;
  4743. v2 = _vertexPool[ _vertexCount - 2 ];
  4744. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4745. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4746. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4747. // Perform the perspective divide
  4748. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4749. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4750. _line = getNextLineInPool();
  4751. _line.id = object.id;
  4752. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4753. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4754. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4755. _line.material = object.material;
  4756. if ( object.material.vertexColors === THREE.VertexColors ) {
  4757. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  4758. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  4759. }
  4760. _renderData.elements.push( _line );
  4761. }
  4762. }
  4763. }
  4764. }
  4765. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  4766. object = _renderData.sprites[ o ].object;
  4767. _modelMatrix = object.matrixWorld;
  4768. if ( object instanceof THREE.Sprite ) {
  4769. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4770. _vector4.applyMatrix4( _viewProjectionMatrix );
  4771. var invW = 1 / _vector4.w;
  4772. _vector4.z *= invW;
  4773. if ( _vector4.z > -1 && _vector4.z < 1 ) {
  4774. _sprite = getNextSpriteInPool();
  4775. _sprite.id = object.id;
  4776. _sprite.x = _vector4.x * invW;
  4777. _sprite.y = _vector4.y * invW;
  4778. _sprite.z = _vector4.z;
  4779. _sprite.object = object;
  4780. _sprite.rotation = object.rotation;
  4781. _sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4782. _sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4783. _sprite.material = object.material;
  4784. _renderData.elements.push( _sprite );
  4785. }
  4786. }
  4787. }
  4788. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4789. return _renderData;
  4790. };
  4791. // Pools
  4792. function getNextObjectInPool() {
  4793. if ( _objectCount === _objectPoolLength ) {
  4794. var object = new THREE.RenderableObject();
  4795. _objectPool.push( object );
  4796. _objectPoolLength ++;
  4797. _objectCount ++;
  4798. return object;
  4799. }
  4800. return _objectPool[ _objectCount ++ ];
  4801. }
  4802. function getNextVertexInPool() {
  4803. if ( _vertexCount === _vertexPoolLength ) {
  4804. var vertex = new THREE.RenderableVertex();
  4805. _vertexPool.push( vertex );
  4806. _vertexPoolLength ++;
  4807. _vertexCount ++;
  4808. return vertex;
  4809. }
  4810. return _vertexPool[ _vertexCount ++ ];
  4811. }
  4812. function getNextFace3InPool() {
  4813. if ( _face3Count === _face3PoolLength ) {
  4814. var face = new THREE.RenderableFace3();
  4815. _face3Pool.push( face );
  4816. _face3PoolLength ++;
  4817. _face3Count ++;
  4818. return face;
  4819. }
  4820. return _face3Pool[ _face3Count ++ ];
  4821. }
  4822. function getNextLineInPool() {
  4823. if ( _lineCount === _linePoolLength ) {
  4824. var line = new THREE.RenderableLine();
  4825. _linePool.push( line );
  4826. _linePoolLength ++;
  4827. _lineCount ++
  4828. return line;
  4829. }
  4830. return _linePool[ _lineCount ++ ];
  4831. }
  4832. function getNextSpriteInPool() {
  4833. if ( _spriteCount === _spritePoolLength ) {
  4834. var sprite = new THREE.RenderableSprite();
  4835. _spritePool.push( sprite );
  4836. _spritePoolLength ++;
  4837. _spriteCount ++
  4838. return sprite;
  4839. }
  4840. return _spritePool[ _spriteCount ++ ];
  4841. }
  4842. //
  4843. function painterSort( a, b ) {
  4844. if ( a.z !== b.z ) {
  4845. return b.z - a.z;
  4846. } else if ( a.id !== b.id ) {
  4847. return a.id - b.id;
  4848. } else {
  4849. return 0;
  4850. }
  4851. }
  4852. function clipLine( s1, s2 ) {
  4853. var alpha1 = 0, alpha2 = 1,
  4854. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4855. // Z = -1 and Z = +1, respectively.
  4856. bc1near = s1.z + s1.w,
  4857. bc2near = s2.z + s2.w,
  4858. bc1far = - s1.z + s1.w,
  4859. bc2far = - s2.z + s2.w;
  4860. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4861. // Both vertices lie entirely within all clip planes.
  4862. return true;
  4863. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4864. // Both vertices lie entirely outside one of the clip planes.
  4865. return false;
  4866. } else {
  4867. // The line segment spans at least one clip plane.
  4868. if ( bc1near < 0 ) {
  4869. // v1 lies outside the near plane, v2 inside
  4870. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4871. } else if ( bc2near < 0 ) {
  4872. // v2 lies outside the near plane, v1 inside
  4873. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4874. }
  4875. if ( bc1far < 0 ) {
  4876. // v1 lies outside the far plane, v2 inside
  4877. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4878. } else if ( bc2far < 0 ) {
  4879. // v2 lies outside the far plane, v2 inside
  4880. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4881. }
  4882. if ( alpha2 < alpha1 ) {
  4883. // The line segment spans two boundaries, but is outside both of them.
  4884. // (This can't happen when we're only clipping against just near/far but good
  4885. // to leave the check here for future usage if other clip planes are added.)
  4886. return false;
  4887. } else {
  4888. // Update the s1 and s2 vertices to match the clipped line segment.
  4889. s1.lerp( s2, alpha1 );
  4890. s2.lerp( s1, 1 - alpha2 );
  4891. return true;
  4892. }
  4893. }
  4894. }
  4895. };
  4896. /**
  4897. * @author mrdoob / http://mrdoob.com/
  4898. * @author alteredq / http://alteredqualia.com/
  4899. */
  4900. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4901. this.a = a;
  4902. this.b = b;
  4903. this.c = c;
  4904. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4905. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4906. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4907. this.vertexColors = color instanceof Array ? color : [];
  4908. this.vertexTangents = [];
  4909. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4910. this.centroid = new THREE.Vector3();
  4911. };
  4912. THREE.Face3.prototype = {
  4913. constructor: THREE.Face3,
  4914. clone: function () {
  4915. var face = new THREE.Face3( this.a, this.b, this.c );
  4916. face.normal.copy( this.normal );
  4917. face.color.copy( this.color );
  4918. face.centroid.copy( this.centroid );
  4919. face.materialIndex = this.materialIndex;
  4920. var i, il;
  4921. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4922. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4923. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4924. return face;
  4925. }
  4926. };
  4927. /**
  4928. * @author mrdoob / http://mrdoob.com/
  4929. */
  4930. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4931. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.')
  4932. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  4933. };
  4934. /**
  4935. * @author mrdoob / http://mrdoob.com/
  4936. * @author kile / http://kile.stravaganza.org/
  4937. * @author alteredq / http://alteredqualia.com/
  4938. * @author mikael emtinger / http://gomo.se/
  4939. * @author zz85 / http://www.lab4games.net/zz85/blog
  4940. * @author bhouston / http://exocortex.com
  4941. */
  4942. THREE.Geometry = function () {
  4943. this.id = THREE.GeometryIdCount ++;
  4944. this.uuid = THREE.Math.generateUUID();
  4945. this.name = '';
  4946. this.vertices = [];
  4947. this.colors = []; // one-to-one vertex colors, used in ParticleSystem and Line
  4948. this.faces = [];
  4949. this.faceVertexUvs = [[]];
  4950. this.morphTargets = [];
  4951. this.morphColors = [];
  4952. this.morphNormals = [];
  4953. this.skinWeights = [];
  4954. this.skinIndices = [];
  4955. this.lineDistances = [];
  4956. this.boundingBox = null;
  4957. this.boundingSphere = null;
  4958. this.hasTangents = false;
  4959. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4960. // update flags
  4961. this.verticesNeedUpdate = false;
  4962. this.elementsNeedUpdate = false;
  4963. this.uvsNeedUpdate = false;
  4964. this.normalsNeedUpdate = false;
  4965. this.tangentsNeedUpdate = false;
  4966. this.colorsNeedUpdate = false;
  4967. this.lineDistancesNeedUpdate = false;
  4968. this.buffersNeedUpdate = false;
  4969. };
  4970. THREE.Geometry.prototype = {
  4971. constructor: THREE.Geometry,
  4972. applyMatrix: function ( matrix ) {
  4973. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  4974. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4975. var vertex = this.vertices[ i ];
  4976. vertex.applyMatrix4( matrix );
  4977. }
  4978. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4979. var face = this.faces[ i ];
  4980. face.normal.applyMatrix3( normalMatrix ).normalize();
  4981. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4982. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4983. }
  4984. face.centroid.applyMatrix4( matrix );
  4985. }
  4986. if ( this.boundingBox instanceof THREE.Box3 ) {
  4987. this.computeBoundingBox();
  4988. }
  4989. if ( this.boundingSphere instanceof THREE.Sphere ) {
  4990. this.computeBoundingSphere();
  4991. }
  4992. },
  4993. computeCentroids: function () {
  4994. var f, fl, face;
  4995. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4996. face = this.faces[ f ];
  4997. face.centroid.set( 0, 0, 0 );
  4998. face.centroid.add( this.vertices[ face.a ] );
  4999. face.centroid.add( this.vertices[ face.b ] );
  5000. face.centroid.add( this.vertices[ face.c ] );
  5001. face.centroid.divideScalar( 3 );
  5002. }
  5003. },
  5004. computeFaceNormals: function () {
  5005. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5006. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5007. var face = this.faces[ f ];
  5008. var vA = this.vertices[ face.a ];
  5009. var vB = this.vertices[ face.b ];
  5010. var vC = this.vertices[ face.c ];
  5011. cb.subVectors( vC, vB );
  5012. ab.subVectors( vA, vB );
  5013. cb.cross( ab );
  5014. cb.normalize();
  5015. face.normal.copy( cb );
  5016. }
  5017. },
  5018. computeVertexNormals: function ( areaWeighted ) {
  5019. var v, vl, f, fl, face, vertices;
  5020. // create internal buffers for reuse when calling this method repeatedly
  5021. // (otherwise memory allocation / deallocation every frame is big resource hog)
  5022. if ( this.__tmpVertices === undefined ) {
  5023. this.__tmpVertices = new Array( this.vertices.length );
  5024. vertices = this.__tmpVertices;
  5025. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5026. vertices[ v ] = new THREE.Vector3();
  5027. }
  5028. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5029. face = this.faces[ f ];
  5030. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  5031. }
  5032. } else {
  5033. vertices = this.__tmpVertices;
  5034. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5035. vertices[ v ].set( 0, 0, 0 );
  5036. }
  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 ].copy( vertices[ face.a ] );
  5070. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  5071. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  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. // reset cache of vertices as it now will be changing.
  5246. this.__tmpVertices = undefined;
  5247. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  5248. v = this.vertices[ i ];
  5249. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  5250. if ( verticesMap[ key ] === undefined ) {
  5251. verticesMap[ key ] = i;
  5252. unique.push( this.vertices[ i ] );
  5253. changes[ i ] = unique.length - 1;
  5254. } else {
  5255. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  5256. changes[ i ] = changes[ verticesMap[ key ] ];
  5257. }
  5258. };
  5259. // if faces are completely degenerate after merging vertices, we
  5260. // have to remove them from the geometry.
  5261. var faceIndicesToRemove = [];
  5262. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  5263. face = this.faces[ i ];
  5264. face.a = changes[ face.a ];
  5265. face.b = changes[ face.b ];
  5266. face.c = changes[ face.c ];
  5267. indices = [ face.a, face.b, face.c ];
  5268. var dupIndex = -1;
  5269. // if any duplicate vertices are found in a Face3
  5270. // we have to remove the face as nothing can be saved
  5271. for ( var n = 0; n < 3; n ++ ) {
  5272. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  5273. dupIndex = n;
  5274. faceIndicesToRemove.push( i );
  5275. break;
  5276. }
  5277. }
  5278. }
  5279. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  5280. var idx = faceIndicesToRemove[ i ];
  5281. this.faces.splice( idx, 1 );
  5282. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5283. this.faceVertexUvs[ j ].splice( idx, 1 );
  5284. }
  5285. }
  5286. // Use unique set of vertices
  5287. var diff = this.vertices.length - unique.length;
  5288. this.vertices = unique;
  5289. return diff;
  5290. },
  5291. clone: function () {
  5292. var geometry = new THREE.Geometry();
  5293. var vertices = this.vertices;
  5294. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5295. geometry.vertices.push( vertices[ i ].clone() );
  5296. }
  5297. var faces = this.faces;
  5298. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  5299. geometry.faces.push( faces[ i ].clone() );
  5300. }
  5301. var uvs = this.faceVertexUvs[ 0 ];
  5302. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  5303. var uv = uvs[ i ], uvCopy = [];
  5304. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5305. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  5306. }
  5307. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  5308. }
  5309. return geometry;
  5310. },
  5311. dispose: function () {
  5312. this.dispatchEvent( { type: 'dispose' } );
  5313. }
  5314. };
  5315. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  5316. THREE.GeometryIdCount = 0;
  5317. /**
  5318. * @author alteredq / http://alteredqualia.com/
  5319. */
  5320. THREE.BufferGeometry = function () {
  5321. this.id = THREE.GeometryIdCount ++;
  5322. this.uuid = THREE.Math.generateUUID();
  5323. this.name = '';
  5324. // attributes
  5325. this.attributes = {};
  5326. // attributes typed arrays are kept only if dynamic flag is set
  5327. this.dynamic = true;
  5328. // offsets for chunks when using indexed elements
  5329. this.offsets = [];
  5330. // boundings
  5331. this.boundingBox = null;
  5332. this.boundingSphere = null;
  5333. this.hasTangents = false;
  5334. // for compatibility
  5335. this.morphTargets = [];
  5336. };
  5337. THREE.BufferGeometry.prototype = {
  5338. constructor: THREE.BufferGeometry,
  5339. addAttribute: function( name, type, numItems, itemSize ) {
  5340. this.attributes[ name ] = {
  5341. itemSize: itemSize,
  5342. array: new type( numItems * itemSize )
  5343. };
  5344. },
  5345. applyMatrix: function ( matrix ) {
  5346. var positionArray;
  5347. var normalArray;
  5348. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  5349. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  5350. if ( positionArray !== undefined ) {
  5351. matrix.multiplyVector3Array( positionArray );
  5352. this.verticesNeedUpdate = true;
  5353. }
  5354. if ( normalArray !== undefined ) {
  5355. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5356. normalMatrix.multiplyVector3Array( normalArray );
  5357. this.normalizeNormals();
  5358. this.normalsNeedUpdate = true;
  5359. }
  5360. },
  5361. computeBoundingBox: function () {
  5362. if ( this.boundingBox === null ) {
  5363. this.boundingBox = new THREE.Box3();
  5364. }
  5365. var positions = this.attributes[ "position" ].array;
  5366. if ( positions ) {
  5367. var bb = this.boundingBox;
  5368. var x, y, z;
  5369. if( positions.length >= 3 ) {
  5370. bb.min.x = bb.max.x = positions[ 0 ];
  5371. bb.min.y = bb.max.y = positions[ 1 ];
  5372. bb.min.z = bb.max.z = positions[ 2 ];
  5373. }
  5374. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5375. x = positions[ i ];
  5376. y = positions[ i + 1 ];
  5377. z = positions[ i + 2 ];
  5378. // bounding box
  5379. if ( x < bb.min.x ) {
  5380. bb.min.x = x;
  5381. } else if ( x > bb.max.x ) {
  5382. bb.max.x = x;
  5383. }
  5384. if ( y < bb.min.y ) {
  5385. bb.min.y = y;
  5386. } else if ( y > bb.max.y ) {
  5387. bb.max.y = y;
  5388. }
  5389. if ( z < bb.min.z ) {
  5390. bb.min.z = z;
  5391. } else if ( z > bb.max.z ) {
  5392. bb.max.z = z;
  5393. }
  5394. }
  5395. }
  5396. if ( positions === undefined || positions.length === 0 ) {
  5397. this.boundingBox.min.set( 0, 0, 0 );
  5398. this.boundingBox.max.set( 0, 0, 0 );
  5399. }
  5400. },
  5401. computeBoundingSphere: function () {
  5402. var box = new THREE.Box3();
  5403. var vector = new THREE.Vector3();
  5404. return function () {
  5405. if ( this.boundingSphere === null ) {
  5406. this.boundingSphere = new THREE.Sphere();
  5407. }
  5408. var positions = this.attributes[ "position" ].array;
  5409. if ( positions ) {
  5410. var center = this.boundingSphere.center;
  5411. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5412. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5413. box.addPoint( vector );
  5414. }
  5415. box.center( center );
  5416. var maxRadiusSq = 0;
  5417. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5418. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5419. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5420. }
  5421. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5422. }
  5423. }
  5424. }(),
  5425. computeVertexNormals: function () {
  5426. if ( this.attributes[ "position" ] ) {
  5427. var i, il;
  5428. var j, jl;
  5429. var nVertexElements = this.attributes[ "position" ].array.length;
  5430. if ( this.attributes[ "normal" ] === undefined ) {
  5431. this.attributes[ "normal" ] = {
  5432. itemSize: 3,
  5433. array: new Float32Array( nVertexElements )
  5434. };
  5435. } else {
  5436. // reset existing normals to zero
  5437. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5438. this.attributes[ "normal" ].array[ i ] = 0;
  5439. }
  5440. }
  5441. var positions = this.attributes[ "position" ].array;
  5442. var normals = this.attributes[ "normal" ].array;
  5443. var vA, vB, vC, x, y, z,
  5444. pA = new THREE.Vector3(),
  5445. pB = new THREE.Vector3(),
  5446. pC = new THREE.Vector3(),
  5447. cb = new THREE.Vector3(),
  5448. ab = new THREE.Vector3();
  5449. // indexed elements
  5450. if ( this.attributes[ "index" ] ) {
  5451. var indices = this.attributes[ "index" ].array;
  5452. var offsets = this.offsets;
  5453. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5454. var start = offsets[ j ].start;
  5455. var count = offsets[ j ].count;
  5456. var index = offsets[ j ].index;
  5457. for ( i = start, il = start + count; i < il; i += 3 ) {
  5458. vA = index + indices[ i ];
  5459. vB = index + indices[ i + 1 ];
  5460. vC = index + indices[ i + 2 ];
  5461. x = positions[ vA * 3 ];
  5462. y = positions[ vA * 3 + 1 ];
  5463. z = positions[ vA * 3 + 2 ];
  5464. pA.set( x, y, z );
  5465. x = positions[ vB * 3 ];
  5466. y = positions[ vB * 3 + 1 ];
  5467. z = positions[ vB * 3 + 2 ];
  5468. pB.set( x, y, z );
  5469. x = positions[ vC * 3 ];
  5470. y = positions[ vC * 3 + 1 ];
  5471. z = positions[ vC * 3 + 2 ];
  5472. pC.set( x, y, z );
  5473. cb.subVectors( pC, pB );
  5474. ab.subVectors( pA, pB );
  5475. cb.cross( ab );
  5476. normals[ vA * 3 ] += cb.x;
  5477. normals[ vA * 3 + 1 ] += cb.y;
  5478. normals[ vA * 3 + 2 ] += cb.z;
  5479. normals[ vB * 3 ] += cb.x;
  5480. normals[ vB * 3 + 1 ] += cb.y;
  5481. normals[ vB * 3 + 2 ] += cb.z;
  5482. normals[ vC * 3 ] += cb.x;
  5483. normals[ vC * 3 + 1 ] += cb.y;
  5484. normals[ vC * 3 + 2 ] += cb.z;
  5485. }
  5486. }
  5487. // non-indexed elements (unconnected triangle soup)
  5488. } else {
  5489. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5490. x = positions[ i ];
  5491. y = positions[ i + 1 ];
  5492. z = positions[ i + 2 ];
  5493. pA.set( x, y, z );
  5494. x = positions[ i + 3 ];
  5495. y = positions[ i + 4 ];
  5496. z = positions[ i + 5 ];
  5497. pB.set( x, y, z );
  5498. x = positions[ i + 6 ];
  5499. y = positions[ i + 7 ];
  5500. z = positions[ i + 8 ];
  5501. pC.set( x, y, z );
  5502. cb.subVectors( pC, pB );
  5503. ab.subVectors( pA, pB );
  5504. cb.cross( ab );
  5505. normals[ i ] = cb.x;
  5506. normals[ i + 1 ] = cb.y;
  5507. normals[ i + 2 ] = cb.z;
  5508. normals[ i + 3 ] = cb.x;
  5509. normals[ i + 4 ] = cb.y;
  5510. normals[ i + 5 ] = cb.z;
  5511. normals[ i + 6 ] = cb.x;
  5512. normals[ i + 7 ] = cb.y;
  5513. normals[ i + 8 ] = cb.z;
  5514. }
  5515. }
  5516. this.normalizeNormals();
  5517. this.normalsNeedUpdate = true;
  5518. }
  5519. },
  5520. normalizeNormals: function () {
  5521. var normals = this.attributes[ "normal" ].array;
  5522. var x, y, z, n;
  5523. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5524. x = normals[ i ];
  5525. y = normals[ i + 1 ];
  5526. z = normals[ i + 2 ];
  5527. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5528. normals[ i ] *= n;
  5529. normals[ i + 1 ] *= n;
  5530. normals[ i + 2 ] *= n;
  5531. }
  5532. },
  5533. computeTangents: function () {
  5534. // based on http://www.terathon.com/code/tangent.html
  5535. // (per vertex tangents)
  5536. if ( this.attributes[ "index" ] === undefined ||
  5537. this.attributes[ "position" ] === undefined ||
  5538. this.attributes[ "normal" ] === undefined ||
  5539. this.attributes[ "uv" ] === undefined ) {
  5540. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5541. return;
  5542. }
  5543. var indices = this.attributes[ "index" ].array;
  5544. var positions = this.attributes[ "position" ].array;
  5545. var normals = this.attributes[ "normal" ].array;
  5546. var uvs = this.attributes[ "uv" ].array;
  5547. var nVertices = positions.length / 3;
  5548. if ( this.attributes[ "tangent" ] === undefined ) {
  5549. var nTangentElements = 4 * nVertices;
  5550. this.attributes[ "tangent" ] = {
  5551. itemSize: 4,
  5552. array: new Float32Array( nTangentElements )
  5553. };
  5554. }
  5555. var tangents = this.attributes[ "tangent" ].array;
  5556. var tan1 = [], tan2 = [];
  5557. for ( var k = 0; k < nVertices; k ++ ) {
  5558. tan1[ k ] = new THREE.Vector3();
  5559. tan2[ k ] = new THREE.Vector3();
  5560. }
  5561. var xA, yA, zA,
  5562. xB, yB, zB,
  5563. xC, yC, zC,
  5564. uA, vA,
  5565. uB, vB,
  5566. uC, vC,
  5567. x1, x2, y1, y2, z1, z2,
  5568. s1, s2, t1, t2, r;
  5569. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5570. function handleTriangle( a, b, c ) {
  5571. xA = positions[ a * 3 ];
  5572. yA = positions[ a * 3 + 1 ];
  5573. zA = positions[ a * 3 + 2 ];
  5574. xB = positions[ b * 3 ];
  5575. yB = positions[ b * 3 + 1 ];
  5576. zB = positions[ b * 3 + 2 ];
  5577. xC = positions[ c * 3 ];
  5578. yC = positions[ c * 3 + 1 ];
  5579. zC = positions[ c * 3 + 2 ];
  5580. uA = uvs[ a * 2 ];
  5581. vA = uvs[ a * 2 + 1 ];
  5582. uB = uvs[ b * 2 ];
  5583. vB = uvs[ b * 2 + 1 ];
  5584. uC = uvs[ c * 2 ];
  5585. vC = uvs[ c * 2 + 1 ];
  5586. x1 = xB - xA;
  5587. x2 = xC - xA;
  5588. y1 = yB - yA;
  5589. y2 = yC - yA;
  5590. z1 = zB - zA;
  5591. z2 = zC - zA;
  5592. s1 = uB - uA;
  5593. s2 = uC - uA;
  5594. t1 = vB - vA;
  5595. t2 = vC - vA;
  5596. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5597. sdir.set(
  5598. ( t2 * x1 - t1 * x2 ) * r,
  5599. ( t2 * y1 - t1 * y2 ) * r,
  5600. ( t2 * z1 - t1 * z2 ) * r
  5601. );
  5602. tdir.set(
  5603. ( s1 * x2 - s2 * x1 ) * r,
  5604. ( s1 * y2 - s2 * y1 ) * r,
  5605. ( s1 * z2 - s2 * z1 ) * r
  5606. );
  5607. tan1[ a ].add( sdir );
  5608. tan1[ b ].add( sdir );
  5609. tan1[ c ].add( sdir );
  5610. tan2[ a ].add( tdir );
  5611. tan2[ b ].add( tdir );
  5612. tan2[ c ].add( tdir );
  5613. }
  5614. var i, il;
  5615. var j, jl;
  5616. var iA, iB, iC;
  5617. var offsets = this.offsets;
  5618. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5619. var start = offsets[ j ].start;
  5620. var count = offsets[ j ].count;
  5621. var index = offsets[ j ].index;
  5622. for ( i = start, il = start + count; i < il; i += 3 ) {
  5623. iA = index + indices[ i ];
  5624. iB = index + indices[ i + 1 ];
  5625. iC = index + indices[ i + 2 ];
  5626. handleTriangle( iA, iB, iC );
  5627. }
  5628. }
  5629. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5630. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5631. var w, t, test;
  5632. function handleVertex( v ) {
  5633. n.x = normals[ v * 3 ];
  5634. n.y = normals[ v * 3 + 1 ];
  5635. n.z = normals[ v * 3 + 2 ];
  5636. n2.copy( n );
  5637. t = tan1[ v ];
  5638. // Gram-Schmidt orthogonalize
  5639. tmp.copy( t );
  5640. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5641. // Calculate handedness
  5642. tmp2.crossVectors( n2, t );
  5643. test = tmp2.dot( tan2[ v ] );
  5644. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5645. tangents[ v * 4 ] = tmp.x;
  5646. tangents[ v * 4 + 1 ] = tmp.y;
  5647. tangents[ v * 4 + 2 ] = tmp.z;
  5648. tangents[ v * 4 + 3 ] = w;
  5649. }
  5650. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5651. var start = offsets[ j ].start;
  5652. var count = offsets[ j ].count;
  5653. var index = offsets[ j ].index;
  5654. for ( i = start, il = start + count; i < il; i += 3 ) {
  5655. iA = index + indices[ i ];
  5656. iB = index + indices[ i + 1 ];
  5657. iC = index + indices[ i + 2 ];
  5658. handleVertex( iA );
  5659. handleVertex( iB );
  5660. handleVertex( iC );
  5661. }
  5662. }
  5663. this.hasTangents = true;
  5664. this.tangentsNeedUpdate = true;
  5665. },
  5666. clone: function () {
  5667. var geometry = new THREE.BufferGeometry();
  5668. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5669. for ( var attr in this.attributes ) {
  5670. var sourceAttr = this.attributes[ attr ];
  5671. var sourceArray = sourceAttr.array;
  5672. var attribute = {
  5673. itemSize: sourceAttr.itemSize,
  5674. numItems: sourceAttr.numItems,
  5675. array: null
  5676. };
  5677. for ( var i = 0, il = types.length; i < il; i ++ ) {
  5678. var type = types[ i ];
  5679. if ( sourceArray instanceof type ) {
  5680. attribute.array = new type( sourceArray );
  5681. break;
  5682. }
  5683. }
  5684. geometry.attributes[ attr ] = attribute;
  5685. }
  5686. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  5687. var offset = this.offsets[ i ];
  5688. geometry.offsets.push( {
  5689. start: offset.start,
  5690. index: offset.index,
  5691. count: offset.count
  5692. } );
  5693. }
  5694. return geometry;
  5695. },
  5696. dispose: function () {
  5697. this.dispatchEvent( { type: 'dispose' } );
  5698. }
  5699. };
  5700. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  5701. /**
  5702. * @author mrdoob / http://mrdoob.com/
  5703. * @author mikael emtinger / http://gomo.se/
  5704. * @author WestLangley / http://github.com/WestLangley
  5705. */
  5706. THREE.Camera = function () {
  5707. THREE.Object3D.call( this );
  5708. this.matrixWorldInverse = new THREE.Matrix4();
  5709. this.projectionMatrix = new THREE.Matrix4();
  5710. this.projectionMatrixInverse = new THREE.Matrix4();
  5711. };
  5712. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5713. THREE.Camera.prototype.lookAt = function () {
  5714. // This routine does not support cameras with rotated and/or translated parent(s)
  5715. var m1 = new THREE.Matrix4();
  5716. return function ( vector ) {
  5717. m1.lookAt( this.position, vector, this.up );
  5718. this.quaternion.setFromRotationMatrix( m1 );
  5719. };
  5720. }();
  5721. THREE.Camera.prototype.clone = function (camera) {
  5722. if ( camera === undefined ) camera = new THREE.Camera();
  5723. THREE.Object3D.prototype.clone.call( this, camera );
  5724. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  5725. camera.projectionMatrix.copy( this.projectionMatrix );
  5726. camera.projectionMatrixInverse.copy( this.projectionMatrixInverse );
  5727. return camera;
  5728. };
  5729. /**
  5730. * @author alteredq / http://alteredqualia.com/
  5731. */
  5732. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5733. THREE.Camera.call( this );
  5734. this.left = left;
  5735. this.right = right;
  5736. this.top = top;
  5737. this.bottom = bottom;
  5738. this.near = ( near !== undefined ) ? near : 0.1;
  5739. this.far = ( far !== undefined ) ? far : 2000;
  5740. this.updateProjectionMatrix();
  5741. };
  5742. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5743. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5744. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5745. };
  5746. THREE.OrthographicCamera.prototype.clone = function () {
  5747. var camera = new THREE.OrthographicCamera();
  5748. THREE.Camera.prototype.clone.call( this, camera );
  5749. camera.left = this.left;
  5750. camera.right = this.right;
  5751. camera.top = this.top;
  5752. camera.bottom = this.bottom;
  5753. camera.near = this.near;
  5754. camera.far = this.far;
  5755. return camera;
  5756. };
  5757. /**
  5758. * @author mrdoob / http://mrdoob.com/
  5759. * @author greggman / http://games.greggman.com/
  5760. * @author zz85 / http://www.lab4games.net/zz85/blog
  5761. */
  5762. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5763. THREE.Camera.call( this );
  5764. this.fov = fov !== undefined ? fov : 50;
  5765. this.aspect = aspect !== undefined ? aspect : 1;
  5766. this.near = near !== undefined ? near : 0.1;
  5767. this.far = far !== undefined ? far : 2000;
  5768. this.updateProjectionMatrix();
  5769. };
  5770. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5771. /**
  5772. * Uses Focal Length (in mm) to estimate and set FOV
  5773. * 35mm (fullframe) camera is used if frame size is not specified;
  5774. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5775. */
  5776. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5777. if ( frameHeight === undefined ) frameHeight = 24;
  5778. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5779. this.updateProjectionMatrix();
  5780. }
  5781. /**
  5782. * Sets an offset in a larger frustum. This is useful for multi-window or
  5783. * multi-monitor/multi-machine setups.
  5784. *
  5785. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5786. * the monitors are in grid like this
  5787. *
  5788. * +---+---+---+
  5789. * | A | B | C |
  5790. * +---+---+---+
  5791. * | D | E | F |
  5792. * +---+---+---+
  5793. *
  5794. * then for each monitor you would call it like this
  5795. *
  5796. * var w = 1920;
  5797. * var h = 1080;
  5798. * var fullWidth = w * 3;
  5799. * var fullHeight = h * 2;
  5800. *
  5801. * --A--
  5802. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5803. * --B--
  5804. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5805. * --C--
  5806. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5807. * --D--
  5808. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5809. * --E--
  5810. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5811. * --F--
  5812. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5813. *
  5814. * Note there is no reason monitors have to be the same size or in a grid.
  5815. */
  5816. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5817. this.fullWidth = fullWidth;
  5818. this.fullHeight = fullHeight;
  5819. this.x = x;
  5820. this.y = y;
  5821. this.width = width;
  5822. this.height = height;
  5823. this.updateProjectionMatrix();
  5824. };
  5825. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5826. if ( this.fullWidth ) {
  5827. var aspect = this.fullWidth / this.fullHeight;
  5828. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5829. var bottom = -top;
  5830. var left = aspect * bottom;
  5831. var right = aspect * top;
  5832. var width = Math.abs( right - left );
  5833. var height = Math.abs( top - bottom );
  5834. this.projectionMatrix.makeFrustum(
  5835. left + this.x * width / this.fullWidth,
  5836. left + ( this.x + this.width ) * width / this.fullWidth,
  5837. top - ( this.y + this.height ) * height / this.fullHeight,
  5838. top - this.y * height / this.fullHeight,
  5839. this.near,
  5840. this.far
  5841. );
  5842. } else {
  5843. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5844. }
  5845. };
  5846. THREE.PerspectiveCamera.prototype.clone = function () {
  5847. var camera = new THREE.PerspectiveCamera();
  5848. THREE.Camera.prototype.clone.call( this, camera );
  5849. camera.fov = this.fov;
  5850. camera.aspect = this.aspect;
  5851. camera.near = this.near;
  5852. camera.far = this.far;
  5853. return camera;
  5854. };
  5855. /**
  5856. * @author mrdoob / http://mrdoob.com/
  5857. * @author alteredq / http://alteredqualia.com/
  5858. */
  5859. THREE.Light = function ( hex ) {
  5860. THREE.Object3D.call( this );
  5861. this.color = new THREE.Color( hex );
  5862. };
  5863. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5864. THREE.Light.prototype.clone = function ( light ) {
  5865. if ( light === undefined ) light = new THREE.Light();
  5866. THREE.Object3D.prototype.clone.call( this, light );
  5867. light.color.copy( this.color );
  5868. return light;
  5869. };
  5870. /**
  5871. * @author mrdoob / http://mrdoob.com/
  5872. */
  5873. THREE.AmbientLight = function ( hex ) {
  5874. THREE.Light.call( this, hex );
  5875. };
  5876. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5877. THREE.AmbientLight.prototype.clone = function () {
  5878. var light = new THREE.AmbientLight();
  5879. THREE.Light.prototype.clone.call( this, light );
  5880. return light;
  5881. };
  5882. /**
  5883. * @author MPanknin / http://www.redplant.de/
  5884. * @author alteredq / http://alteredqualia.com/
  5885. */
  5886. THREE.AreaLight = function ( hex, intensity ) {
  5887. THREE.Light.call( this, hex );
  5888. this.normal = new THREE.Vector3( 0, -1, 0 );
  5889. this.right = new THREE.Vector3( 1, 0, 0 );
  5890. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5891. this.width = 1.0;
  5892. this.height = 1.0;
  5893. this.constantAttenuation = 1.5;
  5894. this.linearAttenuation = 0.5;
  5895. this.quadraticAttenuation = 0.1;
  5896. };
  5897. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5898. /**
  5899. * @author mrdoob / http://mrdoob.com/
  5900. * @author alteredq / http://alteredqualia.com/
  5901. */
  5902. THREE.DirectionalLight = function ( hex, intensity ) {
  5903. THREE.Light.call( this, hex );
  5904. this.position.set( 0, 1, 0 );
  5905. this.target = new THREE.Object3D();
  5906. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5907. this.castShadow = false;
  5908. this.onlyShadow = false;
  5909. //
  5910. this.shadowCameraNear = 50;
  5911. this.shadowCameraFar = 5000;
  5912. this.shadowCameraLeft = -500;
  5913. this.shadowCameraRight = 500;
  5914. this.shadowCameraTop = 500;
  5915. this.shadowCameraBottom = -500;
  5916. this.shadowCameraVisible = false;
  5917. this.shadowBias = 0;
  5918. this.shadowDarkness = 0.5;
  5919. this.shadowMapWidth = 512;
  5920. this.shadowMapHeight = 512;
  5921. //
  5922. this.shadowCascade = false;
  5923. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5924. this.shadowCascadeCount = 2;
  5925. this.shadowCascadeBias = [ 0, 0, 0 ];
  5926. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5927. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5928. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5929. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5930. this.shadowCascadeArray = [];
  5931. //
  5932. this.shadowMap = null;
  5933. this.shadowMapSize = null;
  5934. this.shadowCamera = null;
  5935. this.shadowMatrix = null;
  5936. };
  5937. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5938. THREE.DirectionalLight.prototype.clone = function () {
  5939. var light = new THREE.DirectionalLight();
  5940. THREE.Light.prototype.clone.call( this, light );
  5941. light.target = this.target.clone();
  5942. light.intensity = this.intensity;
  5943. light.castShadow = this.castShadow;
  5944. light.onlyShadow = this.onlyShadow;
  5945. return light;
  5946. };
  5947. /**
  5948. * @author alteredq / http://alteredqualia.com/
  5949. */
  5950. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5951. THREE.Light.call( this, skyColorHex );
  5952. this.position.set( 0, 100, 0 );
  5953. this.groundColor = new THREE.Color( groundColorHex );
  5954. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5955. };
  5956. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5957. THREE.HemisphereLight.prototype.clone = function () {
  5958. var light = new THREE.HemisphereLight();
  5959. THREE.Light.prototype.clone.call( this, light );
  5960. light.groundColor.copy( this.groundColor );
  5961. light.intensity = this.intensity;
  5962. return light;
  5963. };
  5964. /**
  5965. * @author mrdoob / http://mrdoob.com/
  5966. */
  5967. THREE.PointLight = function ( hex, intensity, distance ) {
  5968. THREE.Light.call( this, hex );
  5969. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5970. this.distance = ( distance !== undefined ) ? distance : 0;
  5971. };
  5972. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5973. THREE.PointLight.prototype.clone = function () {
  5974. var light = new THREE.PointLight();
  5975. THREE.Light.prototype.clone.call( this, light );
  5976. light.intensity = this.intensity;
  5977. light.distance = this.distance;
  5978. return light;
  5979. };
  5980. /**
  5981. * @author alteredq / http://alteredqualia.com/
  5982. */
  5983. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5984. THREE.Light.call( this, hex );
  5985. this.position.set( 0, 1, 0 );
  5986. this.target = new THREE.Object3D();
  5987. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5988. this.distance = ( distance !== undefined ) ? distance : 0;
  5989. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  5990. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5991. this.castShadow = false;
  5992. this.onlyShadow = false;
  5993. //
  5994. this.shadowCameraNear = 50;
  5995. this.shadowCameraFar = 5000;
  5996. this.shadowCameraFov = 50;
  5997. this.shadowCameraVisible = false;
  5998. this.shadowBias = 0;
  5999. this.shadowDarkness = 0.5;
  6000. this.shadowMapWidth = 512;
  6001. this.shadowMapHeight = 512;
  6002. //
  6003. this.shadowMap = null;
  6004. this.shadowMapSize = null;
  6005. this.shadowCamera = null;
  6006. this.shadowMatrix = null;
  6007. };
  6008. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  6009. THREE.SpotLight.prototype.clone = function () {
  6010. var light = new THREE.SpotLight();
  6011. THREE.Light.prototype.clone.call( this, light );
  6012. light.target = this.target.clone();
  6013. light.intensity = this.intensity;
  6014. light.distance = this.distance;
  6015. light.angle = this.angle;
  6016. light.exponent = this.exponent;
  6017. light.castShadow = this.castShadow;
  6018. light.onlyShadow = this.onlyShadow;
  6019. return light;
  6020. };
  6021. /**
  6022. * @author alteredq / http://alteredqualia.com/
  6023. */
  6024. THREE.Loader = function ( showStatus ) {
  6025. this.showStatus = showStatus;
  6026. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6027. this.onLoadStart = function () {};
  6028. this.onLoadProgress = function () {};
  6029. this.onLoadComplete = function () {};
  6030. };
  6031. THREE.Loader.prototype = {
  6032. constructor: THREE.Loader,
  6033. crossOrigin: 'anonymous',
  6034. addStatusElement: function () {
  6035. var e = document.createElement( "div" );
  6036. e.style.position = "absolute";
  6037. e.style.right = "0px";
  6038. e.style.top = "0px";
  6039. e.style.fontSize = "0.8em";
  6040. e.style.textAlign = "left";
  6041. e.style.background = "rgba(0,0,0,0.25)";
  6042. e.style.color = "#fff";
  6043. e.style.width = "120px";
  6044. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  6045. e.style.zIndex = 1000;
  6046. e.innerHTML = "Loading ...";
  6047. return e;
  6048. },
  6049. updateProgress: function ( progress ) {
  6050. var message = "Loaded ";
  6051. if ( progress.total ) {
  6052. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  6053. } else {
  6054. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  6055. }
  6056. this.statusDomElement.innerHTML = message;
  6057. },
  6058. extractUrlBase: function ( url ) {
  6059. var parts = url.split( '/' );
  6060. parts.pop();
  6061. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  6062. },
  6063. initMaterials: function ( materials, texturePath ) {
  6064. var array = [];
  6065. for ( var i = 0; i < materials.length; ++ i ) {
  6066. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  6067. }
  6068. return array;
  6069. },
  6070. needsTangents: function ( materials ) {
  6071. for( var i = 0, il = materials.length; i < il; i ++ ) {
  6072. var m = materials[ i ];
  6073. if ( m instanceof THREE.ShaderMaterial ) return true;
  6074. }
  6075. return false;
  6076. },
  6077. createMaterial: function ( m, texturePath ) {
  6078. var _this = this;
  6079. function is_pow2( n ) {
  6080. var l = Math.log( n ) / Math.LN2;
  6081. return Math.floor( l ) == l;
  6082. }
  6083. function nearest_pow2( n ) {
  6084. var l = Math.log( n ) / Math.LN2;
  6085. return Math.pow( 2, Math.round( l ) );
  6086. }
  6087. function load_image( where, url ) {
  6088. var image = new Image();
  6089. image.onload = function () {
  6090. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  6091. var width = nearest_pow2( this.width );
  6092. var height = nearest_pow2( this.height );
  6093. where.image.width = width;
  6094. where.image.height = height;
  6095. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  6096. } else {
  6097. where.image = this;
  6098. }
  6099. where.needsUpdate = true;
  6100. };
  6101. image.crossOrigin = _this.crossOrigin;
  6102. image.src = url;
  6103. }
  6104. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  6105. var isCompressed = /\.dds$/i.test( sourceFile );
  6106. var fullPath = texturePath + "/" + sourceFile;
  6107. if ( isCompressed ) {
  6108. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  6109. where[ name ] = texture;
  6110. } else {
  6111. var texture = document.createElement( 'canvas' );
  6112. where[ name ] = new THREE.Texture( texture );
  6113. }
  6114. where[ name ].sourceFile = sourceFile;
  6115. if( repeat ) {
  6116. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6117. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  6118. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  6119. }
  6120. if ( offset ) {
  6121. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  6122. }
  6123. if ( wrap ) {
  6124. var wrapMap = {
  6125. "repeat": THREE.RepeatWrapping,
  6126. "mirror": THREE.MirroredRepeatWrapping
  6127. }
  6128. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  6129. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  6130. }
  6131. if ( anisotropy ) {
  6132. where[ name ].anisotropy = anisotropy;
  6133. }
  6134. if ( ! isCompressed ) {
  6135. load_image( where[ name ], fullPath );
  6136. }
  6137. }
  6138. function rgb2hex( rgb ) {
  6139. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6140. }
  6141. // defaults
  6142. var mtype = "MeshLambertMaterial";
  6143. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  6144. // parameters from model file
  6145. if ( m.shading ) {
  6146. var shading = m.shading.toLowerCase();
  6147. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  6148. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  6149. }
  6150. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6151. mpars.blending = THREE[ m.blending ];
  6152. }
  6153. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  6154. mpars.transparent = m.transparent;
  6155. }
  6156. if ( m.depthTest !== undefined ) {
  6157. mpars.depthTest = m.depthTest;
  6158. }
  6159. if ( m.depthWrite !== undefined ) {
  6160. mpars.depthWrite = m.depthWrite;
  6161. }
  6162. if ( m.visible !== undefined ) {
  6163. mpars.visible = m.visible;
  6164. }
  6165. if ( m.flipSided !== undefined ) {
  6166. mpars.side = THREE.BackSide;
  6167. }
  6168. if ( m.doubleSided !== undefined ) {
  6169. mpars.side = THREE.DoubleSide;
  6170. }
  6171. if ( m.wireframe !== undefined ) {
  6172. mpars.wireframe = m.wireframe;
  6173. }
  6174. if ( m.vertexColors !== undefined ) {
  6175. if ( m.vertexColors === "face" ) {
  6176. mpars.vertexColors = THREE.FaceColors;
  6177. } else if ( m.vertexColors ) {
  6178. mpars.vertexColors = THREE.VertexColors;
  6179. }
  6180. }
  6181. // colors
  6182. if ( m.colorDiffuse ) {
  6183. mpars.color = rgb2hex( m.colorDiffuse );
  6184. } else if ( m.DbgColor ) {
  6185. mpars.color = m.DbgColor;
  6186. }
  6187. if ( m.colorSpecular ) {
  6188. mpars.specular = rgb2hex( m.colorSpecular );
  6189. }
  6190. if ( m.colorAmbient ) {
  6191. mpars.ambient = rgb2hex( m.colorAmbient );
  6192. }
  6193. // modifiers
  6194. if ( m.transparency ) {
  6195. mpars.opacity = m.transparency;
  6196. }
  6197. if ( m.specularCoef ) {
  6198. mpars.shininess = m.specularCoef;
  6199. }
  6200. // textures
  6201. if ( m.mapDiffuse && texturePath ) {
  6202. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  6203. }
  6204. if ( m.mapLight && texturePath ) {
  6205. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  6206. }
  6207. if ( m.mapBump && texturePath ) {
  6208. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  6209. }
  6210. if ( m.mapNormal && texturePath ) {
  6211. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  6212. }
  6213. if ( m.mapSpecular && texturePath ) {
  6214. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  6215. }
  6216. //
  6217. if ( m.mapBumpScale ) {
  6218. mpars.bumpScale = m.mapBumpScale;
  6219. }
  6220. // special case for normal mapped material
  6221. if ( m.mapNormal ) {
  6222. var shader = THREE.ShaderLib[ "normalmap" ];
  6223. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6224. uniforms[ "tNormal" ].value = mpars.normalMap;
  6225. if ( m.mapNormalFactor ) {
  6226. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  6227. }
  6228. if ( mpars.map ) {
  6229. uniforms[ "tDiffuse" ].value = mpars.map;
  6230. uniforms[ "enableDiffuse" ].value = true;
  6231. }
  6232. if ( mpars.specularMap ) {
  6233. uniforms[ "tSpecular" ].value = mpars.specularMap;
  6234. uniforms[ "enableSpecular" ].value = true;
  6235. }
  6236. if ( mpars.lightMap ) {
  6237. uniforms[ "tAO" ].value = mpars.lightMap;
  6238. uniforms[ "enableAO" ].value = true;
  6239. }
  6240. // for the moment don't handle displacement texture
  6241. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  6242. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  6243. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  6244. uniforms[ "uShininess" ].value = mpars.shininess;
  6245. if ( mpars.opacity !== undefined ) {
  6246. uniforms[ "uOpacity" ].value = mpars.opacity;
  6247. }
  6248. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6249. var material = new THREE.ShaderMaterial( parameters );
  6250. if ( mpars.transparent ) {
  6251. material.transparent = true;
  6252. }
  6253. } else {
  6254. var material = new THREE[ mtype ]( mpars );
  6255. }
  6256. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6257. return material;
  6258. }
  6259. };
  6260. /**
  6261. * @author mrdoob / http://mrdoob.com/
  6262. */
  6263. THREE.XHRLoader = function ( manager ) {
  6264. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6265. };
  6266. THREE.XHRLoader.prototype = {
  6267. constructor: THREE.XHRLoader,
  6268. load: function ( url, onLoad, onProgress, onError ) {
  6269. var scope = this;
  6270. var request = new XMLHttpRequest();
  6271. if ( onLoad !== undefined ) {
  6272. request.addEventListener( 'load', function ( event ) {
  6273. onLoad( event.target.responseText );
  6274. scope.manager.itemEnd( url );
  6275. }, false );
  6276. }
  6277. if ( onProgress !== undefined ) {
  6278. request.addEventListener( 'progress', function ( event ) {
  6279. onProgress( event );
  6280. }, false );
  6281. }
  6282. if ( onError !== undefined ) {
  6283. request.addEventListener( 'error', function ( event ) {
  6284. onError( event );
  6285. }, false );
  6286. }
  6287. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6288. request.open( 'GET', url, true );
  6289. request.send( null );
  6290. scope.manager.itemStart( url );
  6291. },
  6292. setCrossOrigin: function ( value ) {
  6293. this.crossOrigin = value;
  6294. }
  6295. };
  6296. /**
  6297. * @author mrdoob / http://mrdoob.com/
  6298. */
  6299. THREE.ImageLoader = function ( manager ) {
  6300. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6301. };
  6302. THREE.ImageLoader.prototype = {
  6303. constructor: THREE.ImageLoader,
  6304. load: function ( url, onLoad, onProgress, onError ) {
  6305. var scope = this;
  6306. var image = document.createElement( 'img' );
  6307. if ( onLoad !== undefined ) {
  6308. image.addEventListener( 'load', function ( event ) {
  6309. scope.manager.itemEnd( url );
  6310. onLoad( this );
  6311. }, false );
  6312. }
  6313. if ( onProgress !== undefined ) {
  6314. image.addEventListener( 'progress', function ( event ) {
  6315. onProgress( event );
  6316. }, false );
  6317. }
  6318. if ( onError !== undefined ) {
  6319. image.addEventListener( 'error', function ( event ) {
  6320. onError( event );
  6321. }, false );
  6322. }
  6323. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  6324. image.src = url;
  6325. scope.manager.itemStart( url );
  6326. return image;
  6327. },
  6328. setCrossOrigin: function ( value ) {
  6329. this.crossOrigin = value;
  6330. }
  6331. }
  6332. /**
  6333. * @author mrdoob / http://mrdoob.com/
  6334. * @author alteredq / http://alteredqualia.com/
  6335. */
  6336. THREE.JSONLoader = function ( showStatus ) {
  6337. THREE.Loader.call( this, showStatus );
  6338. this.withCredentials = false;
  6339. };
  6340. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  6341. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  6342. var scope = this;
  6343. // todo: unify load API to for easier SceneLoader use
  6344. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  6345. this.onLoadStart();
  6346. this.loadAjaxJSON( this, url, callback, texturePath );
  6347. };
  6348. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  6349. var xhr = new XMLHttpRequest();
  6350. var length = 0;
  6351. xhr.onreadystatechange = function () {
  6352. if ( xhr.readyState === xhr.DONE ) {
  6353. if ( xhr.status === 200 || xhr.status === 0 ) {
  6354. if ( xhr.responseText ) {
  6355. var json = JSON.parse( xhr.responseText );
  6356. var result = context.parse( json, texturePath );
  6357. callback( result.geometry, result.materials );
  6358. } else {
  6359. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  6360. }
  6361. // in context of more complex asset initialization
  6362. // do not block on single failed file
  6363. // maybe should go even one more level up
  6364. context.onLoadComplete();
  6365. } else {
  6366. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  6367. }
  6368. } else if ( xhr.readyState === xhr.LOADING ) {
  6369. if ( callbackProgress ) {
  6370. if ( length === 0 ) {
  6371. length = xhr.getResponseHeader( "Content-Length" );
  6372. }
  6373. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  6374. }
  6375. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  6376. if ( callbackProgress !== undefined ) {
  6377. length = xhr.getResponseHeader( "Content-Length" );
  6378. }
  6379. }
  6380. };
  6381. xhr.open( "GET", url, true );
  6382. xhr.withCredentials = this.withCredentials;
  6383. xhr.send( null );
  6384. };
  6385. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  6386. var scope = this,
  6387. geometry = new THREE.Geometry(),
  6388. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  6389. parseModel( scale );
  6390. parseSkin();
  6391. parseMorphing( scale );
  6392. geometry.computeCentroids();
  6393. geometry.computeFaceNormals();
  6394. geometry.computeBoundingSphere();
  6395. function parseModel( scale ) {
  6396. function isBitSet( value, position ) {
  6397. return value & ( 1 << position );
  6398. }
  6399. var i, j, fi,
  6400. offset, zLength,
  6401. colorIndex, normalIndex, uvIndex, materialIndex,
  6402. type,
  6403. isQuad,
  6404. hasMaterial,
  6405. hasFaceVertexUv,
  6406. hasFaceNormal, hasFaceVertexNormal,
  6407. hasFaceColor, hasFaceVertexColor,
  6408. vertex, face, faceA, faceB, color, hex, normal,
  6409. uvLayer, uv, u, v,
  6410. faces = json.faces,
  6411. vertices = json.vertices,
  6412. normals = json.normals,
  6413. colors = json.colors,
  6414. nUvLayers = 0;
  6415. if ( json.uvs !== undefined ) {
  6416. // disregard empty arrays
  6417. for ( i = 0; i < json.uvs.length; i++ ) {
  6418. if ( json.uvs[ i ].length ) nUvLayers ++;
  6419. }
  6420. for ( i = 0; i < nUvLayers; i++ ) {
  6421. geometry.faceVertexUvs[ i ] = [];
  6422. }
  6423. }
  6424. offset = 0;
  6425. zLength = vertices.length;
  6426. while ( offset < zLength ) {
  6427. vertex = new THREE.Vector3();
  6428. vertex.x = vertices[ offset ++ ] * scale;
  6429. vertex.y = vertices[ offset ++ ] * scale;
  6430. vertex.z = vertices[ offset ++ ] * scale;
  6431. geometry.vertices.push( vertex );
  6432. }
  6433. offset = 0;
  6434. zLength = faces.length;
  6435. while ( offset < zLength ) {
  6436. type = faces[ offset ++ ];
  6437. isQuad = isBitSet( type, 0 );
  6438. hasMaterial = isBitSet( type, 1 );
  6439. hasFaceVertexUv = isBitSet( type, 3 );
  6440. hasFaceNormal = isBitSet( type, 4 );
  6441. hasFaceVertexNormal = isBitSet( type, 5 );
  6442. hasFaceColor = isBitSet( type, 6 );
  6443. hasFaceVertexColor = isBitSet( type, 7 );
  6444. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  6445. if ( isQuad ) {
  6446. faceA = new THREE.Face3();
  6447. faceA.a = faces[ offset ];
  6448. faceA.b = faces[ offset + 1 ];
  6449. faceA.c = faces[ offset + 3 ];
  6450. faceB = new THREE.Face3();
  6451. faceB.a = faces[ offset + 1 ];
  6452. faceB.b = faces[ offset + 2 ];
  6453. faceB.c = faces[ offset + 3 ];
  6454. offset += 4;
  6455. if ( hasMaterial ) {
  6456. materialIndex = faces[ offset ++ ];
  6457. faceA.materialIndex = materialIndex;
  6458. faceB.materialIndex = materialIndex;
  6459. }
  6460. // to get face <=> uv index correspondence
  6461. fi = geometry.faces.length;
  6462. if ( hasFaceVertexUv ) {
  6463. for ( i = 0; i < nUvLayers; i++ ) {
  6464. uvLayer = json.uvs[ i ];
  6465. geometry.faceVertexUvs[ i ][ fi ] = [];
  6466. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  6467. for ( j = 0; j < 4; j ++ ) {
  6468. uvIndex = faces[ offset ++ ];
  6469. u = uvLayer[ uvIndex * 2 ];
  6470. v = uvLayer[ uvIndex * 2 + 1 ];
  6471. uv = new THREE.Vector2( u, v );
  6472. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  6473. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  6474. }
  6475. }
  6476. }
  6477. if ( hasFaceNormal ) {
  6478. normalIndex = faces[ offset ++ ] * 3;
  6479. faceA.normal.set(
  6480. normals[ normalIndex ++ ],
  6481. normals[ normalIndex ++ ],
  6482. normals[ normalIndex ]
  6483. );
  6484. faceB.normal.copy( faceA.normal );
  6485. }
  6486. if ( hasFaceVertexNormal ) {
  6487. for ( i = 0; i < 4; i++ ) {
  6488. normalIndex = faces[ offset ++ ] * 3;
  6489. normal = new THREE.Vector3(
  6490. normals[ normalIndex ++ ],
  6491. normals[ normalIndex ++ ],
  6492. normals[ normalIndex ]
  6493. );
  6494. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  6495. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  6496. }
  6497. }
  6498. if ( hasFaceColor ) {
  6499. colorIndex = faces[ offset ++ ];
  6500. hex = colors[ colorIndex ];
  6501. faceA.color.setHex( hex );
  6502. faceB.color.setHex( hex );
  6503. }
  6504. if ( hasFaceVertexColor ) {
  6505. for ( i = 0; i < 4; i++ ) {
  6506. colorIndex = faces[ offset ++ ];
  6507. hex = colors[ colorIndex ];
  6508. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  6509. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  6510. }
  6511. }
  6512. geometry.faces.push( faceA );
  6513. geometry.faces.push( faceB );
  6514. } else {
  6515. face = new THREE.Face3();
  6516. face.a = faces[ offset ++ ];
  6517. face.b = faces[ offset ++ ];
  6518. face.c = faces[ offset ++ ];
  6519. if ( hasMaterial ) {
  6520. materialIndex = faces[ offset ++ ];
  6521. face.materialIndex = materialIndex;
  6522. }
  6523. // to get face <=> uv index correspondence
  6524. fi = geometry.faces.length;
  6525. if ( hasFaceVertexUv ) {
  6526. for ( i = 0; i < nUvLayers; i++ ) {
  6527. uvLayer = json.uvs[ i ];
  6528. geometry.faceVertexUvs[ i ][ fi ] = [];
  6529. for ( j = 0; j < 3; j ++ ) {
  6530. uvIndex = faces[ offset ++ ];
  6531. u = uvLayer[ uvIndex * 2 ];
  6532. v = uvLayer[ uvIndex * 2 + 1 ];
  6533. uv = new THREE.Vector2( u, v );
  6534. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  6535. }
  6536. }
  6537. }
  6538. if ( hasFaceNormal ) {
  6539. normalIndex = faces[ offset ++ ] * 3;
  6540. face.normal.set(
  6541. normals[ normalIndex ++ ],
  6542. normals[ normalIndex ++ ],
  6543. normals[ normalIndex ]
  6544. );
  6545. }
  6546. if ( hasFaceVertexNormal ) {
  6547. for ( i = 0; i < 3; i++ ) {
  6548. normalIndex = faces[ offset ++ ] * 3;
  6549. normal = new THREE.Vector3(
  6550. normals[ normalIndex ++ ],
  6551. normals[ normalIndex ++ ],
  6552. normals[ normalIndex ]
  6553. );
  6554. face.vertexNormals.push( normal );
  6555. }
  6556. }
  6557. if ( hasFaceColor ) {
  6558. colorIndex = faces[ offset ++ ];
  6559. face.color.setHex( colors[ colorIndex ] );
  6560. }
  6561. if ( hasFaceVertexColor ) {
  6562. for ( i = 0; i < 3; i++ ) {
  6563. colorIndex = faces[ offset ++ ];
  6564. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  6565. }
  6566. }
  6567. geometry.faces.push( face );
  6568. }
  6569. }
  6570. };
  6571. function parseSkin() {
  6572. var i, l, x, y, z, w, a, b, c, d;
  6573. if ( json.skinWeights ) {
  6574. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  6575. x = json.skinWeights[ i ];
  6576. y = json.skinWeights[ i + 1 ];
  6577. z = 0;
  6578. w = 0;
  6579. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  6580. }
  6581. }
  6582. if ( json.skinIndices ) {
  6583. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  6584. a = json.skinIndices[ i ];
  6585. b = json.skinIndices[ i + 1 ];
  6586. c = 0;
  6587. d = 0;
  6588. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  6589. }
  6590. }
  6591. geometry.bones = json.bones;
  6592. // could change this to json.animations[0] or remove completely
  6593. geometry.animation = json.animation;
  6594. geometry.animations = json.animations;
  6595. };
  6596. function parseMorphing( scale ) {
  6597. if ( json.morphTargets !== undefined ) {
  6598. var i, l, v, vl, dstVertices, srcVertices;
  6599. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  6600. geometry.morphTargets[ i ] = {};
  6601. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  6602. geometry.morphTargets[ i ].vertices = [];
  6603. dstVertices = geometry.morphTargets[ i ].vertices;
  6604. srcVertices = json.morphTargets [ i ].vertices;
  6605. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  6606. var vertex = new THREE.Vector3();
  6607. vertex.x = srcVertices[ v ] * scale;
  6608. vertex.y = srcVertices[ v + 1 ] * scale;
  6609. vertex.z = srcVertices[ v + 2 ] * scale;
  6610. dstVertices.push( vertex );
  6611. }
  6612. }
  6613. }
  6614. if ( json.morphColors !== undefined ) {
  6615. var i, l, c, cl, dstColors, srcColors, color;
  6616. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  6617. geometry.morphColors[ i ] = {};
  6618. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  6619. geometry.morphColors[ i ].colors = [];
  6620. dstColors = geometry.morphColors[ i ].colors;
  6621. srcColors = json.morphColors [ i ].colors;
  6622. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  6623. color = new THREE.Color( 0xffaa00 );
  6624. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  6625. dstColors.push( color );
  6626. }
  6627. }
  6628. }
  6629. };
  6630. if ( json.materials === undefined ) {
  6631. return { geometry: geometry };
  6632. } else {
  6633. var materials = this.initMaterials( json.materials, texturePath );
  6634. if ( this.needsTangents( materials ) ) {
  6635. geometry.computeTangents();
  6636. }
  6637. return { geometry: geometry, materials: materials };
  6638. }
  6639. };
  6640. /**
  6641. * @author mrdoob / http://mrdoob.com/
  6642. */
  6643. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  6644. var scope = this;
  6645. var loaded = 0, total = 0;
  6646. this.onLoad = onLoad;
  6647. this.onProgress = onProgress;
  6648. this.onError = onError;
  6649. this.itemStart = function ( url ) {
  6650. total ++;
  6651. };
  6652. this.itemEnd = function ( url ) {
  6653. loaded ++;
  6654. if ( scope.onProgress !== undefined ) {
  6655. scope.onProgress( url, loaded, total );
  6656. }
  6657. if ( loaded === total && scope.onLoad !== undefined ) {
  6658. scope.onLoad();
  6659. }
  6660. };
  6661. };
  6662. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  6663. /**
  6664. * @author mrdoob / http://mrdoob.com/
  6665. */
  6666. THREE.BufferGeometryLoader = function ( manager ) {
  6667. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6668. };
  6669. THREE.BufferGeometryLoader.prototype = {
  6670. constructor: THREE.BufferGeometryLoader,
  6671. load: function ( url, onLoad, onProgress, onError ) {
  6672. var scope = this;
  6673. var loader = new THREE.XHRLoader();
  6674. loader.setCrossOrigin( this.crossOrigin );
  6675. loader.load( url, function ( text ) {
  6676. onLoad( scope.parse( JSON.parse( text ) ) );
  6677. } );
  6678. },
  6679. setCrossOrigin: function ( value ) {
  6680. this.crossOrigin = value;
  6681. },
  6682. parse: function ( json ) {
  6683. var geometry = new THREE.BufferGeometry();
  6684. var attributes = json.attributes;
  6685. var offsets = json.offsets;
  6686. var boundingSphere = json.boundingSphere;
  6687. for ( var key in attributes ) {
  6688. var attribute = attributes[ key ];
  6689. geometry.attributes[ key ] = {
  6690. itemSize: attribute.itemSize,
  6691. array: new self[ attribute.type ]( attribute.array )
  6692. }
  6693. }
  6694. if ( offsets !== undefined ) {
  6695. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  6696. }
  6697. if ( boundingSphere !== undefined ) {
  6698. geometry.boundingSphere = new THREE.Sphere(
  6699. new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
  6700. boundingSphere.radius
  6701. );
  6702. }
  6703. return geometry;
  6704. }
  6705. };
  6706. /**
  6707. * @author mrdoob / http://mrdoob.com/
  6708. */
  6709. THREE.GeometryLoader = function ( manager ) {
  6710. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6711. };
  6712. THREE.GeometryLoader.prototype = {
  6713. constructor: THREE.GeometryLoader,
  6714. load: function ( url, onLoad, onProgress, onError ) {
  6715. var scope = this;
  6716. var loader = new THREE.XHRLoader();
  6717. loader.setCrossOrigin( this.crossOrigin );
  6718. loader.load( url, function ( text ) {
  6719. onLoad( scope.parse( JSON.parse( text ) ) );
  6720. } );
  6721. },
  6722. setCrossOrigin: function ( value ) {
  6723. this.crossOrigin = value;
  6724. },
  6725. parse: function ( json ) {
  6726. }
  6727. };
  6728. /**
  6729. * @author mrdoob / http://mrdoob.com/
  6730. */
  6731. THREE.MaterialLoader = function ( manager ) {
  6732. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6733. };
  6734. THREE.MaterialLoader.prototype = {
  6735. constructor: THREE.MaterialLoader,
  6736. load: function ( url, onLoad, onProgress, onError ) {
  6737. var scope = this;
  6738. var loader = new THREE.XHRLoader();
  6739. loader.setCrossOrigin( this.crossOrigin );
  6740. loader.load( url, function ( text ) {
  6741. onLoad( scope.parse( JSON.parse( text ) ) );
  6742. } );
  6743. },
  6744. setCrossOrigin: function ( value ) {
  6745. this.crossOrigin = value;
  6746. },
  6747. parse: function ( json ) {
  6748. var material = new THREE[ json.type ];
  6749. if ( json.color !== undefined ) material.color.setHex( json.color );
  6750. if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient );
  6751. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  6752. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  6753. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  6754. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  6755. if ( json.blending !== undefined ) material.blending = json.blending;
  6756. if ( json.side !== undefined ) material.side = json.side;
  6757. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  6758. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  6759. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  6760. if ( json.materials !== undefined ) {
  6761. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  6762. material.materials.push( this.parse( json.materials[ i ] ) );
  6763. }
  6764. }
  6765. return material;
  6766. }
  6767. };
  6768. /**
  6769. * @author mrdoob / http://mrdoob.com/
  6770. */
  6771. THREE.ObjectLoader = function ( manager ) {
  6772. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6773. };
  6774. THREE.ObjectLoader.prototype = {
  6775. constructor: THREE.ObjectLoader,
  6776. load: function ( url, onLoad, onProgress, onError ) {
  6777. var scope = this;
  6778. var loader = new THREE.XHRLoader( scope.manager );
  6779. loader.setCrossOrigin( this.crossOrigin );
  6780. loader.load( url, function ( text ) {
  6781. onLoad( scope.parse( JSON.parse( text ) ) );
  6782. } );
  6783. },
  6784. setCrossOrigin: function ( value ) {
  6785. this.crossOrigin = value;
  6786. },
  6787. parse: function ( json ) {
  6788. var geometries = this.parseGeometries( json.geometries );
  6789. var materials = this.parseMaterials( json.materials );
  6790. var object = this.parseObject( json.object, geometries, materials );
  6791. return object;
  6792. },
  6793. parseGeometries: function ( json ) {
  6794. var geometries = {};
  6795. if ( json !== undefined ) {
  6796. var geometryLoader = new THREE.JSONLoader();
  6797. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  6798. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6799. var geometry;
  6800. var data = json[ i ];
  6801. switch ( data.type ) {
  6802. case 'PlaneGeometry':
  6803. geometry = new THREE.PlaneGeometry(
  6804. data.width,
  6805. data.height,
  6806. data.widthSegments,
  6807. data.heightSegments
  6808. );
  6809. break;
  6810. case 'CircleGeometry':
  6811. geometry = new THREE.CircleGeometry(
  6812. data.radius,
  6813. data.segments
  6814. );
  6815. break;
  6816. case 'CubeGeometry':
  6817. geometry = new THREE.CubeGeometry(
  6818. data.width,
  6819. data.height,
  6820. data.depth,
  6821. data.widthSegments,
  6822. data.heightSegments,
  6823. data.depthSegments
  6824. );
  6825. break;
  6826. case 'CylinderGeometry':
  6827. geometry = new THREE.CylinderGeometry(
  6828. data.radiusTop,
  6829. data.radiusBottom,
  6830. data.height,
  6831. data.radialSegments,
  6832. data.heightSegments,
  6833. data.openEnded
  6834. );
  6835. break;
  6836. case 'SphereGeometry':
  6837. geometry = new THREE.SphereGeometry(
  6838. data.radius,
  6839. data.widthSegments,
  6840. data.heightSegments,
  6841. data.phiStart,
  6842. data.phiLength,
  6843. data.thetaStart,
  6844. data.thetaLength
  6845. );
  6846. break;
  6847. case 'IcosahedronGeometry':
  6848. geometry = new THREE.IcosahedronGeometry(
  6849. data.radius,
  6850. data.detail
  6851. );
  6852. break;
  6853. case 'TorusGeometry':
  6854. geometry = new THREE.TorusGeometry(
  6855. data.radius,
  6856. data.tube,
  6857. data.radialSegments,
  6858. data.tubularSegments,
  6859. data.arc
  6860. );
  6861. break;
  6862. case 'TorusKnotGeometry':
  6863. geometry = new THREE.TorusKnotGeometry(
  6864. data.radius,
  6865. data.tube,
  6866. data.radialSegments,
  6867. data.tubularSegments,
  6868. data.p,
  6869. data.q,
  6870. data.heightScale
  6871. );
  6872. break;
  6873. case 'BufferGeometry':
  6874. geometry = bufferGeometryLoader.parse( data.data );
  6875. break;
  6876. case 'Geometry':
  6877. geometry = geometryLoader.parse( data.data ).geometry;
  6878. break;
  6879. }
  6880. geometry.uuid = data.uuid;
  6881. if ( data.name !== undefined ) geometry.name = data.name;
  6882. geometries[ data.uuid ] = geometry;
  6883. }
  6884. }
  6885. return geometries;
  6886. },
  6887. parseMaterials: function ( json ) {
  6888. var materials = {};
  6889. if ( json !== undefined ) {
  6890. var loader = new THREE.MaterialLoader();
  6891. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6892. var data = json[ i ];
  6893. var material = loader.parse( data );
  6894. material.uuid = data.uuid;
  6895. if ( data.name !== undefined ) material.name = data.name;
  6896. materials[ data.uuid ] = material;
  6897. }
  6898. }
  6899. return materials;
  6900. },
  6901. parseObject: function () {
  6902. var matrix = new THREE.Matrix4();
  6903. return function ( data, geometries, materials ) {
  6904. var object;
  6905. switch ( data.type ) {
  6906. case 'Scene':
  6907. object = new THREE.Scene();
  6908. break;
  6909. case 'PerspectiveCamera':
  6910. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  6911. break;
  6912. case 'OrthographicCamera':
  6913. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  6914. break;
  6915. case 'AmbientLight':
  6916. object = new THREE.AmbientLight( data.color );
  6917. break;
  6918. case 'DirectionalLight':
  6919. object = new THREE.DirectionalLight( data.color, data.intensity );
  6920. break;
  6921. case 'PointLight':
  6922. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  6923. break;
  6924. case 'SpotLight':
  6925. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  6926. break;
  6927. case 'HemisphereLight':
  6928. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  6929. break;
  6930. case 'Mesh':
  6931. var geometry = geometries[ data.geometry ];
  6932. var material = materials[ data.material ];
  6933. if ( geometry === undefined ) {
  6934. console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry );
  6935. }
  6936. if ( material === undefined ) {
  6937. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  6938. }
  6939. object = new THREE.Mesh( geometry, material );
  6940. break;
  6941. case 'Sprite':
  6942. var material = materials[ data.material ];
  6943. if ( material === undefined ) {
  6944. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  6945. }
  6946. object = new THREE.Sprite( material );
  6947. break;
  6948. default:
  6949. object = new THREE.Object3D();
  6950. }
  6951. object.uuid = data.uuid;
  6952. if ( data.name !== undefined ) object.name = data.name;
  6953. if ( data.matrix !== undefined ) {
  6954. matrix.fromArray( data.matrix );
  6955. matrix.decompose( object.position, object.quaternion, object.scale );
  6956. } else {
  6957. if ( data.position !== undefined ) object.position.fromArray( data.position );
  6958. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  6959. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  6960. }
  6961. if ( data.visible !== undefined ) object.visible = data.visible;
  6962. if ( data.userData !== undefined ) object.userData = data.userData;
  6963. if ( data.children !== undefined ) {
  6964. for ( var child in data.children ) {
  6965. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  6966. }
  6967. }
  6968. return object;
  6969. }
  6970. }()
  6971. };
  6972. /**
  6973. * @author alteredq / http://alteredqualia.com/
  6974. */
  6975. THREE.SceneLoader = function () {
  6976. this.onLoadStart = function () {};
  6977. this.onLoadProgress = function() {};
  6978. this.onLoadComplete = function () {};
  6979. this.callbackSync = function () {};
  6980. this.callbackProgress = function () {};
  6981. this.geometryHandlers = {};
  6982. this.hierarchyHandlers = {};
  6983. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  6984. };
  6985. THREE.SceneLoader.prototype = {
  6986. constructor: THREE.SceneLoader,
  6987. load: function ( url, onLoad, onProgress, onError ) {
  6988. var scope = this;
  6989. var loader = new THREE.XHRLoader( scope.manager );
  6990. loader.setCrossOrigin( this.crossOrigin );
  6991. loader.load( url, function ( text ) {
  6992. scope.parse( JSON.parse( text ), onLoad, url );
  6993. } );
  6994. },
  6995. setCrossOrigin: function ( value ) {
  6996. this.crossOrigin = value;
  6997. },
  6998. addGeometryHandler: function ( typeID, loaderClass ) {
  6999. this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass };
  7000. },
  7001. addHierarchyHandler: function ( typeID, loaderClass ) {
  7002. this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass };
  7003. },
  7004. parse: function ( json, callbackFinished, url ) {
  7005. var scope = this;
  7006. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  7007. var geometry, material, camera, fog,
  7008. texture, images, color,
  7009. light, hex, intensity,
  7010. counter_models, counter_textures,
  7011. total_models, total_textures,
  7012. result;
  7013. var target_array = [];
  7014. var data = json;
  7015. // async geometry loaders
  7016. for ( var typeID in this.geometryHandlers ) {
  7017. var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ];
  7018. this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7019. }
  7020. // async hierachy loaders
  7021. for ( var typeID in this.hierarchyHandlers ) {
  7022. var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ];
  7023. this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7024. }
  7025. counter_models = 0;
  7026. counter_textures = 0;
  7027. result = {
  7028. scene: new THREE.Scene(),
  7029. geometries: {},
  7030. face_materials: {},
  7031. materials: {},
  7032. textures: {},
  7033. objects: {},
  7034. cameras: {},
  7035. lights: {},
  7036. fogs: {},
  7037. empties: {},
  7038. groups: {}
  7039. };
  7040. if ( data.transform ) {
  7041. var position = data.transform.position,
  7042. rotation = data.transform.rotation,
  7043. scale = data.transform.scale;
  7044. if ( position ) {
  7045. result.scene.position.fromArray( position );
  7046. }
  7047. if ( rotation ) {
  7048. result.scene.rotation.fromArray( rotation );
  7049. }
  7050. if ( scale ) {
  7051. result.scene.scale.fromArray( scale );
  7052. }
  7053. if ( position || rotation || scale ) {
  7054. result.scene.updateMatrix();
  7055. result.scene.updateMatrixWorld();
  7056. }
  7057. }
  7058. function get_url( source_url, url_type ) {
  7059. if ( url_type == "relativeToHTML" ) {
  7060. return source_url;
  7061. } else {
  7062. return urlBase + "/" + source_url;
  7063. }
  7064. };
  7065. // toplevel loader function, delegates to handle_children
  7066. function handle_objects() {
  7067. handle_children( result.scene, data.objects );
  7068. }
  7069. // handle all the children from the loaded json and attach them to given parent
  7070. function handle_children( parent, children ) {
  7071. var mat, dst, pos, rot, scl, quat;
  7072. for ( var objID in children ) {
  7073. // check by id if child has already been handled,
  7074. // if not, create new object
  7075. var object = result.objects[ objID ];
  7076. var objJSON = children[ objID ];
  7077. if ( object === undefined ) {
  7078. // meshes
  7079. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7080. if ( objJSON.loading === undefined ) {
  7081. var reservedTypes = {
  7082. "type": 1, "url": 1, "material": 1,
  7083. "position": 1, "rotation": 1, "scale" : 1,
  7084. "visible": 1, "children": 1, "userData": 1,
  7085. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
  7086. };
  7087. var loaderParameters = {};
  7088. for ( var parType in objJSON ) {
  7089. if ( ! ( parType in reservedTypes ) ) {
  7090. loaderParameters[ parType ] = objJSON[ parType ];
  7091. }
  7092. }
  7093. material = result.materials[ objJSON.material ];
  7094. objJSON.loading = true;
  7095. var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
  7096. // ColladaLoader
  7097. if ( loader.options ) {
  7098. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  7099. // UTF8Loader
  7100. // OBJLoader
  7101. } else {
  7102. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  7103. }
  7104. }
  7105. } else if ( objJSON.geometry !== undefined ) {
  7106. geometry = result.geometries[ objJSON.geometry ];
  7107. // geometry already loaded
  7108. if ( geometry ) {
  7109. var needsTangents = false;
  7110. material = result.materials[ objJSON.material ];
  7111. needsTangents = material instanceof THREE.ShaderMaterial;
  7112. pos = objJSON.position;
  7113. rot = objJSON.rotation;
  7114. scl = objJSON.scale;
  7115. mat = objJSON.matrix;
  7116. quat = objJSON.quaternion;
  7117. // use materials from the model file
  7118. // if there is no material specified in the object
  7119. if ( ! objJSON.material ) {
  7120. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7121. }
  7122. // use materials from the model file
  7123. // if there is just empty face material
  7124. // (must create new material as each model has its own face material)
  7125. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  7126. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7127. }
  7128. if ( material instanceof THREE.MeshFaceMaterial ) {
  7129. for ( var i = 0; i < material.materials.length; i ++ ) {
  7130. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  7131. }
  7132. }
  7133. if ( needsTangents ) {
  7134. geometry.computeTangents();
  7135. }
  7136. if ( objJSON.skin ) {
  7137. object = new THREE.SkinnedMesh( geometry, material );
  7138. } else if ( objJSON.morph ) {
  7139. object = new THREE.MorphAnimMesh( geometry, material );
  7140. if ( objJSON.duration !== undefined ) {
  7141. object.duration = objJSON.duration;
  7142. }
  7143. if ( objJSON.time !== undefined ) {
  7144. object.time = objJSON.time;
  7145. }
  7146. if ( objJSON.mirroredLoop !== undefined ) {
  7147. object.mirroredLoop = objJSON.mirroredLoop;
  7148. }
  7149. if ( material.morphNormals ) {
  7150. geometry.computeMorphNormals();
  7151. }
  7152. } else {
  7153. object = new THREE.Mesh( geometry, material );
  7154. }
  7155. object.name = objID;
  7156. if ( mat ) {
  7157. object.matrixAutoUpdate = false;
  7158. object.matrix.set(
  7159. mat[0], mat[1], mat[2], mat[3],
  7160. mat[4], mat[5], mat[6], mat[7],
  7161. mat[8], mat[9], mat[10], mat[11],
  7162. mat[12], mat[13], mat[14], mat[15]
  7163. );
  7164. } else {
  7165. object.position.fromArray( pos );
  7166. if ( quat ) {
  7167. object.quaternion.fromArray( quat );
  7168. } else {
  7169. object.rotation.fromArray( rot );
  7170. }
  7171. object.scale.fromArray( scl );
  7172. }
  7173. object.visible = objJSON.visible;
  7174. object.castShadow = objJSON.castShadow;
  7175. object.receiveShadow = objJSON.receiveShadow;
  7176. parent.add( object );
  7177. result.objects[ objID ] = object;
  7178. }
  7179. // lights
  7180. } else if ( objJSON.type === "AmbientLight" || objJSON.type === "PointLight" ||
  7181. objJSON.type === "DirectionalLight" || objJSON.type === "SpotLight" ||
  7182. objJSON.type === "HemisphereLight" || objJSON.type === "AreaLight" ) {
  7183. var color = objJSON.color;
  7184. var intensity = objJSON.intensity;
  7185. var distance = objJSON.distance;
  7186. var position = objJSON.position;
  7187. var rotation = objJSON.rotation;
  7188. switch ( objJSON.type ) {
  7189. case 'AmbientLight':
  7190. light = new THREE.AmbientLight( color );
  7191. break;
  7192. case 'PointLight':
  7193. light = new THREE.PointLight( color, intensity, distance );
  7194. light.position.fromArray( position );
  7195. break;
  7196. case 'DirectionalLight':
  7197. light = new THREE.DirectionalLight( color, intensity );
  7198. light.position.fromArray( objJSON.direction );
  7199. break;
  7200. case 'SpotLight':
  7201. light = new THREE.SpotLight( color, intensity, distance, 1 );
  7202. light.angle = objJSON.angle;
  7203. light.position.fromArray( position );
  7204. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  7205. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  7206. break;
  7207. case 'HemisphereLight':
  7208. light = new THREE.DirectionalLight( color, intensity, distance );
  7209. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  7210. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  7211. break;
  7212. case 'AreaLight':
  7213. light = new THREE.AreaLight(color, intensity);
  7214. light.position.fromArray( position );
  7215. light.width = objJSON.size;
  7216. light.height = objJSON.size_y;
  7217. break;
  7218. }
  7219. parent.add( light );
  7220. light.name = objID;
  7221. result.lights[ objID ] = light;
  7222. result.objects[ objID ] = light;
  7223. // cameras
  7224. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  7225. pos = objJSON.position;
  7226. rot = objJSON.rotation;
  7227. quat = objJSON.quaternion;
  7228. if ( objJSON.type === "PerspectiveCamera" ) {
  7229. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  7230. } else if ( objJSON.type === "OrthographicCamera" ) {
  7231. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  7232. }
  7233. camera.name = objID;
  7234. camera.position.fromArray( pos );
  7235. if ( quat !== undefined ) {
  7236. camera.quaternion.fromArray( quat );
  7237. } else if ( rot !== undefined ) {
  7238. camera.rotation.fromArray( rot );
  7239. }
  7240. parent.add( camera );
  7241. result.cameras[ objID ] = camera;
  7242. result.objects[ objID ] = camera;
  7243. // pure Object3D
  7244. } else {
  7245. pos = objJSON.position;
  7246. rot = objJSON.rotation;
  7247. scl = objJSON.scale;
  7248. quat = objJSON.quaternion;
  7249. object = new THREE.Object3D();
  7250. object.name = objID;
  7251. object.position.fromArray( pos );
  7252. if ( quat ) {
  7253. object.quaternion.fromArray( quat );
  7254. } else {
  7255. object.rotation.fromArray( rot );
  7256. }
  7257. object.scale.fromArray( scl );
  7258. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  7259. parent.add( object );
  7260. result.objects[ objID ] = object;
  7261. result.empties[ objID ] = object;
  7262. }
  7263. if ( object ) {
  7264. if ( objJSON.userData !== undefined ) {
  7265. for ( var key in objJSON.userData ) {
  7266. var value = objJSON.userData[ key ];
  7267. object.userData[ key ] = value;
  7268. }
  7269. }
  7270. if ( objJSON.groups !== undefined ) {
  7271. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  7272. var groupID = objJSON.groups[ i ];
  7273. if ( result.groups[ groupID ] === undefined ) {
  7274. result.groups[ groupID ] = [];
  7275. }
  7276. result.groups[ groupID ].push( objID );
  7277. }
  7278. }
  7279. }
  7280. }
  7281. if ( object !== undefined && objJSON.children !== undefined ) {
  7282. handle_children( object, objJSON.children );
  7283. }
  7284. }
  7285. };
  7286. function handle_mesh( geo, mat, id ) {
  7287. result.geometries[ id ] = geo;
  7288. result.face_materials[ id ] = mat;
  7289. handle_objects();
  7290. };
  7291. function handle_hierarchy( node, id, parent, material, obj ) {
  7292. var p = obj.position;
  7293. var r = obj.rotation;
  7294. var q = obj.quaternion;
  7295. var s = obj.scale;
  7296. node.position.fromArray( p );
  7297. if ( q ) {
  7298. node.quaternion.fromArray( q );
  7299. } else {
  7300. node.rotation.fromArray( r );
  7301. }
  7302. node.scale.fromArray( s );
  7303. // override children materials
  7304. // if object material was specified in JSON explicitly
  7305. if ( material ) {
  7306. node.traverse( function ( child ) {
  7307. child.material = material;
  7308. } );
  7309. }
  7310. // override children visibility
  7311. // with root node visibility as specified in JSON
  7312. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  7313. node.traverse( function ( child ) {
  7314. child.visible = visible;
  7315. } );
  7316. parent.add( node );
  7317. node.name = id;
  7318. result.objects[ id ] = node;
  7319. handle_objects();
  7320. };
  7321. function create_callback_geometry( id ) {
  7322. return function ( geo, mat ) {
  7323. geo.name = id;
  7324. handle_mesh( geo, mat, id );
  7325. counter_models -= 1;
  7326. scope.onLoadComplete();
  7327. async_callback_gate();
  7328. }
  7329. };
  7330. function create_callback_hierachy( id, parent, material, obj ) {
  7331. return function ( event ) {
  7332. var result;
  7333. // loaders which use EventDispatcher
  7334. if ( event.content ) {
  7335. result = event.content;
  7336. // ColladaLoader
  7337. } else if ( event.dae ) {
  7338. result = event.scene;
  7339. // UTF8Loader
  7340. } else {
  7341. result = event;
  7342. }
  7343. handle_hierarchy( result, id, parent, material, obj );
  7344. counter_models -= 1;
  7345. scope.onLoadComplete();
  7346. async_callback_gate();
  7347. }
  7348. };
  7349. function create_callback_embed( id ) {
  7350. return function ( geo, mat ) {
  7351. geo.name = id;
  7352. result.geometries[ id ] = geo;
  7353. result.face_materials[ id ] = mat;
  7354. }
  7355. };
  7356. function async_callback_gate() {
  7357. var progress = {
  7358. totalModels : total_models,
  7359. totalTextures : total_textures,
  7360. loadedModels : total_models - counter_models,
  7361. loadedTextures : total_textures - counter_textures
  7362. };
  7363. scope.callbackProgress( progress, result );
  7364. scope.onLoadProgress();
  7365. if ( counter_models === 0 && counter_textures === 0 ) {
  7366. finalize();
  7367. callbackFinished( result );
  7368. }
  7369. };
  7370. function finalize() {
  7371. // take care of targets which could be asynchronously loaded objects
  7372. for ( var i = 0; i < target_array.length; i ++ ) {
  7373. var ta = target_array[ i ];
  7374. var target = result.objects[ ta.targetName ];
  7375. if ( target ) {
  7376. ta.object.target = target;
  7377. } else {
  7378. // if there was error and target of specified name doesn't exist in the scene file
  7379. // create instead dummy target
  7380. // (target must be added to scene explicitly as parent is already added)
  7381. ta.object.target = new THREE.Object3D();
  7382. result.scene.add( ta.object.target );
  7383. }
  7384. ta.object.target.userData.targetInverse = ta.object;
  7385. }
  7386. };
  7387. var callbackTexture = function ( count ) {
  7388. counter_textures -= count;
  7389. async_callback_gate();
  7390. scope.onLoadComplete();
  7391. };
  7392. // must use this instead of just directly calling callbackTexture
  7393. // because of closure in the calling context loop
  7394. var generateTextureCallback = function ( count ) {
  7395. return function () {
  7396. callbackTexture( count );
  7397. };
  7398. };
  7399. function traverse_json_hierarchy( objJSON, callback ) {
  7400. callback( objJSON );
  7401. if ( objJSON.children !== undefined ) {
  7402. for ( var objChildID in objJSON.children ) {
  7403. traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
  7404. }
  7405. }
  7406. };
  7407. // first go synchronous elements
  7408. // fogs
  7409. var fogID, fogJSON;
  7410. for ( fogID in data.fogs ) {
  7411. fogJSON = data.fogs[ fogID ];
  7412. if ( fogJSON.type === "linear" ) {
  7413. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  7414. } else if ( fogJSON.type === "exp2" ) {
  7415. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  7416. }
  7417. color = fogJSON.color;
  7418. fog.color.setRGB( color[0], color[1], color[2] );
  7419. result.fogs[ fogID ] = fog;
  7420. }
  7421. // now come potentially asynchronous elements
  7422. // geometries
  7423. // count how many geometries will be loaded asynchronously
  7424. var geoID, geoJSON;
  7425. for ( geoID in data.geometries ) {
  7426. geoJSON = data.geometries[ geoID ];
  7427. if ( geoJSON.type in this.geometryHandlers ) {
  7428. counter_models += 1;
  7429. scope.onLoadStart();
  7430. }
  7431. }
  7432. // count how many hierarchies will be loaded asynchronously
  7433. for ( var objID in data.objects ) {
  7434. traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
  7435. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7436. counter_models += 1;
  7437. scope.onLoadStart();
  7438. }
  7439. });
  7440. }
  7441. total_models = counter_models;
  7442. for ( geoID in data.geometries ) {
  7443. geoJSON = data.geometries[ geoID ];
  7444. if ( geoJSON.type === "cube" ) {
  7445. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  7446. geometry.name = geoID;
  7447. result.geometries[ geoID ] = geometry;
  7448. } else if ( geoJSON.type === "plane" ) {
  7449. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  7450. geometry.name = geoID;
  7451. result.geometries[ geoID ] = geometry;
  7452. } else if ( geoJSON.type === "sphere" ) {
  7453. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  7454. geometry.name = geoID;
  7455. result.geometries[ geoID ] = geometry;
  7456. } else if ( geoJSON.type === "cylinder" ) {
  7457. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  7458. geometry.name = geoID;
  7459. result.geometries[ geoID ] = geometry;
  7460. } else if ( geoJSON.type === "torus" ) {
  7461. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  7462. geometry.name = geoID;
  7463. result.geometries[ geoID ] = geometry;
  7464. } else if ( geoJSON.type === "icosahedron" ) {
  7465. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  7466. geometry.name = geoID;
  7467. result.geometries[ geoID ] = geometry;
  7468. } else if ( geoJSON.type in this.geometryHandlers ) {
  7469. var loaderParameters = {};
  7470. for ( var parType in geoJSON ) {
  7471. if ( parType !== "type" && parType !== "url" ) {
  7472. loaderParameters[ parType ] = geoJSON[ parType ];
  7473. }
  7474. }
  7475. var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ];
  7476. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  7477. } else if ( geoJSON.type === "embedded" ) {
  7478. var modelJson = data.embeds[ geoJSON.id ],
  7479. texture_path = "";
  7480. // pass metadata along to jsonLoader so it knows the format version
  7481. modelJson.metadata = data.metadata;
  7482. if ( modelJson ) {
  7483. var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ];
  7484. var model = jsonLoader.parse( modelJson, texture_path );
  7485. create_callback_embed( geoID )( model.geometry, model.materials );
  7486. }
  7487. }
  7488. }
  7489. // textures
  7490. // count how many textures will be loaded asynchronously
  7491. var textureID, textureJSON;
  7492. for ( textureID in data.textures ) {
  7493. textureJSON = data.textures[ textureID ];
  7494. if ( textureJSON.url instanceof Array ) {
  7495. counter_textures += textureJSON.url.length;
  7496. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  7497. scope.onLoadStart();
  7498. }
  7499. } else {
  7500. counter_textures += 1;
  7501. scope.onLoadStart();
  7502. }
  7503. }
  7504. total_textures = counter_textures;
  7505. for ( textureID in data.textures ) {
  7506. textureJSON = data.textures[ textureID ];
  7507. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  7508. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  7509. }
  7510. if ( textureJSON.url instanceof Array ) {
  7511. var count = textureJSON.url.length;
  7512. var url_array = [];
  7513. for( var i = 0; i < count; i ++ ) {
  7514. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  7515. }
  7516. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  7517. if ( isCompressed ) {
  7518. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7519. } else {
  7520. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7521. }
  7522. } else {
  7523. var isCompressed = /\.dds$/i.test( textureJSON.url );
  7524. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  7525. var textureCallback = generateTextureCallback( 1 );
  7526. if ( isCompressed ) {
  7527. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  7528. } else {
  7529. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  7530. }
  7531. if ( THREE[ textureJSON.minFilter ] !== undefined )
  7532. texture.minFilter = THREE[ textureJSON.minFilter ];
  7533. if ( THREE[ textureJSON.magFilter ] !== undefined )
  7534. texture.magFilter = THREE[ textureJSON.magFilter ];
  7535. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  7536. if ( textureJSON.repeat ) {
  7537. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  7538. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  7539. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  7540. }
  7541. if ( textureJSON.offset ) {
  7542. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  7543. }
  7544. // handle wrap after repeat so that default repeat can be overriden
  7545. if ( textureJSON.wrap ) {
  7546. var wrapMap = {
  7547. "repeat": THREE.RepeatWrapping,
  7548. "mirror": THREE.MirroredRepeatWrapping
  7549. }
  7550. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  7551. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  7552. }
  7553. }
  7554. result.textures[ textureID ] = texture;
  7555. }
  7556. // materials
  7557. var matID, matJSON;
  7558. var parID;
  7559. for ( matID in data.materials ) {
  7560. matJSON = data.materials[ matID ];
  7561. for ( parID in matJSON.parameters ) {
  7562. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  7563. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  7564. } else if ( parID === "shading" ) {
  7565. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  7566. } else if ( parID === "side" ) {
  7567. if ( matJSON.parameters[ parID ] == "double" ) {
  7568. matJSON.parameters[ parID ] = THREE.DoubleSide;
  7569. } else if ( matJSON.parameters[ parID ] == "back" ) {
  7570. matJSON.parameters[ parID ] = THREE.BackSide;
  7571. } else {
  7572. matJSON.parameters[ parID ] = THREE.FrontSide;
  7573. }
  7574. } else if ( parID === "blending" ) {
  7575. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  7576. } else if ( parID === "combine" ) {
  7577. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  7578. } else if ( parID === "vertexColors" ) {
  7579. if ( matJSON.parameters[ parID ] == "face" ) {
  7580. matJSON.parameters[ parID ] = THREE.FaceColors;
  7581. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  7582. } else if ( matJSON.parameters[ parID ] ) {
  7583. matJSON.parameters[ parID ] = THREE.VertexColors;
  7584. }
  7585. } else if ( parID === "wrapRGB" ) {
  7586. var v3 = matJSON.parameters[ parID ];
  7587. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  7588. }
  7589. }
  7590. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  7591. matJSON.parameters.transparent = true;
  7592. }
  7593. if ( matJSON.parameters.normalMap ) {
  7594. var shader = THREE.ShaderLib[ "normalmap" ];
  7595. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  7596. var diffuse = matJSON.parameters.color;
  7597. var specular = matJSON.parameters.specular;
  7598. var ambient = matJSON.parameters.ambient;
  7599. var shininess = matJSON.parameters.shininess;
  7600. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  7601. if ( matJSON.parameters.normalScale ) {
  7602. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  7603. }
  7604. if ( matJSON.parameters.map ) {
  7605. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  7606. uniforms[ "enableDiffuse" ].value = true;
  7607. }
  7608. if ( matJSON.parameters.envMap ) {
  7609. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  7610. uniforms[ "enableReflection" ].value = true;
  7611. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  7612. }
  7613. if ( matJSON.parameters.lightMap ) {
  7614. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  7615. uniforms[ "enableAO" ].value = true;
  7616. }
  7617. if ( matJSON.parameters.specularMap ) {
  7618. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  7619. uniforms[ "enableSpecular" ].value = true;
  7620. }
  7621. if ( matJSON.parameters.displacementMap ) {
  7622. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  7623. uniforms[ "enableDisplacement" ].value = true;
  7624. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  7625. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  7626. }
  7627. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  7628. uniforms[ "uSpecularColor" ].value.setHex( specular );
  7629. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  7630. uniforms[ "uShininess" ].value = shininess;
  7631. if ( matJSON.parameters.opacity ) {
  7632. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  7633. }
  7634. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  7635. material = new THREE.ShaderMaterial( parameters );
  7636. } else {
  7637. material = new THREE[ matJSON.type ]( matJSON.parameters );
  7638. }
  7639. material.name = matID;
  7640. result.materials[ matID ] = material;
  7641. }
  7642. // second pass through all materials to initialize MeshFaceMaterials
  7643. // that could be referring to other materials out of order
  7644. for ( matID in data.materials ) {
  7645. matJSON = data.materials[ matID ];
  7646. if ( matJSON.parameters.materials ) {
  7647. var materialArray = [];
  7648. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  7649. var label = matJSON.parameters.materials[ i ];
  7650. materialArray.push( result.materials[ label ] );
  7651. }
  7652. result.materials[ matID ].materials = materialArray;
  7653. }
  7654. }
  7655. // objects ( synchronous init of procedural primitives )
  7656. handle_objects();
  7657. // defaults
  7658. if ( result.cameras && data.defaults.camera ) {
  7659. result.currentCamera = result.cameras[ data.defaults.camera ];
  7660. }
  7661. if ( result.fogs && data.defaults.fog ) {
  7662. result.scene.fog = result.fogs[ data.defaults.fog ];
  7663. }
  7664. // synchronous callback
  7665. scope.callbackSync( result );
  7666. // just in case there are no async elements
  7667. async_callback_gate();
  7668. }
  7669. }
  7670. /**
  7671. * @author mrdoob / http://mrdoob.com/
  7672. */
  7673. THREE.TextureLoader = function ( manager ) {
  7674. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7675. };
  7676. THREE.TextureLoader.prototype = {
  7677. constructor: THREE.TextureLoader,
  7678. load: function ( url, onLoad, onProgress, onError ) {
  7679. var scope = this;
  7680. var loader = new THREE.ImageLoader( scope.manager );
  7681. loader.setCrossOrigin( this.crossOrigin );
  7682. loader.load( url, function ( image ) {
  7683. var texture = new THREE.Texture( image );
  7684. texture.needsUpdate = true;
  7685. if ( onLoad !== undefined ) {
  7686. onLoad( texture );
  7687. }
  7688. } );
  7689. },
  7690. setCrossOrigin: function ( value ) {
  7691. this.crossOrigin = value;
  7692. }
  7693. };
  7694. /**
  7695. * @author mrdoob / http://mrdoob.com/
  7696. * @author alteredq / http://alteredqualia.com/
  7697. */
  7698. THREE.Material = function () {
  7699. this.id = THREE.MaterialIdCount ++;
  7700. this.uuid = THREE.Math.generateUUID();
  7701. this.name = '';
  7702. this.side = THREE.FrontSide;
  7703. this.opacity = 1;
  7704. this.transparent = false;
  7705. this.blending = THREE.NormalBlending;
  7706. this.blendSrc = THREE.SrcAlphaFactor;
  7707. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  7708. this.blendEquation = THREE.AddEquation;
  7709. this.depthTest = true;
  7710. this.depthWrite = true;
  7711. this.polygonOffset = false;
  7712. this.polygonOffsetFactor = 0;
  7713. this.polygonOffsetUnits = 0;
  7714. this.alphaTest = 0;
  7715. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  7716. this.visible = true;
  7717. this.needsUpdate = true;
  7718. };
  7719. THREE.Material.prototype = {
  7720. constructor: THREE.Material,
  7721. setValues: function ( values ) {
  7722. if ( values === undefined ) return;
  7723. for ( var key in values ) {
  7724. var newValue = values[ key ];
  7725. if ( newValue === undefined ) {
  7726. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  7727. continue;
  7728. }
  7729. if ( key in this ) {
  7730. var currentValue = this[ key ];
  7731. if ( currentValue instanceof THREE.Color ) {
  7732. currentValue.set( newValue );
  7733. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  7734. currentValue.copy( newValue );
  7735. } else if ( key == 'overdraw') {
  7736. // ensure overdraw is backwards-compatable with legacy boolean type
  7737. this[ key ] = Number(newValue);
  7738. } else {
  7739. this[ key ] = newValue;
  7740. }
  7741. }
  7742. }
  7743. },
  7744. clone: function ( material ) {
  7745. if ( material === undefined ) material = new THREE.Material();
  7746. material.name = this.name;
  7747. material.side = this.side;
  7748. material.opacity = this.opacity;
  7749. material.transparent = this.transparent;
  7750. material.blending = this.blending;
  7751. material.blendSrc = this.blendSrc;
  7752. material.blendDst = this.blendDst;
  7753. material.blendEquation = this.blendEquation;
  7754. material.depthTest = this.depthTest;
  7755. material.depthWrite = this.depthWrite;
  7756. material.polygonOffset = this.polygonOffset;
  7757. material.polygonOffsetFactor = this.polygonOffsetFactor;
  7758. material.polygonOffsetUnits = this.polygonOffsetUnits;
  7759. material.alphaTest = this.alphaTest;
  7760. material.overdraw = this.overdraw;
  7761. material.visible = this.visible;
  7762. return material;
  7763. },
  7764. dispose: function () {
  7765. this.dispatchEvent( { type: 'dispose' } );
  7766. }
  7767. };
  7768. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  7769. THREE.MaterialIdCount = 0;
  7770. /**
  7771. * @author mrdoob / http://mrdoob.com/
  7772. * @author alteredq / http://alteredqualia.com/
  7773. *
  7774. * parameters = {
  7775. * color: <hex>,
  7776. * opacity: <float>,
  7777. *
  7778. * blending: THREE.NormalBlending,
  7779. * depthTest: <bool>,
  7780. * depthWrite: <bool>,
  7781. *
  7782. * linewidth: <float>,
  7783. * linecap: "round",
  7784. * linejoin: "round",
  7785. *
  7786. * vertexColors: <bool>
  7787. *
  7788. * fog: <bool>
  7789. * }
  7790. */
  7791. THREE.LineBasicMaterial = function ( parameters ) {
  7792. THREE.Material.call( this );
  7793. this.color = new THREE.Color( 0xffffff );
  7794. this.linewidth = 1;
  7795. this.linecap = 'round';
  7796. this.linejoin = 'round';
  7797. this.vertexColors = false;
  7798. this.fog = true;
  7799. this.setValues( parameters );
  7800. };
  7801. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7802. THREE.LineBasicMaterial.prototype.clone = function () {
  7803. var material = new THREE.LineBasicMaterial();
  7804. THREE.Material.prototype.clone.call( this, material );
  7805. material.color.copy( this.color );
  7806. material.linewidth = this.linewidth;
  7807. material.linecap = this.linecap;
  7808. material.linejoin = this.linejoin;
  7809. material.vertexColors = this.vertexColors;
  7810. material.fog = this.fog;
  7811. return material;
  7812. };
  7813. /**
  7814. * @author alteredq / http://alteredqualia.com/
  7815. *
  7816. * parameters = {
  7817. * color: <hex>,
  7818. * opacity: <float>,
  7819. *
  7820. * blending: THREE.NormalBlending,
  7821. * depthTest: <bool>,
  7822. * depthWrite: <bool>,
  7823. *
  7824. * linewidth: <float>,
  7825. *
  7826. * scale: <float>,
  7827. * dashSize: <float>,
  7828. * gapSize: <float>,
  7829. *
  7830. * vertexColors: <bool>
  7831. *
  7832. * fog: <bool>
  7833. * }
  7834. */
  7835. THREE.LineDashedMaterial = function ( parameters ) {
  7836. THREE.Material.call( this );
  7837. this.color = new THREE.Color( 0xffffff );
  7838. this.linewidth = 1;
  7839. this.scale = 1;
  7840. this.dashSize = 3;
  7841. this.gapSize = 1;
  7842. this.vertexColors = false;
  7843. this.fog = true;
  7844. this.setValues( parameters );
  7845. };
  7846. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  7847. THREE.LineDashedMaterial.prototype.clone = function () {
  7848. var material = new THREE.LineDashedMaterial();
  7849. THREE.Material.prototype.clone.call( this, material );
  7850. material.color.copy( this.color );
  7851. material.linewidth = this.linewidth;
  7852. material.scale = this.scale;
  7853. material.dashSize = this.dashSize;
  7854. material.gapSize = this.gapSize;
  7855. material.vertexColors = this.vertexColors;
  7856. material.fog = this.fog;
  7857. return material;
  7858. };
  7859. /**
  7860. * @author mrdoob / http://mrdoob.com/
  7861. * @author alteredq / http://alteredqualia.com/
  7862. *
  7863. * parameters = {
  7864. * color: <hex>,
  7865. * opacity: <float>,
  7866. * map: new THREE.Texture( <Image> ),
  7867. *
  7868. * lightMap: new THREE.Texture( <Image> ),
  7869. *
  7870. * specularMap: new THREE.Texture( <Image> ),
  7871. *
  7872. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7873. * combine: THREE.Multiply,
  7874. * reflectivity: <float>,
  7875. * refractionRatio: <float>,
  7876. *
  7877. * shading: THREE.SmoothShading,
  7878. * blending: THREE.NormalBlending,
  7879. * depthTest: <bool>,
  7880. * depthWrite: <bool>,
  7881. *
  7882. * wireframe: <boolean>,
  7883. * wireframeLinewidth: <float>,
  7884. *
  7885. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7886. *
  7887. * skinning: <bool>,
  7888. * morphTargets: <bool>,
  7889. *
  7890. * fog: <bool>
  7891. * }
  7892. */
  7893. THREE.MeshBasicMaterial = function ( parameters ) {
  7894. THREE.Material.call( this );
  7895. this.color = new THREE.Color( 0xffffff ); // emissive
  7896. this.map = null;
  7897. this.lightMap = null;
  7898. this.specularMap = null;
  7899. this.envMap = null;
  7900. this.combine = THREE.MultiplyOperation;
  7901. this.reflectivity = 1;
  7902. this.refractionRatio = 0.98;
  7903. this.fog = true;
  7904. this.shading = THREE.SmoothShading;
  7905. this.wireframe = false;
  7906. this.wireframeLinewidth = 1;
  7907. this.wireframeLinecap = 'round';
  7908. this.wireframeLinejoin = 'round';
  7909. this.vertexColors = THREE.NoColors;
  7910. this.skinning = false;
  7911. this.morphTargets = false;
  7912. this.setValues( parameters );
  7913. };
  7914. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7915. THREE.MeshBasicMaterial.prototype.clone = function () {
  7916. var material = new THREE.MeshBasicMaterial();
  7917. THREE.Material.prototype.clone.call( this, material );
  7918. material.color.copy( this.color );
  7919. material.map = this.map;
  7920. material.lightMap = this.lightMap;
  7921. material.specularMap = this.specularMap;
  7922. material.envMap = this.envMap;
  7923. material.combine = this.combine;
  7924. material.reflectivity = this.reflectivity;
  7925. material.refractionRatio = this.refractionRatio;
  7926. material.fog = this.fog;
  7927. material.shading = this.shading;
  7928. material.wireframe = this.wireframe;
  7929. material.wireframeLinewidth = this.wireframeLinewidth;
  7930. material.wireframeLinecap = this.wireframeLinecap;
  7931. material.wireframeLinejoin = this.wireframeLinejoin;
  7932. material.vertexColors = this.vertexColors;
  7933. material.skinning = this.skinning;
  7934. material.morphTargets = this.morphTargets;
  7935. return material;
  7936. };
  7937. /**
  7938. * @author mrdoob / http://mrdoob.com/
  7939. * @author alteredq / http://alteredqualia.com/
  7940. *
  7941. * parameters = {
  7942. * color: <hex>,
  7943. * ambient: <hex>,
  7944. * emissive: <hex>,
  7945. * opacity: <float>,
  7946. *
  7947. * map: new THREE.Texture( <Image> ),
  7948. *
  7949. * lightMap: new THREE.Texture( <Image> ),
  7950. *
  7951. * specularMap: new THREE.Texture( <Image> ),
  7952. *
  7953. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7954. * combine: THREE.Multiply,
  7955. * reflectivity: <float>,
  7956. * refractionRatio: <float>,
  7957. *
  7958. * shading: THREE.SmoothShading,
  7959. * blending: THREE.NormalBlending,
  7960. * depthTest: <bool>,
  7961. * depthWrite: <bool>,
  7962. *
  7963. * wireframe: <boolean>,
  7964. * wireframeLinewidth: <float>,
  7965. *
  7966. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7967. *
  7968. * skinning: <bool>,
  7969. * morphTargets: <bool>,
  7970. * morphNormals: <bool>,
  7971. *
  7972. * fog: <bool>
  7973. * }
  7974. */
  7975. THREE.MeshLambertMaterial = function ( parameters ) {
  7976. THREE.Material.call( this );
  7977. this.color = new THREE.Color( 0xffffff ); // diffuse
  7978. this.ambient = new THREE.Color( 0xffffff );
  7979. this.emissive = new THREE.Color( 0x000000 );
  7980. this.wrapAround = false;
  7981. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7982. this.map = null;
  7983. this.lightMap = null;
  7984. this.specularMap = null;
  7985. this.envMap = null;
  7986. this.combine = THREE.MultiplyOperation;
  7987. this.reflectivity = 1;
  7988. this.refractionRatio = 0.98;
  7989. this.fog = true;
  7990. this.shading = THREE.SmoothShading;
  7991. this.wireframe = false;
  7992. this.wireframeLinewidth = 1;
  7993. this.wireframeLinecap = 'round';
  7994. this.wireframeLinejoin = 'round';
  7995. this.vertexColors = THREE.NoColors;
  7996. this.skinning = false;
  7997. this.morphTargets = false;
  7998. this.morphNormals = false;
  7999. this.setValues( parameters );
  8000. };
  8001. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  8002. THREE.MeshLambertMaterial.prototype.clone = function () {
  8003. var material = new THREE.MeshLambertMaterial();
  8004. THREE.Material.prototype.clone.call( this, material );
  8005. material.color.copy( this.color );
  8006. material.ambient.copy( this.ambient );
  8007. material.emissive.copy( this.emissive );
  8008. material.wrapAround = this.wrapAround;
  8009. material.wrapRGB.copy( this.wrapRGB );
  8010. material.map = this.map;
  8011. material.lightMap = this.lightMap;
  8012. material.specularMap = this.specularMap;
  8013. material.envMap = this.envMap;
  8014. material.combine = this.combine;
  8015. material.reflectivity = this.reflectivity;
  8016. material.refractionRatio = this.refractionRatio;
  8017. material.fog = this.fog;
  8018. material.shading = this.shading;
  8019. material.wireframe = this.wireframe;
  8020. material.wireframeLinewidth = this.wireframeLinewidth;
  8021. material.wireframeLinecap = this.wireframeLinecap;
  8022. material.wireframeLinejoin = this.wireframeLinejoin;
  8023. material.vertexColors = this.vertexColors;
  8024. material.skinning = this.skinning;
  8025. material.morphTargets = this.morphTargets;
  8026. material.morphNormals = this.morphNormals;
  8027. return material;
  8028. };
  8029. /**
  8030. * @author mrdoob / http://mrdoob.com/
  8031. * @author alteredq / http://alteredqualia.com/
  8032. *
  8033. * parameters = {
  8034. * color: <hex>,
  8035. * ambient: <hex>,
  8036. * emissive: <hex>,
  8037. * specular: <hex>,
  8038. * shininess: <float>,
  8039. * opacity: <float>,
  8040. *
  8041. * map: new THREE.Texture( <Image> ),
  8042. *
  8043. * lightMap: new THREE.Texture( <Image> ),
  8044. *
  8045. * bumpMap: new THREE.Texture( <Image> ),
  8046. * bumpScale: <float>,
  8047. *
  8048. * normalMap: new THREE.Texture( <Image> ),
  8049. * normalScale: <Vector2>,
  8050. *
  8051. * specularMap: new THREE.Texture( <Image> ),
  8052. *
  8053. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8054. * combine: THREE.Multiply,
  8055. * reflectivity: <float>,
  8056. * refractionRatio: <float>,
  8057. *
  8058. * shading: THREE.SmoothShading,
  8059. * blending: THREE.NormalBlending,
  8060. * depthTest: <bool>,
  8061. * depthWrite: <bool>,
  8062. *
  8063. * wireframe: <boolean>,
  8064. * wireframeLinewidth: <float>,
  8065. *
  8066. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8067. *
  8068. * skinning: <bool>,
  8069. * morphTargets: <bool>,
  8070. * morphNormals: <bool>,
  8071. *
  8072. * fog: <bool>
  8073. * }
  8074. */
  8075. THREE.MeshPhongMaterial = function ( parameters ) {
  8076. THREE.Material.call( this );
  8077. this.color = new THREE.Color( 0xffffff ); // diffuse
  8078. this.ambient = new THREE.Color( 0xffffff );
  8079. this.emissive = new THREE.Color( 0x000000 );
  8080. this.specular = new THREE.Color( 0x111111 );
  8081. this.shininess = 30;
  8082. this.metal = false;
  8083. this.perPixel = true;
  8084. this.wrapAround = false;
  8085. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8086. this.map = null;
  8087. this.lightMap = null;
  8088. this.bumpMap = null;
  8089. this.bumpScale = 1;
  8090. this.normalMap = null;
  8091. this.normalScale = new THREE.Vector2( 1, 1 );
  8092. this.specularMap = null;
  8093. this.envMap = null;
  8094. this.combine = THREE.MultiplyOperation;
  8095. this.reflectivity = 1;
  8096. this.refractionRatio = 0.98;
  8097. this.fog = true;
  8098. this.shading = THREE.SmoothShading;
  8099. this.wireframe = false;
  8100. this.wireframeLinewidth = 1;
  8101. this.wireframeLinecap = 'round';
  8102. this.wireframeLinejoin = 'round';
  8103. this.vertexColors = THREE.NoColors;
  8104. this.skinning = false;
  8105. this.morphTargets = false;
  8106. this.morphNormals = false;
  8107. this.setValues( parameters );
  8108. };
  8109. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8110. THREE.MeshPhongMaterial.prototype.clone = function () {
  8111. var material = new THREE.MeshPhongMaterial();
  8112. THREE.Material.prototype.clone.call( this, material );
  8113. material.color.copy( this.color );
  8114. material.ambient.copy( this.ambient );
  8115. material.emissive.copy( this.emissive );
  8116. material.specular.copy( this.specular );
  8117. material.shininess = this.shininess;
  8118. material.metal = this.metal;
  8119. material.perPixel = this.perPixel;
  8120. material.wrapAround = this.wrapAround;
  8121. material.wrapRGB.copy( this.wrapRGB );
  8122. material.map = this.map;
  8123. material.lightMap = this.lightMap;
  8124. material.bumpMap = this.bumpMap;
  8125. material.bumpScale = this.bumpScale;
  8126. material.normalMap = this.normalMap;
  8127. material.normalScale.copy( this.normalScale );
  8128. material.specularMap = this.specularMap;
  8129. material.envMap = this.envMap;
  8130. material.combine = this.combine;
  8131. material.reflectivity = this.reflectivity;
  8132. material.refractionRatio = this.refractionRatio;
  8133. material.fog = this.fog;
  8134. material.shading = this.shading;
  8135. material.wireframe = this.wireframe;
  8136. material.wireframeLinewidth = this.wireframeLinewidth;
  8137. material.wireframeLinecap = this.wireframeLinecap;
  8138. material.wireframeLinejoin = this.wireframeLinejoin;
  8139. material.vertexColors = this.vertexColors;
  8140. material.skinning = this.skinning;
  8141. material.morphTargets = this.morphTargets;
  8142. material.morphNormals = this.morphNormals;
  8143. return material;
  8144. };
  8145. /**
  8146. * @author mrdoob / http://mrdoob.com/
  8147. * @author alteredq / http://alteredqualia.com/
  8148. *
  8149. * parameters = {
  8150. * opacity: <float>,
  8151. *
  8152. * blending: THREE.NormalBlending,
  8153. * depthTest: <bool>,
  8154. * depthWrite: <bool>,
  8155. *
  8156. * wireframe: <boolean>,
  8157. * wireframeLinewidth: <float>
  8158. * }
  8159. */
  8160. THREE.MeshDepthMaterial = function ( parameters ) {
  8161. THREE.Material.call( this );
  8162. this.wireframe = false;
  8163. this.wireframeLinewidth = 1;
  8164. this.setValues( parameters );
  8165. };
  8166. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  8167. THREE.MeshDepthMaterial.prototype.clone = function () {
  8168. var material = new THREE.MeshDepthMaterial();
  8169. THREE.Material.prototype.clone.call( this, material );
  8170. material.wireframe = this.wireframe;
  8171. material.wireframeLinewidth = this.wireframeLinewidth;
  8172. return material;
  8173. };
  8174. /**
  8175. * @author mrdoob / http://mrdoob.com/
  8176. *
  8177. * parameters = {
  8178. * opacity: <float>,
  8179. *
  8180. * shading: THREE.FlatShading,
  8181. * blending: THREE.NormalBlending,
  8182. * depthTest: <bool>,
  8183. * depthWrite: <bool>,
  8184. *
  8185. * wireframe: <boolean>,
  8186. * wireframeLinewidth: <float>
  8187. * }
  8188. */
  8189. THREE.MeshNormalMaterial = function ( parameters ) {
  8190. THREE.Material.call( this, parameters );
  8191. this.shading = THREE.FlatShading;
  8192. this.wireframe = false;
  8193. this.wireframeLinewidth = 1;
  8194. this.morphTargets = false;
  8195. this.setValues( parameters );
  8196. };
  8197. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  8198. THREE.MeshNormalMaterial.prototype.clone = function () {
  8199. var material = new THREE.MeshNormalMaterial();
  8200. THREE.Material.prototype.clone.call( this, material );
  8201. material.shading = this.shading;
  8202. material.wireframe = this.wireframe;
  8203. material.wireframeLinewidth = this.wireframeLinewidth;
  8204. return material;
  8205. };
  8206. /**
  8207. * @author mrdoob / http://mrdoob.com/
  8208. */
  8209. THREE.MeshFaceMaterial = function ( materials ) {
  8210. this.materials = materials instanceof Array ? materials : [];
  8211. };
  8212. THREE.MeshFaceMaterial.prototype.clone = function () {
  8213. var material = new THREE.MeshFaceMaterial();
  8214. for ( var i = 0; i < this.materials.length; i ++ ) {
  8215. material.materials.push( this.materials[ i ].clone() );
  8216. }
  8217. return material;
  8218. };
  8219. /**
  8220. * @author mrdoob / http://mrdoob.com/
  8221. * @author alteredq / http://alteredqualia.com/
  8222. *
  8223. * parameters = {
  8224. * color: <hex>,
  8225. * opacity: <float>,
  8226. * map: new THREE.Texture( <Image> ),
  8227. *
  8228. * size: <float>,
  8229. *
  8230. * blending: THREE.NormalBlending,
  8231. * depthTest: <bool>,
  8232. * depthWrite: <bool>,
  8233. *
  8234. * vertexColors: <bool>,
  8235. *
  8236. * fog: <bool>
  8237. * }
  8238. */
  8239. THREE.ParticleSystemMaterial = function ( parameters ) {
  8240. THREE.Material.call( this );
  8241. this.color = new THREE.Color( 0xffffff );
  8242. this.map = null;
  8243. this.size = 1;
  8244. this.sizeAttenuation = true;
  8245. this.vertexColors = false;
  8246. this.fog = true;
  8247. this.setValues( parameters );
  8248. };
  8249. THREE.ParticleSystemMaterial.prototype = Object.create( THREE.Material.prototype );
  8250. THREE.ParticleSystemMaterial.prototype.clone = function () {
  8251. var material = new THREE.ParticleSystemMaterial();
  8252. THREE.Material.prototype.clone.call( this, material );
  8253. material.color.copy( this.color );
  8254. material.map = this.map;
  8255. material.size = this.size;
  8256. material.sizeAttenuation = this.sizeAttenuation;
  8257. material.vertexColors = this.vertexColors;
  8258. material.fog = this.fog;
  8259. return material;
  8260. };
  8261. // backwards compatibility
  8262. THREE.ParticleBasicMaterial = THREE.ParticleSystemMaterial;
  8263. /**
  8264. * @author alteredq / http://alteredqualia.com/
  8265. *
  8266. * parameters = {
  8267. * fragmentShader: <string>,
  8268. * vertexShader: <string>,
  8269. *
  8270. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  8271. *
  8272. * defines: { "label" : "value" },
  8273. *
  8274. * shading: THREE.SmoothShading,
  8275. * blending: THREE.NormalBlending,
  8276. * depthTest: <bool>,
  8277. * depthWrite: <bool>,
  8278. *
  8279. * wireframe: <boolean>,
  8280. * wireframeLinewidth: <float>,
  8281. *
  8282. * lights: <bool>,
  8283. *
  8284. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8285. *
  8286. * skinning: <bool>,
  8287. * morphTargets: <bool>,
  8288. * morphNormals: <bool>,
  8289. *
  8290. * fog: <bool>
  8291. * }
  8292. */
  8293. THREE.ShaderMaterial = function ( parameters ) {
  8294. THREE.Material.call( this );
  8295. this.fragmentShader = "void main() {}";
  8296. this.vertexShader = "void main() {}";
  8297. this.uniforms = {};
  8298. this.defines = {};
  8299. this.attributes = null;
  8300. this.shading = THREE.SmoothShading;
  8301. this.linewidth = 1;
  8302. this.wireframe = false;
  8303. this.wireframeLinewidth = 1;
  8304. this.fog = false; // set to use scene fog
  8305. this.lights = false; // set to use scene lights
  8306. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  8307. this.skinning = false; // set to use skinning attribute streams
  8308. this.morphTargets = false; // set to use morph targets
  8309. this.morphNormals = false; // set to use morph normals
  8310. // When rendered geometry doesn't include these attributes but the material does,
  8311. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8312. this.defaultAttributeValues = {
  8313. "color" : [ 1, 1, 1],
  8314. "uv" : [ 0, 0 ],
  8315. "uv2" : [ 0, 0 ]
  8316. };
  8317. // By default, bind position to attribute index 0. In WebGL, attribute 0
  8318. // should always be used to avoid potentially expensive emulation.
  8319. this.index0AttributeName = "position";
  8320. this.setValues( parameters );
  8321. };
  8322. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  8323. THREE.ShaderMaterial.prototype.clone = function () {
  8324. var material = new THREE.ShaderMaterial();
  8325. THREE.Material.prototype.clone.call( this, material );
  8326. material.fragmentShader = this.fragmentShader;
  8327. material.vertexShader = this.vertexShader;
  8328. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  8329. material.attributes = this.attributes;
  8330. material.defines = this.defines;
  8331. material.shading = this.shading;
  8332. material.wireframe = this.wireframe;
  8333. material.wireframeLinewidth = this.wireframeLinewidth;
  8334. material.fog = this.fog;
  8335. material.lights = this.lights;
  8336. material.vertexColors = this.vertexColors;
  8337. material.skinning = this.skinning;
  8338. material.morphTargets = this.morphTargets;
  8339. material.morphNormals = this.morphNormals;
  8340. return material;
  8341. };
  8342. /**
  8343. * @author alteredq / http://alteredqualia.com/
  8344. *
  8345. * parameters = {
  8346. * color: <hex>,
  8347. * opacity: <float>,
  8348. * map: new THREE.Texture( <Image> ),
  8349. *
  8350. * blending: THREE.NormalBlending,
  8351. * depthTest: <bool>,
  8352. * depthWrite: <bool>,
  8353. *
  8354. * uvOffset: new THREE.Vector2(),
  8355. * uvScale: new THREE.Vector2(),
  8356. *
  8357. * fog: <bool>
  8358. * }
  8359. */
  8360. THREE.SpriteMaterial = function ( parameters ) {
  8361. THREE.Material.call( this );
  8362. // defaults
  8363. this.color = new THREE.Color( 0xffffff );
  8364. this.map = null;
  8365. this.rotation = 0;
  8366. this.fog = false;
  8367. this.uvOffset = new THREE.Vector2( 0, 0 );
  8368. this.uvScale = new THREE.Vector2( 1, 1 );
  8369. // set parameters
  8370. this.setValues( parameters );
  8371. };
  8372. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8373. THREE.SpriteMaterial.prototype.clone = function () {
  8374. var material = new THREE.SpriteMaterial();
  8375. THREE.Material.prototype.clone.call( this, material );
  8376. material.color.copy( this.color );
  8377. material.map = this.map;
  8378. material.rotation = this.rotation;
  8379. material.uvOffset.copy( this.uvOffset );
  8380. material.uvScale.copy( this.uvScale );
  8381. material.fog = this.fog;
  8382. return material;
  8383. };
  8384. /**
  8385. * @author mrdoob / http://mrdoob.com/
  8386. *
  8387. * parameters = {
  8388. * color: <hex>,
  8389. * program: <function>,
  8390. * opacity: <float>,
  8391. * blending: THREE.NormalBlending
  8392. * }
  8393. */
  8394. THREE.SpriteCanvasMaterial = function ( parameters ) {
  8395. THREE.Material.call( this );
  8396. this.color = new THREE.Color( 0xffffff );
  8397. this.program = function ( context, color ) {};
  8398. this.setValues( parameters );
  8399. };
  8400. THREE.SpriteCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  8401. THREE.SpriteCanvasMaterial.prototype.clone = function () {
  8402. var material = new THREE.SpriteCanvasMaterial();
  8403. THREE.Material.prototype.clone.call( this, material );
  8404. material.color.copy( this.color );
  8405. material.program = this.program;
  8406. return material;
  8407. };
  8408. // backwards compatibility
  8409. THREE.ParticleCanvasMaterial = THREE.SpriteCanvasMaterial;
  8410. /**
  8411. * @author mrdoob / http://mrdoob.com/
  8412. * @author alteredq / http://alteredqualia.com/
  8413. * @author szimek / https://github.com/szimek/
  8414. */
  8415. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8416. this.id = THREE.TextureIdCount ++;
  8417. this.uuid = THREE.Math.generateUUID();
  8418. this.name = '';
  8419. this.image = image;
  8420. this.mipmaps = [];
  8421. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  8422. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8423. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8424. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8425. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8426. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8427. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8428. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8429. this.offset = new THREE.Vector2( 0, 0 );
  8430. this.repeat = new THREE.Vector2( 1, 1 );
  8431. this.generateMipmaps = true;
  8432. this.premultiplyAlpha = false;
  8433. this.flipY = true;
  8434. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8435. this.needsUpdate = false;
  8436. this.onUpdate = null;
  8437. };
  8438. THREE.Texture.prototype = {
  8439. constructor: THREE.Texture,
  8440. clone: function ( texture ) {
  8441. if ( texture === undefined ) texture = new THREE.Texture();
  8442. texture.image = this.image;
  8443. texture.mipmaps = this.mipmaps.slice(0);
  8444. texture.mapping = this.mapping;
  8445. texture.wrapS = this.wrapS;
  8446. texture.wrapT = this.wrapT;
  8447. texture.magFilter = this.magFilter;
  8448. texture.minFilter = this.minFilter;
  8449. texture.anisotropy = this.anisotropy;
  8450. texture.format = this.format;
  8451. texture.type = this.type;
  8452. texture.offset.copy( this.offset );
  8453. texture.repeat.copy( this.repeat );
  8454. texture.generateMipmaps = this.generateMipmaps;
  8455. texture.premultiplyAlpha = this.premultiplyAlpha;
  8456. texture.flipY = this.flipY;
  8457. texture.unpackAlignment = this.unpackAlignment;
  8458. return texture;
  8459. },
  8460. dispose: function () {
  8461. this.dispatchEvent( { type: 'dispose' } );
  8462. }
  8463. };
  8464. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  8465. THREE.TextureIdCount = 0;
  8466. /**
  8467. * @author alteredq / http://alteredqualia.com/
  8468. */
  8469. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8470. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8471. this.image = { width: width, height: height };
  8472. this.mipmaps = mipmaps;
  8473. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  8474. };
  8475. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8476. THREE.CompressedTexture.prototype.clone = function () {
  8477. var texture = new THREE.CompressedTexture();
  8478. THREE.Texture.prototype.clone.call( this, texture );
  8479. return texture;
  8480. };
  8481. /**
  8482. * @author alteredq / http://alteredqualia.com/
  8483. */
  8484. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8485. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8486. this.image = { data: data, width: width, height: height };
  8487. };
  8488. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8489. THREE.DataTexture.prototype.clone = function () {
  8490. var texture = new THREE.DataTexture();
  8491. THREE.Texture.prototype.clone.call( this, texture );
  8492. return texture;
  8493. };
  8494. /**
  8495. * @author alteredq / http://alteredqualia.com/
  8496. */
  8497. THREE.ParticleSystem = function ( geometry, material ) {
  8498. THREE.Object3D.call( this );
  8499. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8500. this.material = material !== undefined ? material : new THREE.ParticleSystemMaterial( { color: Math.random() * 0xffffff } );
  8501. this.sortParticles = false;
  8502. this.frustumCulled = false;
  8503. };
  8504. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  8505. THREE.ParticleSystem.prototype.clone = function ( object ) {
  8506. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  8507. object.sortParticles = this.sortParticles;
  8508. THREE.Object3D.prototype.clone.call( this, object );
  8509. return object;
  8510. };
  8511. /**
  8512. * @author mrdoob / http://mrdoob.com/
  8513. */
  8514. THREE.Line = function ( geometry, material, type ) {
  8515. THREE.Object3D.call( this );
  8516. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8517. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  8518. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  8519. };
  8520. THREE.LineStrip = 0;
  8521. THREE.LinePieces = 1;
  8522. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  8523. THREE.Line.prototype.clone = function ( object ) {
  8524. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  8525. THREE.Object3D.prototype.clone.call( this, object );
  8526. return object;
  8527. };
  8528. /**
  8529. * @author mrdoob / http://mrdoob.com/
  8530. * @author alteredq / http://alteredqualia.com/
  8531. * @author mikael emtinger / http://gomo.se/
  8532. * @author jonobr1 / http://jonobr1.com/
  8533. */
  8534. THREE.Mesh = function ( geometry, material ) {
  8535. THREE.Object3D.call( this );
  8536. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8537. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  8538. this.updateMorphTargets();
  8539. };
  8540. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  8541. THREE.Mesh.prototype.updateMorphTargets = function () {
  8542. if ( this.geometry.morphTargets.length > 0 ) {
  8543. this.morphTargetBase = -1;
  8544. this.morphTargetForcedOrder = [];
  8545. this.morphTargetInfluences = [];
  8546. this.morphTargetDictionary = {};
  8547. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  8548. this.morphTargetInfluences.push( 0 );
  8549. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  8550. }
  8551. }
  8552. };
  8553. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  8554. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  8555. return this.morphTargetDictionary[ name ];
  8556. }
  8557. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  8558. return 0;
  8559. };
  8560. THREE.Mesh.prototype.clone = function ( object ) {
  8561. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  8562. THREE.Object3D.prototype.clone.call( this, object );
  8563. return object;
  8564. };
  8565. /**
  8566. * @author mikael emtinger / http://gomo.se/
  8567. * @author alteredq / http://alteredqualia.com/
  8568. */
  8569. THREE.Bone = function( belongsToSkin ) {
  8570. THREE.Object3D.call( this );
  8571. this.skin = belongsToSkin;
  8572. this.skinMatrix = new THREE.Matrix4();
  8573. };
  8574. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  8575. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  8576. // update local
  8577. if ( this.matrixAutoUpdate ) {
  8578. forceUpdate |= this.updateMatrix();
  8579. }
  8580. // update skin matrix
  8581. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  8582. if( parentSkinMatrix ) {
  8583. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  8584. } else {
  8585. this.skinMatrix.copy( this.matrix );
  8586. }
  8587. this.matrixWorldNeedsUpdate = false;
  8588. forceUpdate = true;
  8589. }
  8590. // update children
  8591. var child, i, l = this.children.length;
  8592. for ( i = 0; i < l; i ++ ) {
  8593. this.children[ i ].update( this.skinMatrix, forceUpdate );
  8594. }
  8595. };
  8596. /**
  8597. * @author mikael emtinger / http://gomo.se/
  8598. * @author alteredq / http://alteredqualia.com/
  8599. */
  8600. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  8601. THREE.Mesh.call( this, geometry, material );
  8602. //
  8603. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  8604. // init bones
  8605. this.identityMatrix = new THREE.Matrix4();
  8606. this.bones = [];
  8607. this.boneMatrices = [];
  8608. var b, bone, gbone, p, q, s;
  8609. if ( this.geometry && this.geometry.bones !== undefined ) {
  8610. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  8611. gbone = this.geometry.bones[ b ];
  8612. p = gbone.pos;
  8613. q = gbone.rotq;
  8614. s = gbone.scl;
  8615. bone = this.addBone();
  8616. bone.name = gbone.name;
  8617. bone.position.set( p[0], p[1], p[2] );
  8618. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  8619. if ( s !== undefined ) {
  8620. bone.scale.set( s[0], s[1], s[2] );
  8621. } else {
  8622. bone.scale.set( 1, 1, 1 );
  8623. }
  8624. }
  8625. for ( b = 0; b < this.bones.length; b ++ ) {
  8626. gbone = this.geometry.bones[ b ];
  8627. bone = this.bones[ b ];
  8628. if ( gbone.parent === -1 ) {
  8629. this.add( bone );
  8630. } else {
  8631. this.bones[ gbone.parent ].add( bone );
  8632. }
  8633. }
  8634. //
  8635. var nBones = this.bones.length;
  8636. if ( this.useVertexTexture ) {
  8637. // layout (1 matrix = 4 pixels)
  8638. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8639. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  8640. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  8641. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  8642. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  8643. var size;
  8644. if ( nBones > 256 )
  8645. size = 64;
  8646. else if ( nBones > 64 )
  8647. size = 32;
  8648. else if ( nBones > 16 )
  8649. size = 16;
  8650. else
  8651. size = 8;
  8652. this.boneTextureWidth = size;
  8653. this.boneTextureHeight = size;
  8654. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  8655. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  8656. this.boneTexture.minFilter = THREE.NearestFilter;
  8657. this.boneTexture.magFilter = THREE.NearestFilter;
  8658. this.boneTexture.generateMipmaps = false;
  8659. this.boneTexture.flipY = false;
  8660. } else {
  8661. this.boneMatrices = new Float32Array( 16 * nBones );
  8662. }
  8663. this.pose();
  8664. }
  8665. };
  8666. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  8667. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  8668. if ( bone === undefined ) {
  8669. bone = new THREE.Bone( this );
  8670. }
  8671. this.bones.push( bone );
  8672. return bone;
  8673. };
  8674. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  8675. var offsetMatrix = new THREE.Matrix4();
  8676. return function ( force ) {
  8677. this.matrixAutoUpdate && this.updateMatrix();
  8678. // update matrixWorld
  8679. if ( this.matrixWorldNeedsUpdate || force ) {
  8680. if ( this.parent ) {
  8681. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8682. } else {
  8683. this.matrixWorld.copy( this.matrix );
  8684. }
  8685. this.matrixWorldNeedsUpdate = false;
  8686. force = true;
  8687. }
  8688. // update children
  8689. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8690. var child = this.children[ i ];
  8691. if ( child instanceof THREE.Bone ) {
  8692. child.update( this.identityMatrix, false );
  8693. } else {
  8694. child.updateMatrixWorld( true );
  8695. }
  8696. }
  8697. // make a snapshot of the bones' rest position
  8698. if ( this.boneInverses == undefined ) {
  8699. this.boneInverses = [];
  8700. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8701. var inverse = new THREE.Matrix4();
  8702. inverse.getInverse( this.bones[ b ].skinMatrix );
  8703. this.boneInverses.push( inverse );
  8704. }
  8705. }
  8706. // flatten bone matrices to array
  8707. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8708. // compute the offset between the current and the original transform;
  8709. // TODO: we could get rid of this multiplication step if the skinMatrix
  8710. // was already representing the offset; however, this requires some
  8711. // major changes to the animation system
  8712. offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  8713. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  8714. }
  8715. if ( this.useVertexTexture ) {
  8716. this.boneTexture.needsUpdate = true;
  8717. }
  8718. };
  8719. }();
  8720. THREE.SkinnedMesh.prototype.pose = function () {
  8721. this.updateMatrixWorld( true );
  8722. this.normalizeSkinWeights();
  8723. };
  8724. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  8725. if ( this.geometry instanceof THREE.Geometry ) {
  8726. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  8727. var sw = this.geometry.skinWeights[ i ];
  8728. var scale = 1.0 / sw.lengthManhattan();
  8729. if ( scale !== Infinity ) {
  8730. sw.multiplyScalar( scale );
  8731. } else {
  8732. sw.set( 1 ); // this will be normalized by the shader anyway
  8733. }
  8734. }
  8735. } else {
  8736. // skinning weights assumed to be normalized for THREE.BufferGeometry
  8737. }
  8738. };
  8739. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  8740. if ( object === undefined ) {
  8741. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  8742. }
  8743. THREE.Mesh.prototype.clone.call( this, object );
  8744. return object;
  8745. };
  8746. /**
  8747. * @author alteredq / http://alteredqualia.com/
  8748. */
  8749. THREE.MorphAnimMesh = function ( geometry, material ) {
  8750. THREE.Mesh.call( this, geometry, material );
  8751. // API
  8752. this.duration = 1000; // milliseconds
  8753. this.mirroredLoop = false;
  8754. this.time = 0;
  8755. // internals
  8756. this.lastKeyframe = 0;
  8757. this.currentKeyframe = 0;
  8758. this.direction = 1;
  8759. this.directionBackwards = false;
  8760. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  8761. };
  8762. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  8763. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  8764. this.startKeyframe = start;
  8765. this.endKeyframe = end;
  8766. this.length = this.endKeyframe - this.startKeyframe + 1;
  8767. };
  8768. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  8769. this.direction = 1;
  8770. this.directionBackwards = false;
  8771. };
  8772. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  8773. this.direction = -1;
  8774. this.directionBackwards = true;
  8775. };
  8776. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  8777. var geometry = this.geometry;
  8778. if ( ! geometry.animations ) geometry.animations = {};
  8779. var firstAnimation, animations = geometry.animations;
  8780. var pattern = /([a-z]+)(\d+)/;
  8781. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  8782. var morph = geometry.morphTargets[ i ];
  8783. var parts = morph.name.match( pattern );
  8784. if ( parts && parts.length > 1 ) {
  8785. var label = parts[ 1 ];
  8786. var num = parts[ 2 ];
  8787. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  8788. var animation = animations[ label ];
  8789. if ( i < animation.start ) animation.start = i;
  8790. if ( i > animation.end ) animation.end = i;
  8791. if ( ! firstAnimation ) firstAnimation = label;
  8792. }
  8793. }
  8794. geometry.firstAnimation = firstAnimation;
  8795. };
  8796. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  8797. if ( ! this.geometry.animations ) this.geometry.animations = {};
  8798. this.geometry.animations[ label ] = { start: start, end: end };
  8799. };
  8800. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  8801. var animation = this.geometry.animations[ label ];
  8802. if ( animation ) {
  8803. this.setFrameRange( animation.start, animation.end );
  8804. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  8805. this.time = 0;
  8806. } else {
  8807. console.warn( "animation[" + label + "] undefined" );
  8808. }
  8809. };
  8810. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  8811. var frameTime = this.duration / this.length;
  8812. this.time += this.direction * delta;
  8813. if ( this.mirroredLoop ) {
  8814. if ( this.time > this.duration || this.time < 0 ) {
  8815. this.direction *= -1;
  8816. if ( this.time > this.duration ) {
  8817. this.time = this.duration;
  8818. this.directionBackwards = true;
  8819. }
  8820. if ( this.time < 0 ) {
  8821. this.time = 0;
  8822. this.directionBackwards = false;
  8823. }
  8824. }
  8825. } else {
  8826. this.time = this.time % this.duration;
  8827. if ( this.time < 0 ) this.time += this.duration;
  8828. }
  8829. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  8830. if ( keyframe !== this.currentKeyframe ) {
  8831. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  8832. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  8833. this.morphTargetInfluences[ keyframe ] = 0;
  8834. this.lastKeyframe = this.currentKeyframe;
  8835. this.currentKeyframe = keyframe;
  8836. }
  8837. var mix = ( this.time % frameTime ) / frameTime;
  8838. if ( this.directionBackwards ) {
  8839. mix = 1 - mix;
  8840. }
  8841. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  8842. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  8843. };
  8844. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  8845. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  8846. object.duration = this.duration;
  8847. object.mirroredLoop = this.mirroredLoop;
  8848. object.time = this.time;
  8849. object.lastKeyframe = this.lastKeyframe;
  8850. object.currentKeyframe = this.currentKeyframe;
  8851. object.direction = this.direction;
  8852. object.directionBackwards = this.directionBackwards;
  8853. THREE.Mesh.prototype.clone.call( this, object );
  8854. return object;
  8855. };
  8856. /**
  8857. * @author mikael emtinger / http://gomo.se/
  8858. * @author alteredq / http://alteredqualia.com/
  8859. * @author mrdoob / http://mrdoob.com/
  8860. */
  8861. THREE.LOD = function () {
  8862. THREE.Object3D.call( this );
  8863. this.objects = [];
  8864. };
  8865. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  8866. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  8867. if ( distance === undefined ) distance = 0;
  8868. distance = Math.abs( distance );
  8869. for ( var l = 0; l < this.objects.length; l ++ ) {
  8870. if ( distance < this.objects[ l ].distance ) {
  8871. break;
  8872. }
  8873. }
  8874. this.objects.splice( l, 0, { distance: distance, object: object } );
  8875. this.add( object );
  8876. };
  8877. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  8878. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8879. if ( distance < this.objects[ i ].distance ) {
  8880. break;
  8881. }
  8882. }
  8883. return this.objects[ i - 1 ].object;
  8884. };
  8885. THREE.LOD.prototype.update = function () {
  8886. var v1 = new THREE.Vector3();
  8887. var v2 = new THREE.Vector3();
  8888. return function ( camera ) {
  8889. if ( this.objects.length > 1 ) {
  8890. v1.getPositionFromMatrix( camera.matrixWorld );
  8891. v2.getPositionFromMatrix( this.matrixWorld );
  8892. var distance = v1.distanceTo( v2 );
  8893. this.objects[ 0 ].object.visible = true;
  8894. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8895. if ( distance >= this.objects[ i ].distance ) {
  8896. this.objects[ i - 1 ].object.visible = false;
  8897. this.objects[ i ].object.visible = true;
  8898. } else {
  8899. break;
  8900. }
  8901. }
  8902. for( ; i < l; i ++ ) {
  8903. this.objects[ i ].object.visible = false;
  8904. }
  8905. }
  8906. };
  8907. }();
  8908. THREE.LOD.prototype.clone = function () {
  8909. // TODO
  8910. };
  8911. /**
  8912. * @author mikael emtinger / http://gomo.se/
  8913. * @author alteredq / http://alteredqualia.com/
  8914. */
  8915. THREE.Sprite = function ( material ) {
  8916. THREE.Object3D.call( this );
  8917. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  8918. };
  8919. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  8920. /*
  8921. * Custom update matrix
  8922. */
  8923. THREE.Sprite.prototype.updateMatrix = function () {
  8924. this.matrix.compose( this.position, this.quaternion, this.scale );
  8925. this.matrixWorldNeedsUpdate = true;
  8926. };
  8927. THREE.Sprite.prototype.clone = function ( object ) {
  8928. if ( object === undefined ) object = new THREE.Sprite( this.material );
  8929. THREE.Object3D.prototype.clone.call( this, object );
  8930. return object;
  8931. };
  8932. // Backwards compatibility
  8933. THREE.Particle = THREE.Sprite;
  8934. /**
  8935. * @author mrdoob / http://mrdoob.com/
  8936. */
  8937. THREE.Scene = function () {
  8938. THREE.Object3D.call( this );
  8939. this.fog = null;
  8940. this.overrideMaterial = null;
  8941. this.autoUpdate = true; // checked by the renderer
  8942. this.matrixAutoUpdate = false;
  8943. this.__lights = [];
  8944. this.__objectsAdded = [];
  8945. this.__objectsRemoved = [];
  8946. };
  8947. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  8948. THREE.Scene.prototype.__addObject = function ( object ) {
  8949. if ( object instanceof THREE.Light ) {
  8950. if ( this.__lights.indexOf( object ) === - 1 ) {
  8951. this.__lights.push( object );
  8952. }
  8953. if ( object.target && object.target.parent === undefined ) {
  8954. this.add( object.target );
  8955. }
  8956. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  8957. this.__objectsAdded.push( object );
  8958. // check if previously removed
  8959. var i = this.__objectsRemoved.indexOf( object );
  8960. if ( i !== -1 ) {
  8961. this.__objectsRemoved.splice( i, 1 );
  8962. }
  8963. }
  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. for ( var c = 0; c < object.children.length; c ++ ) {
  8988. this.__removeObject( object.children[ c ] );
  8989. }
  8990. };
  8991. THREE.Scene.prototype.clone = function ( object ) {
  8992. if ( object === undefined ) object = new THREE.Scene();
  8993. THREE.Object3D.prototype.clone.call(this, object);
  8994. if ( this.fog !== null ) object.fog = this.fog.clone();
  8995. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  8996. object.autoUpdate = this.autoUpdate;
  8997. object.matrixAutoUpdate = this.matrixAutoUpdate;
  8998. return object;
  8999. };
  9000. /**
  9001. * @author mrdoob / http://mrdoob.com/
  9002. * @author alteredq / http://alteredqualia.com/
  9003. */
  9004. THREE.Fog = function ( hex, near, far ) {
  9005. this.name = '';
  9006. this.color = new THREE.Color( hex );
  9007. this.near = ( near !== undefined ) ? near : 1;
  9008. this.far = ( far !== undefined ) ? far : 1000;
  9009. };
  9010. THREE.Fog.prototype.clone = function () {
  9011. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  9012. };
  9013. /**
  9014. * @author mrdoob / http://mrdoob.com/
  9015. * @author alteredq / http://alteredqualia.com/
  9016. */
  9017. THREE.FogExp2 = function ( hex, density ) {
  9018. this.name = '';
  9019. this.color = new THREE.Color( hex );
  9020. this.density = ( density !== undefined ) ? density : 0.00025;
  9021. };
  9022. THREE.FogExp2.prototype.clone = function () {
  9023. return new THREE.FogExp2( this.color.getHex(), this.density );
  9024. };
  9025. /**
  9026. * @author mrdoob / http://mrdoob.com/
  9027. */
  9028. THREE.CanvasRenderer = function ( parameters ) {
  9029. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  9030. var smoothstep = THREE.Math.smoothstep;
  9031. parameters = parameters || {};
  9032. var _this = this,
  9033. _renderData, _elements, _lights,
  9034. _projector = new THREE.Projector(),
  9035. _canvas = parameters.canvas !== undefined
  9036. ? parameters.canvas
  9037. : document.createElement( 'canvas' ),
  9038. _canvasWidth = _canvas.width,
  9039. _canvasHeight = _canvas.height,
  9040. _canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
  9041. _canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
  9042. _context = _canvas.getContext( '2d' ),
  9043. _clearColor = new THREE.Color( 0x000000 ),
  9044. _clearAlpha = 0,
  9045. _contextGlobalAlpha = 1,
  9046. _contextGlobalCompositeOperation = 0,
  9047. _contextStrokeStyle = null,
  9048. _contextFillStyle = null,
  9049. _contextLineWidth = null,
  9050. _contextLineCap = null,
  9051. _contextLineJoin = null,
  9052. _contextDashSize = null,
  9053. _contextGapSize = 0,
  9054. _camera,
  9055. _v1, _v2, _v3, _v4,
  9056. _v5 = new THREE.RenderableVertex(),
  9057. _v6 = new THREE.RenderableVertex(),
  9058. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  9059. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  9060. _color = new THREE.Color(),
  9061. _color1 = new THREE.Color(),
  9062. _color2 = new THREE.Color(),
  9063. _color3 = new THREE.Color(),
  9064. _color4 = new THREE.Color(),
  9065. _diffuseColor = new THREE.Color(),
  9066. _emissiveColor = new THREE.Color(),
  9067. _lightColor = new THREE.Color(),
  9068. _patterns = {}, _imagedatas = {},
  9069. _near, _far,
  9070. _image, _uvs,
  9071. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  9072. _clipBox = new THREE.Box2(),
  9073. _clearBox = new THREE.Box2(),
  9074. _elemBox = new THREE.Box2(),
  9075. _ambientLight = new THREE.Color(),
  9076. _directionalLights = new THREE.Color(),
  9077. _pointLights = new THREE.Color(),
  9078. _vector3 = new THREE.Vector3(), // Needed for PointLight
  9079. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  9080. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  9081. _pixelMap = document.createElement( 'canvas' );
  9082. _pixelMap.width = _pixelMap.height = 2;
  9083. _pixelMapContext = _pixelMap.getContext( '2d' );
  9084. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  9085. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  9086. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  9087. _pixelMapData = _pixelMapImage.data;
  9088. _gradientMap = document.createElement( 'canvas' );
  9089. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  9090. _gradientMapContext = _gradientMap.getContext( '2d' );
  9091. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  9092. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  9093. _gradientMapQuality --; // Fix UVs
  9094. // dash+gap fallbacks for Firefox and everything else
  9095. if ( _context.setLineDash === undefined ) {
  9096. if ( _context.mozDash !== undefined ) {
  9097. _context.setLineDash = function ( values ) {
  9098. _context.mozDash = values[ 0 ] !== null ? values : null;
  9099. }
  9100. } else {
  9101. _context.setLineDash = function () {}
  9102. }
  9103. }
  9104. this.domElement = _canvas;
  9105. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  9106. ? parameters.devicePixelRatio
  9107. : self.devicePixelRatio !== undefined
  9108. ? self.devicePixelRatio
  9109. : 1;
  9110. this.autoClear = true;
  9111. this.sortObjects = true;
  9112. this.sortElements = true;
  9113. this.info = {
  9114. render: {
  9115. vertices: 0,
  9116. faces: 0
  9117. }
  9118. }
  9119. // WebGLRenderer compatibility
  9120. this.supportsVertexTextures = function () {};
  9121. this.setFaceCulling = function () {};
  9122. this.setSize = function ( width, height, updateStyle ) {
  9123. _canvasWidth = width * this.devicePixelRatio;
  9124. _canvasHeight = height * this.devicePixelRatio;
  9125. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  9126. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  9127. _canvas.width = _canvasWidth;
  9128. _canvas.height = _canvasHeight;
  9129. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  9130. _canvas.style.width = width + 'px';
  9131. _canvas.style.height = height + 'px';
  9132. }
  9133. _clipBox.set(
  9134. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  9135. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  9136. );
  9137. _clearBox.set(
  9138. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  9139. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  9140. );
  9141. _contextGlobalAlpha = 1;
  9142. _contextGlobalCompositeOperation = 0;
  9143. _contextStrokeStyle = null;
  9144. _contextFillStyle = null;
  9145. _contextLineWidth = null;
  9146. _contextLineCap = null;
  9147. _contextLineJoin = null;
  9148. };
  9149. this.setClearColor = function ( color, alpha ) {
  9150. _clearColor.set( color );
  9151. _clearAlpha = alpha !== undefined ? alpha : 1;
  9152. _clearBox.set(
  9153. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  9154. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  9155. );
  9156. };
  9157. this.setClearColorHex = function ( hex, alpha ) {
  9158. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  9159. this.setClearColor( hex, alpha );
  9160. };
  9161. this.getMaxAnisotropy = function () {
  9162. return 0;
  9163. };
  9164. this.clear = function () {
  9165. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  9166. if ( _clearBox.empty() === false ) {
  9167. _clearBox.intersect( _clipBox );
  9168. _clearBox.expandByScalar( 2 );
  9169. if ( _clearAlpha < 1 ) {
  9170. _context.clearRect(
  9171. _clearBox.min.x | 0,
  9172. _clearBox.min.y | 0,
  9173. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9174. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9175. );
  9176. }
  9177. if ( _clearAlpha > 0 ) {
  9178. setBlending( THREE.NormalBlending );
  9179. setOpacity( 1 );
  9180. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  9181. _context.fillRect(
  9182. _clearBox.min.x | 0,
  9183. _clearBox.min.y | 0,
  9184. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9185. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9186. );
  9187. }
  9188. _clearBox.makeEmpty();
  9189. }
  9190. };
  9191. this.render = function ( scene, camera ) {
  9192. if ( camera instanceof THREE.Camera === false ) {
  9193. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  9194. return;
  9195. }
  9196. if ( this.autoClear === true ) this.clear();
  9197. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  9198. _this.info.render.vertices = 0;
  9199. _this.info.render.faces = 0;
  9200. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  9201. _elements = _renderData.elements;
  9202. _lights = _renderData.lights;
  9203. _camera = camera;
  9204. /* DEBUG
  9205. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  9206. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  9207. */
  9208. calculateLights();
  9209. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  9210. var element = _elements[ e ];
  9211. var material = element.material;
  9212. if ( material === undefined || material.visible === false ) continue;
  9213. _elemBox.makeEmpty();
  9214. if ( element instanceof THREE.RenderableSprite ) {
  9215. _v1 = element;
  9216. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  9217. renderSprite( _v1, element, material );
  9218. } else if ( element instanceof THREE.RenderableLine ) {
  9219. _v1 = element.v1; _v2 = element.v2;
  9220. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9221. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9222. _elemBox.setFromPoints( [
  9223. _v1.positionScreen,
  9224. _v2.positionScreen
  9225. ] );
  9226. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9227. renderLine( _v1, _v2, element, material );
  9228. }
  9229. } else if ( element instanceof THREE.RenderableFace3 ) {
  9230. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  9231. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  9232. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  9233. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  9234. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9235. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9236. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  9237. if ( material.overdraw > 0 ) {
  9238. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  9239. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  9240. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  9241. }
  9242. _elemBox.setFromPoints( [
  9243. _v1.positionScreen,
  9244. _v2.positionScreen,
  9245. _v3.positionScreen
  9246. ] );
  9247. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9248. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  9249. }
  9250. }
  9251. /* DEBUG
  9252. setLineWidth( 1 );
  9253. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  9254. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  9255. */
  9256. _clearBox.union( _elemBox );
  9257. }
  9258. /* DEBUG
  9259. setLineWidth( 1 );
  9260. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  9261. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  9262. */
  9263. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  9264. };
  9265. //
  9266. function calculateLights() {
  9267. _ambientLight.setRGB( 0, 0, 0 );
  9268. _directionalLights.setRGB( 0, 0, 0 );
  9269. _pointLights.setRGB( 0, 0, 0 );
  9270. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9271. var light = _lights[ l ];
  9272. var lightColor = light.color;
  9273. if ( light instanceof THREE.AmbientLight ) {
  9274. _ambientLight.add( lightColor );
  9275. } else if ( light instanceof THREE.DirectionalLight ) {
  9276. // for sprites
  9277. _directionalLights.add( lightColor );
  9278. } else if ( light instanceof THREE.PointLight ) {
  9279. // for sprites
  9280. _pointLights.add( lightColor );
  9281. }
  9282. }
  9283. }
  9284. function calculateLight( position, normal, color ) {
  9285. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9286. var light = _lights[ l ];
  9287. _lightColor.copy( light.color );
  9288. if ( light instanceof THREE.DirectionalLight ) {
  9289. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld ).normalize();
  9290. var amount = normal.dot( lightPosition );
  9291. if ( amount <= 0 ) continue;
  9292. amount *= light.intensity;
  9293. color.add( _lightColor.multiplyScalar( amount ) );
  9294. } else if ( light instanceof THREE.PointLight ) {
  9295. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld );
  9296. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  9297. if ( amount <= 0 ) continue;
  9298. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  9299. if ( amount == 0 ) continue;
  9300. amount *= light.intensity;
  9301. color.add( _lightColor.multiplyScalar( amount ) );
  9302. }
  9303. }
  9304. }
  9305. function renderSprite( v1, element, material ) {
  9306. setOpacity( material.opacity );
  9307. setBlending( material.blending );
  9308. var scaleX = element.scale.x * _canvasWidthHalf;
  9309. var scaleY = element.scale.y * _canvasHeightHalf;
  9310. _elemBox.min.set( v1.x - ( scaleX * 0.5 ), v1.y - ( scaleY * 0.5 ) );
  9311. _elemBox.max.set( v1.x + ( scaleX * 0.5 ), v1.y + ( scaleY * 0.5 ) );
  9312. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9313. _elemBox.makeEmpty();
  9314. return;
  9315. }
  9316. if ( material instanceof THREE.SpriteMaterial ||
  9317. material instanceof THREE.ParticleSystemMaterial ) { // Backwards compatibility
  9318. if ( material.map !== null ) {
  9319. var bitmap = material.map.image;
  9320. _context.save();
  9321. _context.translate( v1.x, v1.y );
  9322. _context.rotate( - material.rotation );
  9323. _context.scale( scaleX, - scaleY );
  9324. _context.drawImage( bitmap, 0, 0, bitmap.width, bitmap.height, - 0.5, - 0.5, 1, 1 );
  9325. _context.restore();
  9326. } else {
  9327. setFillStyle( material.color.getStyle() );
  9328. _context.save();
  9329. _context.translate( v1.x, v1.y );
  9330. _context.rotate( - element.rotation );
  9331. _context.scale( scaleX, scaleY );
  9332. _context.fillRect( - 0.5, - 0.5, 1, 1 );
  9333. _context.restore();
  9334. }
  9335. } else if ( material instanceof THREE.SpriteCanvasMaterial ) {
  9336. setStrokeStyle( material.color.getStyle() );
  9337. setFillStyle( material.color.getStyle() );
  9338. _context.save();
  9339. _context.translate( v1.x, v1.y );
  9340. _context.rotate( - element.rotation );
  9341. _context.scale( scaleX, scaleY );
  9342. material.program( _context );
  9343. _context.restore();
  9344. }
  9345. /* DEBUG
  9346. setStrokeStyle( 'rgb(255,255,0)' );
  9347. _context.beginPath();
  9348. _context.moveTo( v1.x - 10, v1.y );
  9349. _context.lineTo( v1.x + 10, v1.y );
  9350. _context.moveTo( v1.x, v1.y - 10 );
  9351. _context.lineTo( v1.x, v1.y + 10 );
  9352. _context.stroke();
  9353. */
  9354. }
  9355. function renderLine( v1, v2, element, material ) {
  9356. setOpacity( material.opacity );
  9357. setBlending( material.blending );
  9358. _context.beginPath();
  9359. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  9360. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  9361. if ( material instanceof THREE.LineBasicMaterial ) {
  9362. setLineWidth( material.linewidth );
  9363. setLineCap( material.linecap );
  9364. setLineJoin( material.linejoin );
  9365. if ( material.vertexColors !== THREE.VertexColors ) {
  9366. setStrokeStyle( material.color.getStyle() );
  9367. } else {
  9368. var colorStyle1 = element.vertexColors[0].getStyle();
  9369. var colorStyle2 = element.vertexColors[1].getStyle();
  9370. if ( colorStyle1 === colorStyle2 ) {
  9371. setStrokeStyle( colorStyle1 );
  9372. } else {
  9373. try {
  9374. var grad = _context.createLinearGradient(
  9375. v1.positionScreen.x,
  9376. v1.positionScreen.y,
  9377. v2.positionScreen.x,
  9378. v2.positionScreen.y
  9379. );
  9380. grad.addColorStop( 0, colorStyle1 );
  9381. grad.addColorStop( 1, colorStyle2 );
  9382. } catch ( exception ) {
  9383. grad = colorStyle1;
  9384. }
  9385. setStrokeStyle( grad );
  9386. }
  9387. }
  9388. _context.stroke();
  9389. _elemBox.expandByScalar( material.linewidth * 2 );
  9390. } else if ( material instanceof THREE.LineDashedMaterial ) {
  9391. setLineWidth( material.linewidth );
  9392. setLineCap( material.linecap );
  9393. setLineJoin( material.linejoin );
  9394. setStrokeStyle( material.color.getStyle() );
  9395. setDashAndGap( material.dashSize, material.gapSize );
  9396. _context.stroke();
  9397. _elemBox.expandByScalar( material.linewidth * 2 );
  9398. setDashAndGap( null, null );
  9399. }
  9400. }
  9401. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  9402. _this.info.render.vertices += 3;
  9403. _this.info.render.faces ++;
  9404. setOpacity( material.opacity );
  9405. setBlending( material.blending );
  9406. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9407. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9408. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9409. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  9410. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  9411. _diffuseColor.copy( material.color );
  9412. _emissiveColor.copy( material.emissive );
  9413. if ( material.vertexColors === THREE.FaceColors ) {
  9414. _diffuseColor.multiply( element.color );
  9415. }
  9416. if ( material.wireframe === false && material.shading === THREE.SmoothShading && element.vertexNormalsLength === 3 ) {
  9417. _color1.copy( _ambientLight );
  9418. _color2.copy( _ambientLight );
  9419. _color3.copy( _ambientLight );
  9420. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  9421. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  9422. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  9423. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  9424. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  9425. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  9426. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9427. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9428. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9429. } else {
  9430. _color.copy( _ambientLight );
  9431. calculateLight( element.centroidModel, element.normalModel, _color );
  9432. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9433. material.wireframe === true
  9434. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9435. : fillPath( _color );
  9436. }
  9437. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9438. if ( material.map !== null ) {
  9439. if ( material.map.mapping instanceof THREE.UVMapping ) {
  9440. _uvs = element.uvs[ 0 ];
  9441. 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 );
  9442. }
  9443. } else if ( material.envMap !== null ) {
  9444. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  9445. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  9446. _uv1x = 0.5 * _vector3.x + 0.5;
  9447. _uv1y = 0.5 * _vector3.y + 0.5;
  9448. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  9449. _uv2x = 0.5 * _vector3.x + 0.5;
  9450. _uv2y = 0.5 * _vector3.y + 0.5;
  9451. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  9452. _uv3x = 0.5 * _vector3.x + 0.5;
  9453. _uv3y = 0.5 * _vector3.y + 0.5;
  9454. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9455. }/* else if ( material.envMap.mapping === THREE.SphericalRefractionMapping ) {
  9456. }*/
  9457. } else {
  9458. _color.copy( material.color );
  9459. if ( material.vertexColors === THREE.FaceColors ) {
  9460. _color.multiply( element.color );
  9461. }
  9462. material.wireframe === true
  9463. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9464. : fillPath( _color );
  9465. }
  9466. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9467. _near = _camera.near;
  9468. _far = _camera.far;
  9469. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  9470. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  9471. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  9472. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9473. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9474. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9475. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9476. var normal;
  9477. if ( material.shading === THREE.FlatShading ) {
  9478. normal = element.normalModelView;
  9479. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9480. material.wireframe === true
  9481. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9482. : fillPath( _color );
  9483. } else if ( material.shading === THREE.SmoothShading ) {
  9484. normal = element.vertexNormalsModelView[ uv1 ];
  9485. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9486. normal = element.vertexNormalsModelView[ uv2 ];
  9487. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9488. normal = element.vertexNormalsModelView[ uv3 ];
  9489. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9490. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9491. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9492. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9493. }
  9494. }
  9495. }
  9496. //
  9497. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  9498. _context.beginPath();
  9499. _context.moveTo( x0, y0 );
  9500. _context.lineTo( x1, y1 );
  9501. _context.lineTo( x2, y2 );
  9502. _context.closePath();
  9503. }
  9504. function strokePath( color, linewidth, linecap, linejoin ) {
  9505. setLineWidth( linewidth );
  9506. setLineCap( linecap );
  9507. setLineJoin( linejoin );
  9508. setStrokeStyle( color.getStyle() );
  9509. _context.stroke();
  9510. _elemBox.expandByScalar( linewidth * 2 );
  9511. }
  9512. function fillPath( color ) {
  9513. setFillStyle( color.getStyle() );
  9514. _context.fill();
  9515. }
  9516. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  9517. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width === 0 ) return;
  9518. if ( texture.needsUpdate === true ) {
  9519. var repeatX = texture.wrapS === THREE.RepeatWrapping;
  9520. var repeatY = texture.wrapT === THREE.RepeatWrapping;
  9521. _patterns[ texture.id ] = _context.createPattern(
  9522. texture.image, repeatX === true && repeatY === true
  9523. ? 'repeat'
  9524. : repeatX === true && repeatY === false
  9525. ? 'repeat-x'
  9526. : repeatX === false && repeatY === true
  9527. ? 'repeat-y'
  9528. : 'no-repeat'
  9529. );
  9530. texture.needsUpdate = false;
  9531. }
  9532. _patterns[ texture.id ] === undefined
  9533. ? setFillStyle( 'rgba(0,0,0,1)' )
  9534. : setFillStyle( _patterns[ texture.id ] );
  9535. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9536. var a, b, c, d, e, f, det, idet,
  9537. offsetX = texture.offset.x / texture.repeat.x,
  9538. offsetY = texture.offset.y / texture.repeat.y,
  9539. width = texture.image.width * texture.repeat.x,
  9540. height = texture.image.height * texture.repeat.y;
  9541. u0 = ( u0 + offsetX ) * width;
  9542. v0 = ( 1.0 - v0 + offsetY ) * height;
  9543. u1 = ( u1 + offsetX ) * width;
  9544. v1 = ( 1.0 - v1 + offsetY ) * height;
  9545. u2 = ( u2 + offsetX ) * width;
  9546. v2 = ( 1.0 - v2 + offsetY ) * height;
  9547. x1 -= x0; y1 -= y0;
  9548. x2 -= x0; y2 -= y0;
  9549. u1 -= u0; v1 -= v0;
  9550. u2 -= u0; v2 -= v0;
  9551. det = u1 * v2 - u2 * v1;
  9552. if ( det === 0 ) {
  9553. if ( _imagedatas[ texture.id ] === undefined ) {
  9554. var canvas = document.createElement( 'canvas' )
  9555. canvas.width = texture.image.width;
  9556. canvas.height = texture.image.height;
  9557. var context = canvas.getContext( '2d' );
  9558. context.drawImage( texture.image, 0, 0 );
  9559. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  9560. }
  9561. var data = _imagedatas[ texture.id ];
  9562. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  9563. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  9564. fillPath( _color );
  9565. return;
  9566. }
  9567. idet = 1 / det;
  9568. a = ( v2 * x1 - v1 * x2 ) * idet;
  9569. b = ( v2 * y1 - v1 * y2 ) * idet;
  9570. c = ( u1 * x2 - u2 * x1 ) * idet;
  9571. d = ( u1 * y2 - u2 * y1 ) * idet;
  9572. e = x0 - a * u0 - c * v0;
  9573. f = y0 - b * u0 - d * v0;
  9574. _context.save();
  9575. _context.transform( a, b, c, d, e, f );
  9576. _context.fill();
  9577. _context.restore();
  9578. }
  9579. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  9580. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9581. var a, b, c, d, e, f, det, idet,
  9582. width = image.width - 1,
  9583. height = image.height - 1;
  9584. u0 *= width; v0 *= height;
  9585. u1 *= width; v1 *= height;
  9586. u2 *= width; v2 *= height;
  9587. x1 -= x0; y1 -= y0;
  9588. x2 -= x0; y2 -= y0;
  9589. u1 -= u0; v1 -= v0;
  9590. u2 -= u0; v2 -= v0;
  9591. det = u1 * v2 - u2 * v1;
  9592. idet = 1 / det;
  9593. a = ( v2 * x1 - v1 * x2 ) * idet;
  9594. b = ( v2 * y1 - v1 * y2 ) * idet;
  9595. c = ( u1 * x2 - u2 * x1 ) * idet;
  9596. d = ( u1 * y2 - u2 * y1 ) * idet;
  9597. e = x0 - a * u0 - c * v0;
  9598. f = y0 - b * u0 - d * v0;
  9599. _context.save();
  9600. _context.transform( a, b, c, d, e, f );
  9601. _context.clip();
  9602. _context.drawImage( image, 0, 0 );
  9603. _context.restore();
  9604. }
  9605. function getGradientTexture( color1, color2, color3, color4 ) {
  9606. // http://mrdoob.com/blog/post/710
  9607. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  9608. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  9609. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  9610. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  9611. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  9612. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  9613. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  9614. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  9615. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  9616. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  9617. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  9618. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  9619. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  9620. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  9621. return _gradientMap;
  9622. }
  9623. // Hide anti-alias gaps
  9624. function expand( v1, v2, pixels ) {
  9625. var x = v2.x - v1.x, y = v2.y - v1.y,
  9626. det = x * x + y * y, idet;
  9627. if ( det === 0 ) return;
  9628. idet = pixels / Math.sqrt( det );
  9629. x *= idet; y *= idet;
  9630. v2.x += x; v2.y += y;
  9631. v1.x -= x; v1.y -= y;
  9632. }
  9633. // Context cached methods.
  9634. function setOpacity( value ) {
  9635. if ( _contextGlobalAlpha !== value ) {
  9636. _context.globalAlpha = value;
  9637. _contextGlobalAlpha = value;
  9638. }
  9639. }
  9640. function setBlending( value ) {
  9641. if ( _contextGlobalCompositeOperation !== value ) {
  9642. if ( value === THREE.NormalBlending ) {
  9643. _context.globalCompositeOperation = 'source-over';
  9644. } else if ( value === THREE.AdditiveBlending ) {
  9645. _context.globalCompositeOperation = 'lighter';
  9646. } else if ( value === THREE.SubtractiveBlending ) {
  9647. _context.globalCompositeOperation = 'darker';
  9648. }
  9649. _contextGlobalCompositeOperation = value;
  9650. }
  9651. }
  9652. function setLineWidth( value ) {
  9653. if ( _contextLineWidth !== value ) {
  9654. _context.lineWidth = value;
  9655. _contextLineWidth = value;
  9656. }
  9657. }
  9658. function setLineCap( value ) {
  9659. // "butt", "round", "square"
  9660. if ( _contextLineCap !== value ) {
  9661. _context.lineCap = value;
  9662. _contextLineCap = value;
  9663. }
  9664. }
  9665. function setLineJoin( value ) {
  9666. // "round", "bevel", "miter"
  9667. if ( _contextLineJoin !== value ) {
  9668. _context.lineJoin = value;
  9669. _contextLineJoin = value;
  9670. }
  9671. }
  9672. function setStrokeStyle( value ) {
  9673. if ( _contextStrokeStyle !== value ) {
  9674. _context.strokeStyle = value;
  9675. _contextStrokeStyle = value;
  9676. }
  9677. }
  9678. function setFillStyle( value ) {
  9679. if ( _contextFillStyle !== value ) {
  9680. _context.fillStyle = value;
  9681. _contextFillStyle = value;
  9682. }
  9683. }
  9684. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  9685. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  9686. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  9687. _contextDashSize = dashSizeValue;
  9688. _contextGapSize = gapSizeValue;
  9689. }
  9690. }
  9691. };
  9692. /**
  9693. * @author alteredq / http://alteredqualia.com/
  9694. * @author mrdoob / http://mrdoob.com/
  9695. * @author mikael emtinger / http://gomo.se/
  9696. */
  9697. THREE.ShaderChunk = {
  9698. // FOG
  9699. fog_pars_fragment: [
  9700. "#ifdef USE_FOG",
  9701. "uniform vec3 fogColor;",
  9702. "#ifdef FOG_EXP2",
  9703. "uniform float fogDensity;",
  9704. "#else",
  9705. "uniform float fogNear;",
  9706. "uniform float fogFar;",
  9707. "#endif",
  9708. "#endif"
  9709. ].join("\n"),
  9710. fog_fragment: [
  9711. "#ifdef USE_FOG",
  9712. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9713. "#ifdef FOG_EXP2",
  9714. "const float LOG2 = 1.442695;",
  9715. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  9716. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  9717. "#else",
  9718. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  9719. "#endif",
  9720. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  9721. "#endif"
  9722. ].join("\n"),
  9723. // ENVIRONMENT MAP
  9724. envmap_pars_fragment: [
  9725. "#ifdef USE_ENVMAP",
  9726. "uniform float reflectivity;",
  9727. "uniform samplerCube envMap;",
  9728. "uniform float flipEnvMap;",
  9729. "uniform int combine;",
  9730. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9731. "uniform bool useRefract;",
  9732. "uniform float refractionRatio;",
  9733. "#else",
  9734. "varying vec3 vReflect;",
  9735. "#endif",
  9736. "#endif"
  9737. ].join("\n"),
  9738. envmap_fragment: [
  9739. "#ifdef USE_ENVMAP",
  9740. "vec3 reflectVec;",
  9741. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9742. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  9743. "if ( useRefract ) {",
  9744. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  9745. "} else { ",
  9746. "reflectVec = reflect( cameraToVertex, normal );",
  9747. "}",
  9748. "#else",
  9749. "reflectVec = vReflect;",
  9750. "#endif",
  9751. "#ifdef DOUBLE_SIDED",
  9752. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9753. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9754. "#else",
  9755. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9756. "#endif",
  9757. "#ifdef GAMMA_INPUT",
  9758. "cubeColor.xyz *= cubeColor.xyz;",
  9759. "#endif",
  9760. "if ( combine == 1 ) {",
  9761. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  9762. "} else if ( combine == 2 ) {",
  9763. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  9764. "} else {",
  9765. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  9766. "}",
  9767. "#endif"
  9768. ].join("\n"),
  9769. envmap_pars_vertex: [
  9770. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9771. "varying vec3 vReflect;",
  9772. "uniform float refractionRatio;",
  9773. "uniform bool useRefract;",
  9774. "#endif"
  9775. ].join("\n"),
  9776. worldpos_vertex : [
  9777. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  9778. "#ifdef USE_SKINNING",
  9779. "vec4 worldPosition = modelMatrix * skinned;",
  9780. "#endif",
  9781. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9782. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  9783. "#endif",
  9784. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9785. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  9786. "#endif",
  9787. "#endif"
  9788. ].join("\n"),
  9789. envmap_vertex : [
  9790. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9791. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  9792. "worldNormal = normalize( worldNormal );",
  9793. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  9794. "if ( useRefract ) {",
  9795. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  9796. "} else {",
  9797. "vReflect = reflect( cameraToVertex, worldNormal );",
  9798. "}",
  9799. "#endif"
  9800. ].join("\n"),
  9801. // COLOR MAP (particles)
  9802. map_particle_pars_fragment: [
  9803. "#ifdef USE_MAP",
  9804. "uniform sampler2D map;",
  9805. "#endif"
  9806. ].join("\n"),
  9807. map_particle_fragment: [
  9808. "#ifdef USE_MAP",
  9809. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  9810. "#endif"
  9811. ].join("\n"),
  9812. // COLOR MAP (triangles)
  9813. map_pars_vertex: [
  9814. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9815. "varying vec2 vUv;",
  9816. "uniform vec4 offsetRepeat;",
  9817. "#endif"
  9818. ].join("\n"),
  9819. map_pars_fragment: [
  9820. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9821. "varying vec2 vUv;",
  9822. "#endif",
  9823. "#ifdef USE_MAP",
  9824. "uniform sampler2D map;",
  9825. "#endif"
  9826. ].join("\n"),
  9827. map_vertex: [
  9828. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9829. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  9830. "#endif"
  9831. ].join("\n"),
  9832. map_fragment: [
  9833. "#ifdef USE_MAP",
  9834. "vec4 texelColor = texture2D( map, vUv );",
  9835. "#ifdef GAMMA_INPUT",
  9836. "texelColor.xyz *= texelColor.xyz;",
  9837. "#endif",
  9838. "gl_FragColor = gl_FragColor * texelColor;",
  9839. "#endif"
  9840. ].join("\n"),
  9841. // LIGHT MAP
  9842. lightmap_pars_fragment: [
  9843. "#ifdef USE_LIGHTMAP",
  9844. "varying vec2 vUv2;",
  9845. "uniform sampler2D lightMap;",
  9846. "#endif"
  9847. ].join("\n"),
  9848. lightmap_pars_vertex: [
  9849. "#ifdef USE_LIGHTMAP",
  9850. "varying vec2 vUv2;",
  9851. "#endif"
  9852. ].join("\n"),
  9853. lightmap_fragment: [
  9854. "#ifdef USE_LIGHTMAP",
  9855. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  9856. "#endif"
  9857. ].join("\n"),
  9858. lightmap_vertex: [
  9859. "#ifdef USE_LIGHTMAP",
  9860. "vUv2 = uv2;",
  9861. "#endif"
  9862. ].join("\n"),
  9863. // BUMP MAP
  9864. bumpmap_pars_fragment: [
  9865. "#ifdef USE_BUMPMAP",
  9866. "uniform sampler2D bumpMap;",
  9867. "uniform float bumpScale;",
  9868. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  9869. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  9870. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9871. "vec2 dHdxy_fwd() {",
  9872. "vec2 dSTdx = dFdx( vUv );",
  9873. "vec2 dSTdy = dFdy( vUv );",
  9874. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  9875. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  9876. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  9877. "return vec2( dBx, dBy );",
  9878. "}",
  9879. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  9880. "vec3 vSigmaX = dFdx( surf_pos );",
  9881. "vec3 vSigmaY = dFdy( surf_pos );",
  9882. "vec3 vN = surf_norm;", // normalized
  9883. "vec3 R1 = cross( vSigmaY, vN );",
  9884. "vec3 R2 = cross( vN, vSigmaX );",
  9885. "float fDet = dot( vSigmaX, R1 );",
  9886. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  9887. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  9888. "}",
  9889. "#endif"
  9890. ].join("\n"),
  9891. // NORMAL MAP
  9892. normalmap_pars_fragment: [
  9893. "#ifdef USE_NORMALMAP",
  9894. "uniform sampler2D normalMap;",
  9895. "uniform vec2 normalScale;",
  9896. // Per-Pixel Tangent Space Normal Mapping
  9897. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  9898. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  9899. "vec3 q0 = dFdx( eye_pos.xyz );",
  9900. "vec3 q1 = dFdy( eye_pos.xyz );",
  9901. "vec2 st0 = dFdx( vUv.st );",
  9902. "vec2 st1 = dFdy( vUv.st );",
  9903. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  9904. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  9905. "vec3 N = normalize( surf_norm );",
  9906. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  9907. "mapN.xy = normalScale * mapN.xy;",
  9908. "mat3 tsn = mat3( S, T, N );",
  9909. "return normalize( tsn * mapN );",
  9910. "}",
  9911. "#endif"
  9912. ].join("\n"),
  9913. // SPECULAR MAP
  9914. specularmap_pars_fragment: [
  9915. "#ifdef USE_SPECULARMAP",
  9916. "uniform sampler2D specularMap;",
  9917. "#endif"
  9918. ].join("\n"),
  9919. specularmap_fragment: [
  9920. "float specularStrength;",
  9921. "#ifdef USE_SPECULARMAP",
  9922. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  9923. "specularStrength = texelSpecular.r;",
  9924. "#else",
  9925. "specularStrength = 1.0;",
  9926. "#endif"
  9927. ].join("\n"),
  9928. // LIGHTS LAMBERT
  9929. lights_lambert_pars_vertex: [
  9930. "uniform vec3 ambient;",
  9931. "uniform vec3 diffuse;",
  9932. "uniform vec3 emissive;",
  9933. "uniform vec3 ambientLightColor;",
  9934. "#if MAX_DIR_LIGHTS > 0",
  9935. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9936. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9937. "#endif",
  9938. "#if MAX_HEMI_LIGHTS > 0",
  9939. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9940. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9941. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9942. "#endif",
  9943. "#if MAX_POINT_LIGHTS > 0",
  9944. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9945. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9946. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9947. "#endif",
  9948. "#if MAX_SPOT_LIGHTS > 0",
  9949. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9950. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9951. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9952. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9953. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9954. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9955. "#endif",
  9956. "#ifdef WRAP_AROUND",
  9957. "uniform vec3 wrapRGB;",
  9958. "#endif"
  9959. ].join("\n"),
  9960. lights_lambert_vertex: [
  9961. "vLightFront = vec3( 0.0 );",
  9962. "#ifdef DOUBLE_SIDED",
  9963. "vLightBack = vec3( 0.0 );",
  9964. "#endif",
  9965. "transformedNormal = normalize( transformedNormal );",
  9966. "#if MAX_DIR_LIGHTS > 0",
  9967. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9968. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9969. "vec3 dirVector = normalize( lDirection.xyz );",
  9970. "float dotProduct = dot( transformedNormal, dirVector );",
  9971. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9972. "#ifdef DOUBLE_SIDED",
  9973. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9974. "#ifdef WRAP_AROUND",
  9975. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9976. "#endif",
  9977. "#endif",
  9978. "#ifdef WRAP_AROUND",
  9979. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9980. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  9981. "#ifdef DOUBLE_SIDED",
  9982. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  9983. "#endif",
  9984. "#endif",
  9985. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  9986. "#ifdef DOUBLE_SIDED",
  9987. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  9988. "#endif",
  9989. "}",
  9990. "#endif",
  9991. "#if MAX_POINT_LIGHTS > 0",
  9992. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9993. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9994. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9995. "float lDistance = 1.0;",
  9996. "if ( pointLightDistance[ i ] > 0.0 )",
  9997. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9998. "lVector = normalize( lVector );",
  9999. "float dotProduct = dot( transformedNormal, lVector );",
  10000. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10001. "#ifdef DOUBLE_SIDED",
  10002. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10003. "#ifdef WRAP_AROUND",
  10004. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10005. "#endif",
  10006. "#endif",
  10007. "#ifdef WRAP_AROUND",
  10008. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10009. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  10010. "#ifdef DOUBLE_SIDED",
  10011. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  10012. "#endif",
  10013. "#endif",
  10014. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  10015. "#ifdef DOUBLE_SIDED",
  10016. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  10017. "#endif",
  10018. "}",
  10019. "#endif",
  10020. "#if MAX_SPOT_LIGHTS > 0",
  10021. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10022. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10023. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10024. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  10025. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10026. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10027. "float lDistance = 1.0;",
  10028. "if ( spotLightDistance[ i ] > 0.0 )",
  10029. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10030. "lVector = normalize( lVector );",
  10031. "float dotProduct = dot( transformedNormal, lVector );",
  10032. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10033. "#ifdef DOUBLE_SIDED",
  10034. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10035. "#ifdef WRAP_AROUND",
  10036. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10037. "#endif",
  10038. "#endif",
  10039. "#ifdef WRAP_AROUND",
  10040. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10041. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  10042. "#ifdef DOUBLE_SIDED",
  10043. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  10044. "#endif",
  10045. "#endif",
  10046. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  10047. "#ifdef DOUBLE_SIDED",
  10048. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  10049. "#endif",
  10050. "}",
  10051. "}",
  10052. "#endif",
  10053. "#if MAX_HEMI_LIGHTS > 0",
  10054. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10055. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10056. "vec3 lVector = normalize( lDirection.xyz );",
  10057. "float dotProduct = dot( transformedNormal, lVector );",
  10058. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10059. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  10060. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10061. "#ifdef DOUBLE_SIDED",
  10062. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  10063. "#endif",
  10064. "}",
  10065. "#endif",
  10066. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  10067. "#ifdef DOUBLE_SIDED",
  10068. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  10069. "#endif"
  10070. ].join("\n"),
  10071. // LIGHTS PHONG
  10072. lights_phong_pars_vertex: [
  10073. "#ifndef PHONG_PER_PIXEL",
  10074. "#if MAX_POINT_LIGHTS > 0",
  10075. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10076. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10077. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  10078. "#endif",
  10079. "#if MAX_SPOT_LIGHTS > 0",
  10080. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10081. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10082. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  10083. "#endif",
  10084. "#endif",
  10085. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10086. "varying vec3 vWorldPosition;",
  10087. "#endif"
  10088. ].join("\n"),
  10089. lights_phong_vertex: [
  10090. "#ifndef PHONG_PER_PIXEL",
  10091. "#if MAX_POINT_LIGHTS > 0",
  10092. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10093. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10094. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10095. "float lDistance = 1.0;",
  10096. "if ( pointLightDistance[ i ] > 0.0 )",
  10097. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10098. "vPointLight[ i ] = vec4( lVector, lDistance );",
  10099. "}",
  10100. "#endif",
  10101. "#if MAX_SPOT_LIGHTS > 0",
  10102. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10103. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10104. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10105. "float lDistance = 1.0;",
  10106. "if ( spotLightDistance[ i ] > 0.0 )",
  10107. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10108. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  10109. "}",
  10110. "#endif",
  10111. "#endif",
  10112. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10113. "vWorldPosition = worldPosition.xyz;",
  10114. "#endif"
  10115. ].join("\n"),
  10116. lights_phong_pars_fragment: [
  10117. "uniform vec3 ambientLightColor;",
  10118. "#if MAX_DIR_LIGHTS > 0",
  10119. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10120. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10121. "#endif",
  10122. "#if MAX_HEMI_LIGHTS > 0",
  10123. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10124. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10125. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10126. "#endif",
  10127. "#if MAX_POINT_LIGHTS > 0",
  10128. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10129. "#ifdef PHONG_PER_PIXEL",
  10130. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10131. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10132. "#else",
  10133. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  10134. "#endif",
  10135. "#endif",
  10136. "#if MAX_SPOT_LIGHTS > 0",
  10137. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10138. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10139. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10140. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10141. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10142. "#ifdef PHONG_PER_PIXEL",
  10143. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10144. "#else",
  10145. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  10146. "#endif",
  10147. "#endif",
  10148. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10149. "varying vec3 vWorldPosition;",
  10150. "#endif",
  10151. "#ifdef WRAP_AROUND",
  10152. "uniform vec3 wrapRGB;",
  10153. "#endif",
  10154. "varying vec3 vViewPosition;",
  10155. "varying vec3 vNormal;"
  10156. ].join("\n"),
  10157. lights_phong_fragment: [
  10158. "vec3 normal = normalize( vNormal );",
  10159. "vec3 viewPosition = normalize( vViewPosition );",
  10160. "#ifdef DOUBLE_SIDED",
  10161. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10162. "#endif",
  10163. "#ifdef USE_NORMALMAP",
  10164. "normal = perturbNormal2Arb( -vViewPosition, normal );",
  10165. "#elif defined( USE_BUMPMAP )",
  10166. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  10167. "#endif",
  10168. "#if MAX_POINT_LIGHTS > 0",
  10169. "vec3 pointDiffuse = vec3( 0.0 );",
  10170. "vec3 pointSpecular = vec3( 0.0 );",
  10171. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10172. "#ifdef PHONG_PER_PIXEL",
  10173. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10174. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10175. "float lDistance = 1.0;",
  10176. "if ( pointLightDistance[ i ] > 0.0 )",
  10177. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10178. "lVector = normalize( lVector );",
  10179. "#else",
  10180. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  10181. "float lDistance = vPointLight[ i ].w;",
  10182. "#endif",
  10183. // diffuse
  10184. "float dotProduct = dot( normal, lVector );",
  10185. "#ifdef WRAP_AROUND",
  10186. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  10187. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10188. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10189. "#else",
  10190. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  10191. "#endif",
  10192. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  10193. // specular
  10194. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  10195. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10196. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  10197. "#ifdef PHYSICALLY_BASED_SHADING",
  10198. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10199. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10200. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  10201. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  10202. "#else",
  10203. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  10204. "#endif",
  10205. "}",
  10206. "#endif",
  10207. "#if MAX_SPOT_LIGHTS > 0",
  10208. "vec3 spotDiffuse = vec3( 0.0 );",
  10209. "vec3 spotSpecular = vec3( 0.0 );",
  10210. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10211. "#ifdef PHONG_PER_PIXEL",
  10212. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10213. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10214. "float lDistance = 1.0;",
  10215. "if ( spotLightDistance[ i ] > 0.0 )",
  10216. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10217. "lVector = normalize( lVector );",
  10218. "#else",
  10219. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  10220. "float lDistance = vSpotLight[ i ].w;",
  10221. "#endif",
  10222. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10223. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10224. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10225. // diffuse
  10226. "float dotProduct = dot( normal, lVector );",
  10227. "#ifdef WRAP_AROUND",
  10228. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  10229. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10230. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10231. "#else",
  10232. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  10233. "#endif",
  10234. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  10235. // specular
  10236. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  10237. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10238. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  10239. "#ifdef PHYSICALLY_BASED_SHADING",
  10240. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10241. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10242. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  10243. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  10244. "#else",
  10245. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  10246. "#endif",
  10247. "}",
  10248. "}",
  10249. "#endif",
  10250. "#if MAX_DIR_LIGHTS > 0",
  10251. "vec3 dirDiffuse = vec3( 0.0 );",
  10252. "vec3 dirSpecular = vec3( 0.0 );" ,
  10253. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10254. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10255. "vec3 dirVector = normalize( lDirection.xyz );",
  10256. // diffuse
  10257. "float dotProduct = dot( normal, dirVector );",
  10258. "#ifdef WRAP_AROUND",
  10259. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  10260. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10261. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  10262. "#else",
  10263. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  10264. "#endif",
  10265. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  10266. // specular
  10267. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10268. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10269. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  10270. "#ifdef PHYSICALLY_BASED_SHADING",
  10271. /*
  10272. // fresnel term from skin shader
  10273. "const float F0 = 0.128;",
  10274. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  10275. "float exponential = pow( base, 5.0 );",
  10276. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  10277. */
  10278. /*
  10279. // fresnel term from fresnel shader
  10280. "const float mFresnelBias = 0.08;",
  10281. "const float mFresnelScale = 0.3;",
  10282. "const float mFresnelPower = 5.0;",
  10283. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  10284. */
  10285. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10286. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10287. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  10288. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10289. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10290. "#else",
  10291. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  10292. "#endif",
  10293. "}",
  10294. "#endif",
  10295. "#if MAX_HEMI_LIGHTS > 0",
  10296. "vec3 hemiDiffuse = vec3( 0.0 );",
  10297. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10298. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10299. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10300. "vec3 lVector = normalize( lDirection.xyz );",
  10301. // diffuse
  10302. "float dotProduct = dot( normal, lVector );",
  10303. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10304. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10305. "hemiDiffuse += diffuse * hemiColor;",
  10306. // specular (sky light)
  10307. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10308. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10309. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  10310. // specular (ground light)
  10311. "vec3 lVectorGround = -lVector;",
  10312. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10313. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10314. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  10315. "#ifdef PHYSICALLY_BASED_SHADING",
  10316. "float dotProductGround = dot( normal, lVectorGround );",
  10317. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10318. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10319. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10320. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10321. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10322. "#else",
  10323. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  10324. "#endif",
  10325. "}",
  10326. "#endif",
  10327. "vec3 totalDiffuse = vec3( 0.0 );",
  10328. "vec3 totalSpecular = vec3( 0.0 );",
  10329. "#if MAX_DIR_LIGHTS > 0",
  10330. "totalDiffuse += dirDiffuse;",
  10331. "totalSpecular += dirSpecular;",
  10332. "#endif",
  10333. "#if MAX_HEMI_LIGHTS > 0",
  10334. "totalDiffuse += hemiDiffuse;",
  10335. "totalSpecular += hemiSpecular;",
  10336. "#endif",
  10337. "#if MAX_POINT_LIGHTS > 0",
  10338. "totalDiffuse += pointDiffuse;",
  10339. "totalSpecular += pointSpecular;",
  10340. "#endif",
  10341. "#if MAX_SPOT_LIGHTS > 0",
  10342. "totalDiffuse += spotDiffuse;",
  10343. "totalSpecular += spotSpecular;",
  10344. "#endif",
  10345. "#ifdef METAL",
  10346. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  10347. "#else",
  10348. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  10349. "#endif"
  10350. ].join("\n"),
  10351. // VERTEX COLORS
  10352. color_pars_fragment: [
  10353. "#ifdef USE_COLOR",
  10354. "varying vec3 vColor;",
  10355. "#endif"
  10356. ].join("\n"),
  10357. color_fragment: [
  10358. "#ifdef USE_COLOR",
  10359. "gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );",
  10360. "#endif"
  10361. ].join("\n"),
  10362. color_pars_vertex: [
  10363. "#ifdef USE_COLOR",
  10364. "varying vec3 vColor;",
  10365. "#endif"
  10366. ].join("\n"),
  10367. color_vertex: [
  10368. "#ifdef USE_COLOR",
  10369. "#ifdef GAMMA_INPUT",
  10370. "vColor = color * color;",
  10371. "#else",
  10372. "vColor = color;",
  10373. "#endif",
  10374. "#endif"
  10375. ].join("\n"),
  10376. // SKINNING
  10377. skinning_pars_vertex: [
  10378. "#ifdef USE_SKINNING",
  10379. "#ifdef BONE_TEXTURE",
  10380. "uniform sampler2D boneTexture;",
  10381. "uniform int boneTextureWidth;",
  10382. "uniform int boneTextureHeight;",
  10383. "mat4 getBoneMatrix( const in float i ) {",
  10384. "float j = i * 4.0;",
  10385. "float x = mod( j, float( boneTextureWidth ) );",
  10386. "float y = floor( j / float( boneTextureWidth ) );",
  10387. "float dx = 1.0 / float( boneTextureWidth );",
  10388. "float dy = 1.0 / float( boneTextureHeight );",
  10389. "y = dy * ( y + 0.5 );",
  10390. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  10391. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  10392. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  10393. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  10394. "mat4 bone = mat4( v1, v2, v3, v4 );",
  10395. "return bone;",
  10396. "}",
  10397. "#else",
  10398. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  10399. "mat4 getBoneMatrix( const in float i ) {",
  10400. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  10401. "return bone;",
  10402. "}",
  10403. "#endif",
  10404. "#endif"
  10405. ].join("\n"),
  10406. skinbase_vertex: [
  10407. "#ifdef USE_SKINNING",
  10408. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  10409. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  10410. "#endif"
  10411. ].join("\n"),
  10412. skinning_vertex: [
  10413. "#ifdef USE_SKINNING",
  10414. "#ifdef USE_MORPHTARGETS",
  10415. "vec4 skinVertex = vec4( morphed, 1.0 );",
  10416. "#else",
  10417. "vec4 skinVertex = vec4( position, 1.0 );",
  10418. "#endif",
  10419. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10420. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10421. "#endif"
  10422. ].join("\n"),
  10423. // MORPHING
  10424. morphtarget_pars_vertex: [
  10425. "#ifdef USE_MORPHTARGETS",
  10426. "#ifndef USE_MORPHNORMALS",
  10427. "uniform float morphTargetInfluences[ 8 ];",
  10428. "#else",
  10429. "uniform float morphTargetInfluences[ 4 ];",
  10430. "#endif",
  10431. "#endif"
  10432. ].join("\n"),
  10433. morphtarget_vertex: [
  10434. "#ifdef USE_MORPHTARGETS",
  10435. "vec3 morphed = vec3( 0.0 );",
  10436. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  10437. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  10438. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  10439. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  10440. "#ifndef USE_MORPHNORMALS",
  10441. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  10442. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  10443. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  10444. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  10445. "#endif",
  10446. "morphed += position;",
  10447. "#endif"
  10448. ].join("\n"),
  10449. default_vertex : [
  10450. "vec4 mvPosition;",
  10451. "#ifdef USE_SKINNING",
  10452. "mvPosition = modelViewMatrix * skinned;",
  10453. "#endif",
  10454. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  10455. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  10456. "#endif",
  10457. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  10458. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10459. "#endif",
  10460. "gl_Position = projectionMatrix * mvPosition;"
  10461. ].join("\n"),
  10462. morphnormal_vertex: [
  10463. "#ifdef USE_MORPHNORMALS",
  10464. "vec3 morphedNormal = vec3( 0.0 );",
  10465. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  10466. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  10467. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  10468. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  10469. "morphedNormal += normal;",
  10470. "#endif"
  10471. ].join("\n"),
  10472. skinnormal_vertex: [
  10473. "#ifdef USE_SKINNING",
  10474. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  10475. "skinMatrix += skinWeight.y * boneMatY;",
  10476. "#ifdef USE_MORPHNORMALS",
  10477. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  10478. "#else",
  10479. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  10480. "#endif",
  10481. "#endif"
  10482. ].join("\n"),
  10483. defaultnormal_vertex: [
  10484. "vec3 objectNormal;",
  10485. "#ifdef USE_SKINNING",
  10486. "objectNormal = skinnedNormal.xyz;",
  10487. "#endif",
  10488. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  10489. "objectNormal = morphedNormal;",
  10490. "#endif",
  10491. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  10492. "objectNormal = normal;",
  10493. "#endif",
  10494. "#ifdef FLIP_SIDED",
  10495. "objectNormal = -objectNormal;",
  10496. "#endif",
  10497. "vec3 transformedNormal = normalMatrix * objectNormal;"
  10498. ].join("\n"),
  10499. // SHADOW MAP
  10500. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  10501. // http://spidergl.org/example.php?id=6
  10502. // http://fabiensanglard.net/shadowmapping
  10503. shadowmap_pars_fragment: [
  10504. "#ifdef USE_SHADOWMAP",
  10505. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  10506. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  10507. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  10508. "uniform float shadowBias[ MAX_SHADOWS ];",
  10509. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10510. "float unpackDepth( const in vec4 rgba_depth ) {",
  10511. "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 );",
  10512. "float depth = dot( rgba_depth, bit_shift );",
  10513. "return depth;",
  10514. "}",
  10515. "#endif"
  10516. ].join("\n"),
  10517. shadowmap_fragment: [
  10518. "#ifdef USE_SHADOWMAP",
  10519. "#ifdef SHADOWMAP_DEBUG",
  10520. "vec3 frustumColors[3];",
  10521. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  10522. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  10523. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  10524. "#endif",
  10525. "#ifdef SHADOWMAP_CASCADE",
  10526. "int inFrustumCount = 0;",
  10527. "#endif",
  10528. "float fDepth;",
  10529. "vec3 shadowColor = vec3( 1.0 );",
  10530. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10531. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  10532. // "if ( something && something )" breaks ATI OpenGL shader compiler
  10533. // "if ( all( something, something ) )" using this instead
  10534. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  10535. "bool inFrustum = all( inFrustumVec );",
  10536. // don't shadow pixels outside of light frustum
  10537. // use just first frustum (for cascades)
  10538. // don't shadow pixels behind far plane of light frustum
  10539. "#ifdef SHADOWMAP_CASCADE",
  10540. "inFrustumCount += int( inFrustum );",
  10541. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  10542. "#else",
  10543. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  10544. "#endif",
  10545. "bool frustumTest = all( frustumTestVec );",
  10546. "if ( frustumTest ) {",
  10547. "shadowCoord.z += shadowBias[ i ];",
  10548. "#if defined( SHADOWMAP_TYPE_PCF )",
  10549. // Percentage-close filtering
  10550. // (9 pixel kernel)
  10551. // http://fabiensanglard.net/shadowmappingPCF/
  10552. "float shadow = 0.0;",
  10553. /*
  10554. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  10555. // must enroll loop manually
  10556. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  10557. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  10558. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  10559. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  10560. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  10561. "float fDepth = unpackDepth( rgbaDepth );",
  10562. "if ( fDepth < shadowCoord.z )",
  10563. "shadow += 1.0;",
  10564. "}",
  10565. "shadow /= 9.0;",
  10566. */
  10567. "const float shadowDelta = 1.0 / 9.0;",
  10568. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10569. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10570. "float dx0 = -1.25 * xPixelOffset;",
  10571. "float dy0 = -1.25 * yPixelOffset;",
  10572. "float dx1 = 1.25 * xPixelOffset;",
  10573. "float dy1 = 1.25 * yPixelOffset;",
  10574. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10575. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10576. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10577. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10578. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10579. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10580. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10581. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10582. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10583. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10584. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10585. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10586. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10587. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10588. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10589. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10590. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10591. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10592. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10593. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  10594. // Percentage-close filtering
  10595. // (9 pixel kernel)
  10596. // http://fabiensanglard.net/shadowmappingPCF/
  10597. "float shadow = 0.0;",
  10598. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10599. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10600. "float dx0 = -1.0 * xPixelOffset;",
  10601. "float dy0 = -1.0 * yPixelOffset;",
  10602. "float dx1 = 1.0 * xPixelOffset;",
  10603. "float dy1 = 1.0 * yPixelOffset;",
  10604. "mat3 shadowKernel;",
  10605. "mat3 depthKernel;",
  10606. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10607. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10608. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10609. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10610. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10611. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10612. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10613. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10614. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10615. "vec3 shadowZ = vec3( shadowCoord.z );",
  10616. "shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  10617. "shadowKernel[0] *= vec3(0.25);",
  10618. "shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  10619. "shadowKernel[1] *= vec3(0.25);",
  10620. "shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  10621. "shadowKernel[2] *= vec3(0.25);",
  10622. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  10623. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  10624. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  10625. "vec4 shadowValues;",
  10626. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  10627. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  10628. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  10629. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  10630. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  10631. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10632. "#else",
  10633. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  10634. "float fDepth = unpackDepth( rgbaDepth );",
  10635. "if ( fDepth < shadowCoord.z )",
  10636. // spot with multiple shadows is darker
  10637. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  10638. // spot with multiple shadows has the same color as single shadow spot
  10639. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  10640. "#endif",
  10641. "}",
  10642. "#ifdef SHADOWMAP_DEBUG",
  10643. "#ifdef SHADOWMAP_CASCADE",
  10644. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  10645. "#else",
  10646. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  10647. "#endif",
  10648. "#endif",
  10649. "}",
  10650. "#ifdef GAMMA_OUTPUT",
  10651. "shadowColor *= shadowColor;",
  10652. "#endif",
  10653. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  10654. "#endif"
  10655. ].join("\n"),
  10656. shadowmap_pars_vertex: [
  10657. "#ifdef USE_SHADOWMAP",
  10658. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10659. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  10660. "#endif"
  10661. ].join("\n"),
  10662. shadowmap_vertex: [
  10663. "#ifdef USE_SHADOWMAP",
  10664. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10665. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10666. "}",
  10667. "#endif"
  10668. ].join("\n"),
  10669. // ALPHATEST
  10670. alphatest_fragment: [
  10671. "#ifdef ALPHATEST",
  10672. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  10673. "#endif"
  10674. ].join("\n"),
  10675. // LINEAR SPACE
  10676. linear_to_gamma_fragment: [
  10677. "#ifdef GAMMA_OUTPUT",
  10678. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  10679. "#endif"
  10680. ].join("\n")
  10681. };
  10682. THREE.UniformsUtils = {
  10683. merge: function ( uniforms ) {
  10684. var u, p, tmp, merged = {};
  10685. for ( u = 0; u < uniforms.length; u ++ ) {
  10686. tmp = this.clone( uniforms[ u ] );
  10687. for ( p in tmp ) {
  10688. merged[ p ] = tmp[ p ];
  10689. }
  10690. }
  10691. return merged;
  10692. },
  10693. clone: function ( uniforms_src ) {
  10694. var u, p, parameter, parameter_src, uniforms_dst = {};
  10695. for ( u in uniforms_src ) {
  10696. uniforms_dst[ u ] = {};
  10697. for ( p in uniforms_src[ u ] ) {
  10698. parameter_src = uniforms_src[ u ][ p ];
  10699. if ( parameter_src instanceof THREE.Color ||
  10700. parameter_src instanceof THREE.Vector2 ||
  10701. parameter_src instanceof THREE.Vector3 ||
  10702. parameter_src instanceof THREE.Vector4 ||
  10703. parameter_src instanceof THREE.Matrix4 ||
  10704. parameter_src instanceof THREE.Texture ) {
  10705. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10706. } else if ( parameter_src instanceof Array ) {
  10707. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10708. } else {
  10709. uniforms_dst[ u ][ p ] = parameter_src;
  10710. }
  10711. }
  10712. }
  10713. return uniforms_dst;
  10714. }
  10715. };
  10716. THREE.UniformsLib = {
  10717. common: {
  10718. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10719. "opacity" : { type: "f", value: 1.0 },
  10720. "map" : { type: "t", value: null },
  10721. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10722. "lightMap" : { type: "t", value: null },
  10723. "specularMap" : { type: "t", value: null },
  10724. "envMap" : { type: "t", value: null },
  10725. "flipEnvMap" : { type: "f", value: -1 },
  10726. "useRefract" : { type: "i", value: 0 },
  10727. "reflectivity" : { type: "f", value: 1.0 },
  10728. "refractionRatio" : { type: "f", value: 0.98 },
  10729. "combine" : { type: "i", value: 0 },
  10730. "morphTargetInfluences" : { type: "f", value: 0 }
  10731. },
  10732. bump: {
  10733. "bumpMap" : { type: "t", value: null },
  10734. "bumpScale" : { type: "f", value: 1 }
  10735. },
  10736. normalmap: {
  10737. "normalMap" : { type: "t", value: null },
  10738. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10739. },
  10740. fog : {
  10741. "fogDensity" : { type: "f", value: 0.00025 },
  10742. "fogNear" : { type: "f", value: 1 },
  10743. "fogFar" : { type: "f", value: 2000 },
  10744. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10745. },
  10746. lights: {
  10747. "ambientLightColor" : { type: "fv", value: [] },
  10748. "directionalLightDirection" : { type: "fv", value: [] },
  10749. "directionalLightColor" : { type: "fv", value: [] },
  10750. "hemisphereLightDirection" : { type: "fv", value: [] },
  10751. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10752. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10753. "pointLightColor" : { type: "fv", value: [] },
  10754. "pointLightPosition" : { type: "fv", value: [] },
  10755. "pointLightDistance" : { type: "fv1", value: [] },
  10756. "spotLightColor" : { type: "fv", value: [] },
  10757. "spotLightPosition" : { type: "fv", value: [] },
  10758. "spotLightDirection" : { type: "fv", value: [] },
  10759. "spotLightDistance" : { type: "fv1", value: [] },
  10760. "spotLightAngleCos" : { type: "fv1", value: [] },
  10761. "spotLightExponent" : { type: "fv1", value: [] }
  10762. },
  10763. particle: {
  10764. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10765. "opacity" : { type: "f", value: 1.0 },
  10766. "size" : { type: "f", value: 1.0 },
  10767. "scale" : { type: "f", value: 1.0 },
  10768. "map" : { type: "t", value: null },
  10769. "fogDensity" : { type: "f", value: 0.00025 },
  10770. "fogNear" : { type: "f", value: 1 },
  10771. "fogFar" : { type: "f", value: 2000 },
  10772. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10773. },
  10774. shadowmap: {
  10775. "shadowMap": { type: "tv", value: [] },
  10776. "shadowMapSize": { type: "v2v", value: [] },
  10777. "shadowBias" : { type: "fv1", value: [] },
  10778. "shadowDarkness": { type: "fv1", value: [] },
  10779. "shadowMatrix" : { type: "m4v", value: [] }
  10780. }
  10781. };
  10782. THREE.ShaderLib = {
  10783. 'basic': {
  10784. uniforms: THREE.UniformsUtils.merge( [
  10785. THREE.UniformsLib[ "common" ],
  10786. THREE.UniformsLib[ "fog" ],
  10787. THREE.UniformsLib[ "shadowmap" ]
  10788. ] ),
  10789. vertexShader: [
  10790. THREE.ShaderChunk[ "map_pars_vertex" ],
  10791. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10792. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10793. THREE.ShaderChunk[ "color_pars_vertex" ],
  10794. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10795. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10796. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10797. "void main() {",
  10798. THREE.ShaderChunk[ "map_vertex" ],
  10799. THREE.ShaderChunk[ "lightmap_vertex" ],
  10800. THREE.ShaderChunk[ "color_vertex" ],
  10801. THREE.ShaderChunk[ "skinbase_vertex" ],
  10802. "#ifdef USE_ENVMAP",
  10803. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10804. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10805. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10806. "#endif",
  10807. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10808. THREE.ShaderChunk[ "skinning_vertex" ],
  10809. THREE.ShaderChunk[ "default_vertex" ],
  10810. THREE.ShaderChunk[ "worldpos_vertex" ],
  10811. THREE.ShaderChunk[ "envmap_vertex" ],
  10812. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10813. "}"
  10814. ].join("\n"),
  10815. fragmentShader: [
  10816. "uniform vec3 diffuse;",
  10817. "uniform float opacity;",
  10818. THREE.ShaderChunk[ "color_pars_fragment" ],
  10819. THREE.ShaderChunk[ "map_pars_fragment" ],
  10820. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10821. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10822. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10823. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10824. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10825. "void main() {",
  10826. "gl_FragColor = vec4( diffuse, opacity );",
  10827. THREE.ShaderChunk[ "map_fragment" ],
  10828. THREE.ShaderChunk[ "alphatest_fragment" ],
  10829. THREE.ShaderChunk[ "specularmap_fragment" ],
  10830. THREE.ShaderChunk[ "lightmap_fragment" ],
  10831. THREE.ShaderChunk[ "color_fragment" ],
  10832. THREE.ShaderChunk[ "envmap_fragment" ],
  10833. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10834. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10835. THREE.ShaderChunk[ "fog_fragment" ],
  10836. "}"
  10837. ].join("\n")
  10838. },
  10839. 'lambert': {
  10840. uniforms: THREE.UniformsUtils.merge( [
  10841. THREE.UniformsLib[ "common" ],
  10842. THREE.UniformsLib[ "fog" ],
  10843. THREE.UniformsLib[ "lights" ],
  10844. THREE.UniformsLib[ "shadowmap" ],
  10845. {
  10846. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10847. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10848. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10849. }
  10850. ] ),
  10851. vertexShader: [
  10852. "#define LAMBERT",
  10853. "varying vec3 vLightFront;",
  10854. "#ifdef DOUBLE_SIDED",
  10855. "varying vec3 vLightBack;",
  10856. "#endif",
  10857. THREE.ShaderChunk[ "map_pars_vertex" ],
  10858. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10859. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10860. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10861. THREE.ShaderChunk[ "color_pars_vertex" ],
  10862. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10863. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10864. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10865. "void main() {",
  10866. THREE.ShaderChunk[ "map_vertex" ],
  10867. THREE.ShaderChunk[ "lightmap_vertex" ],
  10868. THREE.ShaderChunk[ "color_vertex" ],
  10869. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10870. THREE.ShaderChunk[ "skinbase_vertex" ],
  10871. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10872. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10873. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10874. THREE.ShaderChunk[ "skinning_vertex" ],
  10875. THREE.ShaderChunk[ "default_vertex" ],
  10876. THREE.ShaderChunk[ "worldpos_vertex" ],
  10877. THREE.ShaderChunk[ "envmap_vertex" ],
  10878. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10879. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10880. "}"
  10881. ].join("\n"),
  10882. fragmentShader: [
  10883. "uniform float opacity;",
  10884. "varying vec3 vLightFront;",
  10885. "#ifdef DOUBLE_SIDED",
  10886. "varying vec3 vLightBack;",
  10887. "#endif",
  10888. THREE.ShaderChunk[ "color_pars_fragment" ],
  10889. THREE.ShaderChunk[ "map_pars_fragment" ],
  10890. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10891. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10892. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10893. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10894. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10895. "void main() {",
  10896. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10897. THREE.ShaderChunk[ "map_fragment" ],
  10898. THREE.ShaderChunk[ "alphatest_fragment" ],
  10899. THREE.ShaderChunk[ "specularmap_fragment" ],
  10900. "#ifdef DOUBLE_SIDED",
  10901. //"float isFront = float( gl_FrontFacing );",
  10902. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10903. "if ( gl_FrontFacing )",
  10904. "gl_FragColor.xyz *= vLightFront;",
  10905. "else",
  10906. "gl_FragColor.xyz *= vLightBack;",
  10907. "#else",
  10908. "gl_FragColor.xyz *= vLightFront;",
  10909. "#endif",
  10910. THREE.ShaderChunk[ "lightmap_fragment" ],
  10911. THREE.ShaderChunk[ "color_fragment" ],
  10912. THREE.ShaderChunk[ "envmap_fragment" ],
  10913. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10914. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10915. THREE.ShaderChunk[ "fog_fragment" ],
  10916. "}"
  10917. ].join("\n")
  10918. },
  10919. 'phong': {
  10920. uniforms: THREE.UniformsUtils.merge( [
  10921. THREE.UniformsLib[ "common" ],
  10922. THREE.UniformsLib[ "bump" ],
  10923. THREE.UniformsLib[ "normalmap" ],
  10924. THREE.UniformsLib[ "fog" ],
  10925. THREE.UniformsLib[ "lights" ],
  10926. THREE.UniformsLib[ "shadowmap" ],
  10927. {
  10928. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10929. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10930. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10931. "shininess": { type: "f", value: 30 },
  10932. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10933. }
  10934. ] ),
  10935. vertexShader: [
  10936. "#define PHONG",
  10937. "varying vec3 vViewPosition;",
  10938. "varying vec3 vNormal;",
  10939. THREE.ShaderChunk[ "map_pars_vertex" ],
  10940. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10941. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10942. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10943. THREE.ShaderChunk[ "color_pars_vertex" ],
  10944. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10945. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10946. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10947. "void main() {",
  10948. THREE.ShaderChunk[ "map_vertex" ],
  10949. THREE.ShaderChunk[ "lightmap_vertex" ],
  10950. THREE.ShaderChunk[ "color_vertex" ],
  10951. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10952. THREE.ShaderChunk[ "skinbase_vertex" ],
  10953. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10954. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10955. "vNormal = normalize( transformedNormal );",
  10956. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10957. THREE.ShaderChunk[ "skinning_vertex" ],
  10958. THREE.ShaderChunk[ "default_vertex" ],
  10959. "vViewPosition = -mvPosition.xyz;",
  10960. THREE.ShaderChunk[ "worldpos_vertex" ],
  10961. THREE.ShaderChunk[ "envmap_vertex" ],
  10962. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10963. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10964. "}"
  10965. ].join("\n"),
  10966. fragmentShader: [
  10967. "uniform vec3 diffuse;",
  10968. "uniform float opacity;",
  10969. "uniform vec3 ambient;",
  10970. "uniform vec3 emissive;",
  10971. "uniform vec3 specular;",
  10972. "uniform float shininess;",
  10973. THREE.ShaderChunk[ "color_pars_fragment" ],
  10974. THREE.ShaderChunk[ "map_pars_fragment" ],
  10975. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10976. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10977. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10978. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10979. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10980. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10981. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10982. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10983. "void main() {",
  10984. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10985. THREE.ShaderChunk[ "map_fragment" ],
  10986. THREE.ShaderChunk[ "alphatest_fragment" ],
  10987. THREE.ShaderChunk[ "specularmap_fragment" ],
  10988. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10989. THREE.ShaderChunk[ "lightmap_fragment" ],
  10990. THREE.ShaderChunk[ "color_fragment" ],
  10991. THREE.ShaderChunk[ "envmap_fragment" ],
  10992. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10993. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10994. THREE.ShaderChunk[ "fog_fragment" ],
  10995. "}"
  10996. ].join("\n")
  10997. },
  10998. 'particle_basic': {
  10999. uniforms: THREE.UniformsUtils.merge( [
  11000. THREE.UniformsLib[ "particle" ],
  11001. THREE.UniformsLib[ "shadowmap" ]
  11002. ] ),
  11003. vertexShader: [
  11004. "uniform float size;",
  11005. "uniform float scale;",
  11006. THREE.ShaderChunk[ "color_pars_vertex" ],
  11007. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11008. "void main() {",
  11009. THREE.ShaderChunk[ "color_vertex" ],
  11010. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11011. "#ifdef USE_SIZEATTENUATION",
  11012. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  11013. "#else",
  11014. "gl_PointSize = size;",
  11015. "#endif",
  11016. "gl_Position = projectionMatrix * mvPosition;",
  11017. THREE.ShaderChunk[ "worldpos_vertex" ],
  11018. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11019. "}"
  11020. ].join("\n"),
  11021. fragmentShader: [
  11022. "uniform vec3 psColor;",
  11023. "uniform float opacity;",
  11024. THREE.ShaderChunk[ "color_pars_fragment" ],
  11025. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  11026. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11027. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11028. "void main() {",
  11029. "gl_FragColor = vec4( psColor, opacity );",
  11030. THREE.ShaderChunk[ "map_particle_fragment" ],
  11031. THREE.ShaderChunk[ "alphatest_fragment" ],
  11032. THREE.ShaderChunk[ "color_fragment" ],
  11033. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11034. THREE.ShaderChunk[ "fog_fragment" ],
  11035. "}"
  11036. ].join("\n")
  11037. },
  11038. 'dashed': {
  11039. uniforms: THREE.UniformsUtils.merge( [
  11040. THREE.UniformsLib[ "common" ],
  11041. THREE.UniformsLib[ "fog" ],
  11042. {
  11043. "scale": { type: "f", value: 1 },
  11044. "dashSize": { type: "f", value: 1 },
  11045. "totalSize": { type: "f", value: 2 }
  11046. }
  11047. ] ),
  11048. vertexShader: [
  11049. "uniform float scale;",
  11050. "attribute float lineDistance;",
  11051. "varying float vLineDistance;",
  11052. THREE.ShaderChunk[ "color_pars_vertex" ],
  11053. "void main() {",
  11054. THREE.ShaderChunk[ "color_vertex" ],
  11055. "vLineDistance = scale * lineDistance;",
  11056. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11057. "gl_Position = projectionMatrix * mvPosition;",
  11058. "}"
  11059. ].join("\n"),
  11060. fragmentShader: [
  11061. "uniform vec3 diffuse;",
  11062. "uniform float opacity;",
  11063. "uniform float dashSize;",
  11064. "uniform float totalSize;",
  11065. "varying float vLineDistance;",
  11066. THREE.ShaderChunk[ "color_pars_fragment" ],
  11067. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11068. "void main() {",
  11069. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  11070. "discard;",
  11071. "}",
  11072. "gl_FragColor = vec4( diffuse, opacity );",
  11073. THREE.ShaderChunk[ "color_fragment" ],
  11074. THREE.ShaderChunk[ "fog_fragment" ],
  11075. "}"
  11076. ].join("\n")
  11077. },
  11078. 'depth': {
  11079. uniforms: {
  11080. "mNear": { type: "f", value: 1.0 },
  11081. "mFar" : { type: "f", value: 2000.0 },
  11082. "opacity" : { type: "f", value: 1.0 }
  11083. },
  11084. vertexShader: [
  11085. "void main() {",
  11086. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11087. "}"
  11088. ].join("\n"),
  11089. fragmentShader: [
  11090. "uniform float mNear;",
  11091. "uniform float mFar;",
  11092. "uniform float opacity;",
  11093. "void main() {",
  11094. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  11095. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  11096. "gl_FragColor = vec4( vec3( color ), opacity );",
  11097. "}"
  11098. ].join("\n")
  11099. },
  11100. 'normal': {
  11101. uniforms: {
  11102. "opacity" : { type: "f", value: 1.0 }
  11103. },
  11104. vertexShader: [
  11105. "varying vec3 vNormal;",
  11106. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11107. "void main() {",
  11108. "vNormal = normalize( normalMatrix * normal );",
  11109. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11110. THREE.ShaderChunk[ "default_vertex" ],
  11111. "}"
  11112. ].join("\n"),
  11113. fragmentShader: [
  11114. "uniform float opacity;",
  11115. "varying vec3 vNormal;",
  11116. "void main() {",
  11117. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  11118. "}"
  11119. ].join("\n")
  11120. },
  11121. /* -------------------------------------------------------------------------
  11122. // Normal map shader
  11123. // - Blinn-Phong
  11124. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  11125. // - point and directional lights (use with "lights: true" material option)
  11126. ------------------------------------------------------------------------- */
  11127. 'normalmap' : {
  11128. uniforms: THREE.UniformsUtils.merge( [
  11129. THREE.UniformsLib[ "fog" ],
  11130. THREE.UniformsLib[ "lights" ],
  11131. THREE.UniformsLib[ "shadowmap" ],
  11132. {
  11133. "enableAO" : { type: "i", value: 0 },
  11134. "enableDiffuse" : { type: "i", value: 0 },
  11135. "enableSpecular" : { type: "i", value: 0 },
  11136. "enableReflection": { type: "i", value: 0 },
  11137. "enableDisplacement": { type: "i", value: 0 },
  11138. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  11139. "tDiffuse" : { type: "t", value: null },
  11140. "tCube" : { type: "t", value: null },
  11141. "tNormal" : { type: "t", value: null },
  11142. "tSpecular" : { type: "t", value: null },
  11143. "tAO" : { type: "t", value: null },
  11144. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11145. "uDisplacementBias": { type: "f", value: 0.0 },
  11146. "uDisplacementScale": { type: "f", value: 1.0 },
  11147. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11148. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  11149. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11150. "uShininess": { type: "f", value: 30 },
  11151. "uOpacity": { type: "f", value: 1 },
  11152. "useRefract": { type: "i", value: 0 },
  11153. "uRefractionRatio": { type: "f", value: 0.98 },
  11154. "uReflectivity": { type: "f", value: 0.5 },
  11155. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11156. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11157. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11158. }
  11159. ] ),
  11160. fragmentShader: [
  11161. "uniform vec3 uAmbientColor;",
  11162. "uniform vec3 uDiffuseColor;",
  11163. "uniform vec3 uSpecularColor;",
  11164. "uniform float uShininess;",
  11165. "uniform float uOpacity;",
  11166. "uniform bool enableDiffuse;",
  11167. "uniform bool enableSpecular;",
  11168. "uniform bool enableAO;",
  11169. "uniform bool enableReflection;",
  11170. "uniform sampler2D tDiffuse;",
  11171. "uniform sampler2D tNormal;",
  11172. "uniform sampler2D tSpecular;",
  11173. "uniform sampler2D tAO;",
  11174. "uniform samplerCube tCube;",
  11175. "uniform vec2 uNormalScale;",
  11176. "uniform bool useRefract;",
  11177. "uniform float uRefractionRatio;",
  11178. "uniform float uReflectivity;",
  11179. "varying vec3 vTangent;",
  11180. "varying vec3 vBinormal;",
  11181. "varying vec3 vNormal;",
  11182. "varying vec2 vUv;",
  11183. "uniform vec3 ambientLightColor;",
  11184. "#if MAX_DIR_LIGHTS > 0",
  11185. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11186. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11187. "#endif",
  11188. "#if MAX_HEMI_LIGHTS > 0",
  11189. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11190. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11191. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11192. "#endif",
  11193. "#if MAX_POINT_LIGHTS > 0",
  11194. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11195. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11196. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11197. "#endif",
  11198. "#if MAX_SPOT_LIGHTS > 0",
  11199. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11200. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11201. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11202. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11203. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11204. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11205. "#endif",
  11206. "#ifdef WRAP_AROUND",
  11207. "uniform vec3 wrapRGB;",
  11208. "#endif",
  11209. "varying vec3 vWorldPosition;",
  11210. "varying vec3 vViewPosition;",
  11211. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11212. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11213. "void main() {",
  11214. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  11215. "vec3 specularTex = vec3( 1.0 );",
  11216. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11217. "normalTex.xy *= uNormalScale;",
  11218. "normalTex = normalize( normalTex );",
  11219. "if( enableDiffuse ) {",
  11220. "#ifdef GAMMA_INPUT",
  11221. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  11222. "texelColor.xyz *= texelColor.xyz;",
  11223. "gl_FragColor = gl_FragColor * texelColor;",
  11224. "#else",
  11225. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11226. "#endif",
  11227. "}",
  11228. "if( enableAO ) {",
  11229. "#ifdef GAMMA_INPUT",
  11230. "vec4 aoColor = texture2D( tAO, vUv );",
  11231. "aoColor.xyz *= aoColor.xyz;",
  11232. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11233. "#else",
  11234. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11235. "#endif",
  11236. "}",
  11237. "if( enableSpecular )",
  11238. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  11239. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11240. "vec3 finalNormal = tsb * normalTex;",
  11241. "#ifdef FLIP_SIDED",
  11242. "finalNormal = -finalNormal;",
  11243. "#endif",
  11244. "vec3 normal = normalize( finalNormal );",
  11245. "vec3 viewPosition = normalize( vViewPosition );",
  11246. // point lights
  11247. "#if MAX_POINT_LIGHTS > 0",
  11248. "vec3 pointDiffuse = vec3( 0.0 );",
  11249. "vec3 pointSpecular = vec3( 0.0 );",
  11250. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11251. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11252. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  11253. "float pointDistance = 1.0;",
  11254. "if ( pointLightDistance[ i ] > 0.0 )",
  11255. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  11256. "pointVector = normalize( pointVector );",
  11257. // diffuse
  11258. "#ifdef WRAP_AROUND",
  11259. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11260. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11261. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11262. "#else",
  11263. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11264. "#endif",
  11265. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  11266. // specular
  11267. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11268. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11269. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  11270. "#ifdef PHYSICALLY_BASED_SHADING",
  11271. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11272. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11273. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11274. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11275. "#else",
  11276. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  11277. "#endif",
  11278. "}",
  11279. "#endif",
  11280. // spot lights
  11281. "#if MAX_SPOT_LIGHTS > 0",
  11282. "vec3 spotDiffuse = vec3( 0.0 );",
  11283. "vec3 spotSpecular = vec3( 0.0 );",
  11284. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11285. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11286. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  11287. "float spotDistance = 1.0;",
  11288. "if ( spotLightDistance[ i ] > 0.0 )",
  11289. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  11290. "spotVector = normalize( spotVector );",
  11291. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11292. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11293. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11294. // diffuse
  11295. "#ifdef WRAP_AROUND",
  11296. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  11297. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  11298. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11299. "#else",
  11300. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  11301. "#endif",
  11302. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  11303. // specular
  11304. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  11305. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11306. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  11307. "#ifdef PHYSICALLY_BASED_SHADING",
  11308. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11309. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11310. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  11311. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  11312. "#else",
  11313. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  11314. "#endif",
  11315. "}",
  11316. "}",
  11317. "#endif",
  11318. // directional lights
  11319. "#if MAX_DIR_LIGHTS > 0",
  11320. "vec3 dirDiffuse = vec3( 0.0 );",
  11321. "vec3 dirSpecular = vec3( 0.0 );",
  11322. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11323. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11324. "vec3 dirVector = normalize( lDirection.xyz );",
  11325. // diffuse
  11326. "#ifdef WRAP_AROUND",
  11327. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11328. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11329. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11330. "#else",
  11331. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11332. "#endif",
  11333. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  11334. // specular
  11335. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11336. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11337. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  11338. "#ifdef PHYSICALLY_BASED_SHADING",
  11339. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11340. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11341. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11342. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11343. "#else",
  11344. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  11345. "#endif",
  11346. "}",
  11347. "#endif",
  11348. // hemisphere lights
  11349. "#if MAX_HEMI_LIGHTS > 0",
  11350. "vec3 hemiDiffuse = vec3( 0.0 );",
  11351. "vec3 hemiSpecular = vec3( 0.0 );" ,
  11352. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11353. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11354. "vec3 lVector = normalize( lDirection.xyz );",
  11355. // diffuse
  11356. "float dotProduct = dot( normal, lVector );",
  11357. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11358. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11359. "hemiDiffuse += uDiffuseColor * hemiColor;",
  11360. // specular (sky light)
  11361. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11362. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11363. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  11364. // specular (ground light)
  11365. "vec3 lVectorGround = -lVector;",
  11366. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11367. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11368. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  11369. "#ifdef PHYSICALLY_BASED_SHADING",
  11370. "float dotProductGround = dot( normal, lVectorGround );",
  11371. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11372. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11373. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  11374. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  11375. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11376. "#else",
  11377. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  11378. "#endif",
  11379. "}",
  11380. "#endif",
  11381. // all lights contribution summation
  11382. "vec3 totalDiffuse = vec3( 0.0 );",
  11383. "vec3 totalSpecular = vec3( 0.0 );",
  11384. "#if MAX_DIR_LIGHTS > 0",
  11385. "totalDiffuse += dirDiffuse;",
  11386. "totalSpecular += dirSpecular;",
  11387. "#endif",
  11388. "#if MAX_HEMI_LIGHTS > 0",
  11389. "totalDiffuse += hemiDiffuse;",
  11390. "totalSpecular += hemiSpecular;",
  11391. "#endif",
  11392. "#if MAX_POINT_LIGHTS > 0",
  11393. "totalDiffuse += pointDiffuse;",
  11394. "totalSpecular += pointSpecular;",
  11395. "#endif",
  11396. "#if MAX_SPOT_LIGHTS > 0",
  11397. "totalDiffuse += spotDiffuse;",
  11398. "totalSpecular += spotSpecular;",
  11399. "#endif",
  11400. "#ifdef METAL",
  11401. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  11402. "#else",
  11403. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  11404. "#endif",
  11405. "if ( enableReflection ) {",
  11406. "vec3 vReflect;",
  11407. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  11408. "if ( useRefract ) {",
  11409. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  11410. "} else {",
  11411. "vReflect = reflect( cameraToVertex, normal );",
  11412. "}",
  11413. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11414. "#ifdef GAMMA_INPUT",
  11415. "cubeColor.xyz *= cubeColor.xyz;",
  11416. "#endif",
  11417. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  11418. "}",
  11419. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11420. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11421. THREE.ShaderChunk[ "fog_fragment" ],
  11422. "}"
  11423. ].join("\n"),
  11424. vertexShader: [
  11425. "attribute vec4 tangent;",
  11426. "uniform vec2 uOffset;",
  11427. "uniform vec2 uRepeat;",
  11428. "uniform bool enableDisplacement;",
  11429. "#ifdef VERTEX_TEXTURES",
  11430. "uniform sampler2D tDisplacement;",
  11431. "uniform float uDisplacementScale;",
  11432. "uniform float uDisplacementBias;",
  11433. "#endif",
  11434. "varying vec3 vTangent;",
  11435. "varying vec3 vBinormal;",
  11436. "varying vec3 vNormal;",
  11437. "varying vec2 vUv;",
  11438. "varying vec3 vWorldPosition;",
  11439. "varying vec3 vViewPosition;",
  11440. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11441. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11442. "void main() {",
  11443. THREE.ShaderChunk[ "skinbase_vertex" ],
  11444. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11445. // normal, tangent and binormal vectors
  11446. "#ifdef USE_SKINNING",
  11447. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  11448. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  11449. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  11450. "#else",
  11451. "vNormal = normalize( normalMatrix * normal );",
  11452. "vTangent = normalize( normalMatrix * tangent.xyz );",
  11453. "#endif",
  11454. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  11455. "vUv = uv * uRepeat + uOffset;",
  11456. // displacement mapping
  11457. "vec3 displacedPosition;",
  11458. "#ifdef VERTEX_TEXTURES",
  11459. "if ( enableDisplacement ) {",
  11460. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11461. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11462. "displacedPosition = position + normalize( normal ) * df;",
  11463. "} else {",
  11464. "#ifdef USE_SKINNING",
  11465. "vec4 skinVertex = vec4( position, 1.0 );",
  11466. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11467. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11468. "displacedPosition = skinned.xyz;",
  11469. "#else",
  11470. "displacedPosition = position;",
  11471. "#endif",
  11472. "}",
  11473. "#else",
  11474. "#ifdef USE_SKINNING",
  11475. "vec4 skinVertex = vec4( position, 1.0 );",
  11476. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11477. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11478. "displacedPosition = skinned.xyz;",
  11479. "#else",
  11480. "displacedPosition = position;",
  11481. "#endif",
  11482. "#endif",
  11483. //
  11484. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  11485. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  11486. "gl_Position = projectionMatrix * mvPosition;",
  11487. //
  11488. "vWorldPosition = worldPosition.xyz;",
  11489. "vViewPosition = -mvPosition.xyz;",
  11490. // shadows
  11491. "#ifdef USE_SHADOWMAP",
  11492. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11493. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11494. "}",
  11495. "#endif",
  11496. "}"
  11497. ].join("\n")
  11498. },
  11499. /* -------------------------------------------------------------------------
  11500. // Cube map shader
  11501. ------------------------------------------------------------------------- */
  11502. 'cube': {
  11503. uniforms: { "tCube": { type: "t", value: null },
  11504. "tFlip": { type: "f", value: -1 } },
  11505. vertexShader: [
  11506. "varying vec3 vWorldPosition;",
  11507. "void main() {",
  11508. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  11509. "vWorldPosition = worldPosition.xyz;",
  11510. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11511. "}"
  11512. ].join("\n"),
  11513. fragmentShader: [
  11514. "uniform samplerCube tCube;",
  11515. "uniform float tFlip;",
  11516. "varying vec3 vWorldPosition;",
  11517. "void main() {",
  11518. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11519. "}"
  11520. ].join("\n")
  11521. },
  11522. // Depth encoding into RGBA texture
  11523. // based on SpiderGL shadow map example
  11524. // http://spidergl.org/example.php?id=6
  11525. // originally from
  11526. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11527. // see also here:
  11528. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11529. 'depthRGBA': {
  11530. uniforms: {},
  11531. vertexShader: [
  11532. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11533. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11534. "void main() {",
  11535. THREE.ShaderChunk[ "skinbase_vertex" ],
  11536. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11537. THREE.ShaderChunk[ "skinning_vertex" ],
  11538. THREE.ShaderChunk[ "default_vertex" ],
  11539. "}"
  11540. ].join("\n"),
  11541. fragmentShader: [
  11542. "vec4 pack_depth( const in float depth ) {",
  11543. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11544. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11545. "vec4 res = fract( depth * bit_shift );",
  11546. "res -= res.xxyz * bit_mask;",
  11547. "return res;",
  11548. "}",
  11549. "void main() {",
  11550. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  11551. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  11552. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  11553. //"gl_FragData[ 0 ] = pack_depth( z );",
  11554. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  11555. "}"
  11556. ].join("\n")
  11557. }
  11558. };
  11559. /**
  11560. * @author supereggbert / http://www.paulbrunt.co.uk/
  11561. * @author mrdoob / http://mrdoob.com/
  11562. * @author alteredq / http://alteredqualia.com/
  11563. * @author szimek / https://github.com/szimek/
  11564. */
  11565. THREE.WebGLRenderer = function ( parameters ) {
  11566. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  11567. parameters = parameters || {};
  11568. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11569. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  11570. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11571. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11572. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11573. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11574. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  11575. _clearColor = new THREE.Color( 0x000000 ),
  11576. _clearAlpha = 0;
  11577. // public properties
  11578. this.domElement = _canvas;
  11579. this.context = null;
  11580. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  11581. ? parameters.devicePixelRatio
  11582. : self.devicePixelRatio !== undefined
  11583. ? self.devicePixelRatio
  11584. : 1;
  11585. // clearing
  11586. this.autoClear = true;
  11587. this.autoClearColor = true;
  11588. this.autoClearDepth = true;
  11589. this.autoClearStencil = true;
  11590. // scene graph
  11591. this.sortObjects = true;
  11592. this.autoUpdateObjects = true;
  11593. // physically based shading
  11594. this.gammaInput = false;
  11595. this.gammaOutput = false;
  11596. this.physicallyBasedShading = false;
  11597. // shadow map
  11598. this.shadowMapEnabled = false;
  11599. this.shadowMapAutoUpdate = true;
  11600. this.shadowMapType = THREE.PCFShadowMap;
  11601. this.shadowMapCullFace = THREE.CullFaceFront;
  11602. this.shadowMapDebug = false;
  11603. this.shadowMapCascade = false;
  11604. // morphs
  11605. this.maxMorphTargets = 8;
  11606. this.maxMorphNormals = 4;
  11607. // flags
  11608. this.autoScaleCubemaps = true;
  11609. // custom render plugins
  11610. this.renderPluginsPre = [];
  11611. this.renderPluginsPost = [];
  11612. // info
  11613. this.info = {
  11614. memory: {
  11615. programs: 0,
  11616. geometries: 0,
  11617. textures: 0
  11618. },
  11619. render: {
  11620. calls: 0,
  11621. vertices: 0,
  11622. faces: 0,
  11623. points: 0
  11624. }
  11625. };
  11626. // internal properties
  11627. var _this = this,
  11628. _programs = [],
  11629. _programs_counter = 0,
  11630. // internal state cache
  11631. _currentProgram = null,
  11632. _currentFramebuffer = null,
  11633. _currentMaterialId = -1,
  11634. _currentGeometryGroupHash = null,
  11635. _currentCamera = null,
  11636. _geometryGroupCounter = 0,
  11637. _usedTextureUnits = 0,
  11638. // GL state cache
  11639. _oldDoubleSided = -1,
  11640. _oldFlipSided = -1,
  11641. _oldBlending = -1,
  11642. _oldBlendEquation = -1,
  11643. _oldBlendSrc = -1,
  11644. _oldBlendDst = -1,
  11645. _oldDepthTest = -1,
  11646. _oldDepthWrite = -1,
  11647. _oldPolygonOffset = null,
  11648. _oldPolygonOffsetFactor = null,
  11649. _oldPolygonOffsetUnits = null,
  11650. _oldLineWidth = null,
  11651. _viewportX = 0,
  11652. _viewportY = 0,
  11653. _viewportWidth = _canvas.width,
  11654. _viewportHeight = _canvas.height,
  11655. _currentWidth = 0,
  11656. _currentHeight = 0,
  11657. _enabledAttributes = {},
  11658. // frustum
  11659. _frustum = new THREE.Frustum(),
  11660. // camera matrices cache
  11661. _projScreenMatrix = new THREE.Matrix4(),
  11662. _projScreenMatrixPS = new THREE.Matrix4(),
  11663. _vector3 = new THREE.Vector3(),
  11664. // light arrays cache
  11665. _direction = new THREE.Vector3(),
  11666. _lightsNeedUpdate = true,
  11667. _lights = {
  11668. ambient: [ 0, 0, 0 ],
  11669. directional: { length: 0, colors: new Array(), positions: new Array() },
  11670. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  11671. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  11672. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  11673. };
  11674. // initialize
  11675. var _gl;
  11676. var _glExtensionTextureFloat;
  11677. var _glExtensionTextureFloatLinear;
  11678. var _glExtensionStandardDerivatives;
  11679. var _glExtensionTextureFilterAnisotropic;
  11680. var _glExtensionCompressedTextureS3TC;
  11681. initGL();
  11682. setDefaultGLState();
  11683. this.context = _gl;
  11684. // GPU capabilities
  11685. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  11686. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11687. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  11688. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11689. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  11690. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  11691. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  11692. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  11693. //
  11694. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  11695. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  11696. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  11697. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  11698. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  11699. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  11700. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  11701. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  11702. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  11703. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  11704. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  11705. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  11706. // clamp precision to maximum available
  11707. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  11708. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  11709. if ( _precision === "highp" && ! highpAvailable ) {
  11710. if ( mediumpAvailable ) {
  11711. _precision = "mediump";
  11712. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  11713. } else {
  11714. _precision = "lowp";
  11715. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  11716. }
  11717. }
  11718. if ( _precision === "mediump" && ! mediumpAvailable ) {
  11719. _precision = "lowp";
  11720. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  11721. }
  11722. // API
  11723. this.getContext = function () {
  11724. return _gl;
  11725. };
  11726. this.supportsVertexTextures = function () {
  11727. return _supportsVertexTextures;
  11728. };
  11729. this.supportsFloatTextures = function () {
  11730. return _glExtensionTextureFloat;
  11731. };
  11732. this.supportsStandardDerivatives = function () {
  11733. return _glExtensionStandardDerivatives;
  11734. };
  11735. this.supportsCompressedTextureS3TC = function () {
  11736. return _glExtensionCompressedTextureS3TC;
  11737. };
  11738. this.getMaxAnisotropy = function () {
  11739. return _maxAnisotropy;
  11740. };
  11741. this.getPrecision = function () {
  11742. return _precision;
  11743. };
  11744. this.setSize = function ( width, height, updateStyle ) {
  11745. _canvas.width = width * this.devicePixelRatio;
  11746. _canvas.height = height * this.devicePixelRatio;
  11747. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  11748. _canvas.style.width = width + 'px';
  11749. _canvas.style.height = height + 'px';
  11750. }
  11751. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  11752. };
  11753. this.setViewport = function ( x, y, width, height ) {
  11754. _viewportX = x !== undefined ? x : 0;
  11755. _viewportY = y !== undefined ? y : 0;
  11756. _viewportWidth = width !== undefined ? width : _canvas.width;
  11757. _viewportHeight = height !== undefined ? height : _canvas.height;
  11758. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11759. };
  11760. this.setScissor = function ( x, y, width, height ) {
  11761. _gl.scissor( x, y, width, height );
  11762. };
  11763. this.enableScissorTest = function ( enable ) {
  11764. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  11765. };
  11766. // Clearing
  11767. this.setClearColor = function ( color, alpha ) {
  11768. _clearColor.set( color );
  11769. _clearAlpha = alpha !== undefined ? alpha : 1;
  11770. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11771. };
  11772. this.setClearColorHex = function ( hex, alpha ) {
  11773. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  11774. this.setClearColor( hex, alpha );
  11775. };
  11776. this.getClearColor = function () {
  11777. return _clearColor;
  11778. };
  11779. this.getClearAlpha = function () {
  11780. return _clearAlpha;
  11781. };
  11782. this.clear = function ( color, depth, stencil ) {
  11783. var bits = 0;
  11784. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11785. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11786. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11787. _gl.clear( bits );
  11788. };
  11789. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11790. this.setRenderTarget( renderTarget );
  11791. this.clear( color, depth, stencil );
  11792. };
  11793. // Plugins
  11794. this.addPostPlugin = function ( plugin ) {
  11795. plugin.init( this );
  11796. this.renderPluginsPost.push( plugin );
  11797. };
  11798. this.addPrePlugin = function ( plugin ) {
  11799. plugin.init( this );
  11800. this.renderPluginsPre.push( plugin );
  11801. };
  11802. // Rendering
  11803. this.updateShadowMap = function ( scene, camera ) {
  11804. _currentProgram = null;
  11805. _oldBlending = -1;
  11806. _oldDepthTest = -1;
  11807. _oldDepthWrite = -1;
  11808. _currentGeometryGroupHash = -1;
  11809. _currentMaterialId = -1;
  11810. _lightsNeedUpdate = true;
  11811. _oldDoubleSided = -1;
  11812. _oldFlipSided = -1;
  11813. this.shadowMapPlugin.update( scene, camera );
  11814. };
  11815. // Internal functions
  11816. // Buffer allocation
  11817. function createParticleBuffers ( geometry ) {
  11818. geometry.__webglVertexBuffer = _gl.createBuffer();
  11819. geometry.__webglColorBuffer = _gl.createBuffer();
  11820. _this.info.memory.geometries ++;
  11821. };
  11822. function createLineBuffers ( geometry ) {
  11823. geometry.__webglVertexBuffer = _gl.createBuffer();
  11824. geometry.__webglColorBuffer = _gl.createBuffer();
  11825. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  11826. _this.info.memory.geometries ++;
  11827. };
  11828. function createMeshBuffers ( geometryGroup ) {
  11829. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  11830. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  11831. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  11832. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  11833. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  11834. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  11835. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  11836. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  11837. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  11838. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  11839. var m, ml;
  11840. if ( geometryGroup.numMorphTargets ) {
  11841. geometryGroup.__webglMorphTargetsBuffers = [];
  11842. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11843. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  11844. }
  11845. }
  11846. if ( geometryGroup.numMorphNormals ) {
  11847. geometryGroup.__webglMorphNormalsBuffers = [];
  11848. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11849. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  11850. }
  11851. }
  11852. _this.info.memory.geometries ++;
  11853. };
  11854. // Events
  11855. var onGeometryDispose = function ( event ) {
  11856. var geometry = event.target;
  11857. geometry.removeEventListener( 'dispose', onGeometryDispose );
  11858. deallocateGeometry( geometry );
  11859. };
  11860. var onTextureDispose = function ( event ) {
  11861. var texture = event.target;
  11862. texture.removeEventListener( 'dispose', onTextureDispose );
  11863. deallocateTexture( texture );
  11864. _this.info.memory.textures --;
  11865. };
  11866. var onRenderTargetDispose = function ( event ) {
  11867. var renderTarget = event.target;
  11868. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11869. deallocateRenderTarget( renderTarget );
  11870. _this.info.memory.textures --;
  11871. };
  11872. var onMaterialDispose = function ( event ) {
  11873. var material = event.target;
  11874. material.removeEventListener( 'dispose', onMaterialDispose );
  11875. deallocateMaterial( material );
  11876. };
  11877. // Buffer deallocation
  11878. var deleteBuffers = function ( geometry ) {
  11879. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11880. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  11881. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  11882. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  11883. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  11884. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  11885. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  11886. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  11887. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  11888. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  11889. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  11890. // custom attributes
  11891. if ( geometry.__webglCustomAttributesList !== undefined ) {
  11892. for ( var id in geometry.__webglCustomAttributesList ) {
  11893. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  11894. }
  11895. }
  11896. _this.info.memory.geometries --;
  11897. };
  11898. var deallocateGeometry = function ( geometry ) {
  11899. geometry.__webglInit = undefined;
  11900. if ( geometry instanceof THREE.BufferGeometry ) {
  11901. var attributes = geometry.attributes;
  11902. for ( var key in attributes ) {
  11903. if ( attributes[ key ].buffer !== undefined ) {
  11904. _gl.deleteBuffer( attributes[ key ].buffer );
  11905. }
  11906. }
  11907. _this.info.memory.geometries --;
  11908. } else {
  11909. if ( geometry.geometryGroups !== undefined ) {
  11910. for ( var g in geometry.geometryGroups ) {
  11911. var geometryGroup = geometry.geometryGroups[ g ];
  11912. if ( geometryGroup.numMorphTargets !== undefined ) {
  11913. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11914. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11915. }
  11916. }
  11917. if ( geometryGroup.numMorphNormals !== undefined ) {
  11918. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11919. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11920. }
  11921. }
  11922. deleteBuffers( geometryGroup );
  11923. }
  11924. } else {
  11925. deleteBuffers( geometry );
  11926. }
  11927. }
  11928. };
  11929. var deallocateTexture = function ( texture ) {
  11930. if ( texture.image && texture.image.__webglTextureCube ) {
  11931. // cube texture
  11932. _gl.deleteTexture( texture.image.__webglTextureCube );
  11933. } else {
  11934. // 2D texture
  11935. if ( ! texture.__webglInit ) return;
  11936. texture.__webglInit = false;
  11937. _gl.deleteTexture( texture.__webglTexture );
  11938. }
  11939. };
  11940. var deallocateRenderTarget = function ( renderTarget ) {
  11941. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  11942. _gl.deleteTexture( renderTarget.__webglTexture );
  11943. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  11944. for ( var i = 0; i < 6; i ++ ) {
  11945. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  11946. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  11947. }
  11948. } else {
  11949. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  11950. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  11951. }
  11952. };
  11953. var deallocateMaterial = function ( material ) {
  11954. var program = material.program;
  11955. if ( program === undefined ) return;
  11956. material.program = undefined;
  11957. // only deallocate GL program if this was the last use of shared program
  11958. // assumed there is only single copy of any program in the _programs list
  11959. // (that's how it's constructed)
  11960. var i, il, programInfo;
  11961. var deleteProgram = false;
  11962. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11963. programInfo = _programs[ i ];
  11964. if ( programInfo.program === program ) {
  11965. programInfo.usedTimes --;
  11966. if ( programInfo.usedTimes === 0 ) {
  11967. deleteProgram = true;
  11968. }
  11969. break;
  11970. }
  11971. }
  11972. if ( deleteProgram === true ) {
  11973. // avoid using array.splice, this is costlier than creating new array from scratch
  11974. var newPrograms = [];
  11975. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11976. programInfo = _programs[ i ];
  11977. if ( programInfo.program !== program ) {
  11978. newPrograms.push( programInfo );
  11979. }
  11980. }
  11981. _programs = newPrograms;
  11982. _gl.deleteProgram( program );
  11983. _this.info.memory.programs --;
  11984. }
  11985. };
  11986. // Buffer initialization
  11987. function initCustomAttributes ( geometry, object ) {
  11988. var nvertices = geometry.vertices.length;
  11989. var material = object.material;
  11990. if ( material.attributes ) {
  11991. if ( geometry.__webglCustomAttributesList === undefined ) {
  11992. geometry.__webglCustomAttributesList = [];
  11993. }
  11994. for ( var a in material.attributes ) {
  11995. var attribute = material.attributes[ a ];
  11996. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11997. attribute.__webglInitialized = true;
  11998. var size = 1; // "f" and "i"
  11999. if ( attribute.type === "v2" ) size = 2;
  12000. else if ( attribute.type === "v3" ) size = 3;
  12001. else if ( attribute.type === "v4" ) size = 4;
  12002. else if ( attribute.type === "c" ) size = 3;
  12003. attribute.size = size;
  12004. attribute.array = new Float32Array( nvertices * size );
  12005. attribute.buffer = _gl.createBuffer();
  12006. attribute.buffer.belongsToAttribute = a;
  12007. attribute.needsUpdate = true;
  12008. }
  12009. geometry.__webglCustomAttributesList.push( attribute );
  12010. }
  12011. }
  12012. };
  12013. function initParticleBuffers ( geometry, object ) {
  12014. var nvertices = geometry.vertices.length;
  12015. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12016. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12017. geometry.__sortArray = [];
  12018. geometry.__webglParticleCount = nvertices;
  12019. initCustomAttributes ( geometry, object );
  12020. };
  12021. function initLineBuffers ( geometry, object ) {
  12022. var nvertices = geometry.vertices.length;
  12023. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12024. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12025. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  12026. geometry.__webglLineCount = nvertices;
  12027. initCustomAttributes ( geometry, object );
  12028. };
  12029. function initMeshBuffers ( geometryGroup, object ) {
  12030. var geometry = object.geometry,
  12031. faces3 = geometryGroup.faces3,
  12032. nvertices = faces3.length * 3,
  12033. ntris = faces3.length * 1,
  12034. nlines = faces3.length * 3,
  12035. material = getBufferMaterial( object, geometryGroup ),
  12036. uvType = bufferGuessUVType( material ),
  12037. normalType = bufferGuessNormalType( material ),
  12038. vertexColorType = bufferGuessVertexColorType( material );
  12039. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  12040. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  12041. if ( normalType ) {
  12042. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  12043. }
  12044. if ( geometry.hasTangents ) {
  12045. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  12046. }
  12047. if ( vertexColorType ) {
  12048. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  12049. }
  12050. if ( uvType ) {
  12051. if ( geometry.faceVertexUvs.length > 0 ) {
  12052. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  12053. }
  12054. if ( geometry.faceVertexUvs.length > 1 ) {
  12055. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  12056. }
  12057. }
  12058. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  12059. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  12060. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  12061. }
  12062. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  12063. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  12064. var m, ml;
  12065. if ( geometryGroup.numMorphTargets ) {
  12066. geometryGroup.__morphTargetsArrays = [];
  12067. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12068. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  12069. }
  12070. }
  12071. if ( geometryGroup.numMorphNormals ) {
  12072. geometryGroup.__morphNormalsArrays = [];
  12073. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12074. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  12075. }
  12076. }
  12077. geometryGroup.__webglFaceCount = ntris * 3;
  12078. geometryGroup.__webglLineCount = nlines * 2;
  12079. // custom attributes
  12080. if ( material.attributes ) {
  12081. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  12082. geometryGroup.__webglCustomAttributesList = [];
  12083. }
  12084. for ( var a in material.attributes ) {
  12085. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  12086. // attribute buffers which are correctly indexed in the setMeshBuffers function
  12087. var originalAttribute = material.attributes[ a ];
  12088. var attribute = {};
  12089. for ( var property in originalAttribute ) {
  12090. attribute[ property ] = originalAttribute[ property ];
  12091. }
  12092. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12093. attribute.__webglInitialized = true;
  12094. var size = 1; // "f" and "i"
  12095. if( attribute.type === "v2" ) size = 2;
  12096. else if( attribute.type === "v3" ) size = 3;
  12097. else if( attribute.type === "v4" ) size = 4;
  12098. else if( attribute.type === "c" ) size = 3;
  12099. attribute.size = size;
  12100. attribute.array = new Float32Array( nvertices * size );
  12101. attribute.buffer = _gl.createBuffer();
  12102. attribute.buffer.belongsToAttribute = a;
  12103. originalAttribute.needsUpdate = true;
  12104. attribute.__original = originalAttribute;
  12105. }
  12106. geometryGroup.__webglCustomAttributesList.push( attribute );
  12107. }
  12108. }
  12109. geometryGroup.__inittedArrays = true;
  12110. };
  12111. function getBufferMaterial( object, geometryGroup ) {
  12112. return object.material instanceof THREE.MeshFaceMaterial
  12113. ? object.material.materials[ geometryGroup.materialIndex ]
  12114. : object.material;
  12115. };
  12116. function materialNeedsSmoothNormals ( material ) {
  12117. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  12118. };
  12119. function bufferGuessNormalType ( material ) {
  12120. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  12121. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  12122. return false;
  12123. }
  12124. if ( materialNeedsSmoothNormals( material ) ) {
  12125. return THREE.SmoothShading;
  12126. } else {
  12127. return THREE.FlatShading;
  12128. }
  12129. };
  12130. function bufferGuessVertexColorType( material ) {
  12131. if ( material.vertexColors ) {
  12132. return material.vertexColors;
  12133. }
  12134. return false;
  12135. };
  12136. function bufferGuessUVType( material ) {
  12137. // material must use some texture to require uvs
  12138. if ( material.map ||
  12139. material.lightMap ||
  12140. material.bumpMap ||
  12141. material.normalMap ||
  12142. material.specularMap ||
  12143. material instanceof THREE.ShaderMaterial ) {
  12144. return true;
  12145. }
  12146. return false;
  12147. };
  12148. //
  12149. function initDirectBuffers( geometry ) {
  12150. var a, attribute, type;
  12151. for ( a in geometry.attributes ) {
  12152. if ( a === "index" ) {
  12153. type = _gl.ELEMENT_ARRAY_BUFFER;
  12154. } else {
  12155. type = _gl.ARRAY_BUFFER;
  12156. }
  12157. attribute = geometry.attributes[ a ];
  12158. if ( attribute.numItems === undefined ) {
  12159. attribute.numItems = attribute.array.length;
  12160. }
  12161. attribute.buffer = _gl.createBuffer();
  12162. _gl.bindBuffer( type, attribute.buffer );
  12163. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  12164. }
  12165. };
  12166. // Buffer setting
  12167. function setParticleBuffers ( geometry, hint, object ) {
  12168. var v, c, vertex, offset, index, color,
  12169. vertices = geometry.vertices,
  12170. vl = vertices.length,
  12171. colors = geometry.colors,
  12172. cl = colors.length,
  12173. vertexArray = geometry.__vertexArray,
  12174. colorArray = geometry.__colorArray,
  12175. sortArray = geometry.__sortArray,
  12176. dirtyVertices = geometry.verticesNeedUpdate,
  12177. dirtyElements = geometry.elementsNeedUpdate,
  12178. dirtyColors = geometry.colorsNeedUpdate,
  12179. customAttributes = geometry.__webglCustomAttributesList,
  12180. i, il,
  12181. a, ca, cal, value,
  12182. customAttribute;
  12183. if ( object.sortParticles ) {
  12184. _projScreenMatrixPS.copy( _projScreenMatrix );
  12185. _projScreenMatrixPS.multiply( object.matrixWorld );
  12186. for ( v = 0; v < vl; v ++ ) {
  12187. vertex = vertices[ v ];
  12188. _vector3.copy( vertex );
  12189. _vector3.applyProjection( _projScreenMatrixPS );
  12190. sortArray[ v ] = [ _vector3.z, v ];
  12191. }
  12192. sortArray.sort( numericalSort );
  12193. for ( v = 0; v < vl; v ++ ) {
  12194. vertex = vertices[ sortArray[v][1] ];
  12195. offset = v * 3;
  12196. vertexArray[ offset ] = vertex.x;
  12197. vertexArray[ offset + 1 ] = vertex.y;
  12198. vertexArray[ offset + 2 ] = vertex.z;
  12199. }
  12200. for ( c = 0; c < cl; c ++ ) {
  12201. offset = c * 3;
  12202. color = colors[ sortArray[c][1] ];
  12203. colorArray[ offset ] = color.r;
  12204. colorArray[ offset + 1 ] = color.g;
  12205. colorArray[ offset + 2 ] = color.b;
  12206. }
  12207. if ( customAttributes ) {
  12208. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12209. customAttribute = customAttributes[ i ];
  12210. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  12211. offset = 0;
  12212. cal = customAttribute.value.length;
  12213. if ( customAttribute.size === 1 ) {
  12214. for ( ca = 0; ca < cal; ca ++ ) {
  12215. index = sortArray[ ca ][ 1 ];
  12216. customAttribute.array[ ca ] = customAttribute.value[ index ];
  12217. }
  12218. } else if ( customAttribute.size === 2 ) {
  12219. for ( ca = 0; ca < cal; ca ++ ) {
  12220. index = sortArray[ ca ][ 1 ];
  12221. value = customAttribute.value[ index ];
  12222. customAttribute.array[ offset ] = value.x;
  12223. customAttribute.array[ offset + 1 ] = value.y;
  12224. offset += 2;
  12225. }
  12226. } else if ( customAttribute.size === 3 ) {
  12227. if ( customAttribute.type === "c" ) {
  12228. for ( ca = 0; ca < cal; ca ++ ) {
  12229. index = sortArray[ ca ][ 1 ];
  12230. value = customAttribute.value[ index ];
  12231. customAttribute.array[ offset ] = value.r;
  12232. customAttribute.array[ offset + 1 ] = value.g;
  12233. customAttribute.array[ offset + 2 ] = value.b;
  12234. offset += 3;
  12235. }
  12236. } else {
  12237. for ( ca = 0; ca < cal; ca ++ ) {
  12238. index = sortArray[ ca ][ 1 ];
  12239. value = customAttribute.value[ index ];
  12240. customAttribute.array[ offset ] = value.x;
  12241. customAttribute.array[ offset + 1 ] = value.y;
  12242. customAttribute.array[ offset + 2 ] = value.z;
  12243. offset += 3;
  12244. }
  12245. }
  12246. } else if ( customAttribute.size === 4 ) {
  12247. for ( ca = 0; ca < cal; ca ++ ) {
  12248. index = sortArray[ ca ][ 1 ];
  12249. value = customAttribute.value[ index ];
  12250. customAttribute.array[ offset ] = value.x;
  12251. customAttribute.array[ offset + 1 ] = value.y;
  12252. customAttribute.array[ offset + 2 ] = value.z;
  12253. customAttribute.array[ offset + 3 ] = value.w;
  12254. offset += 4;
  12255. }
  12256. }
  12257. }
  12258. }
  12259. } else {
  12260. if ( dirtyVertices ) {
  12261. for ( v = 0; v < vl; v ++ ) {
  12262. vertex = vertices[ v ];
  12263. offset = v * 3;
  12264. vertexArray[ offset ] = vertex.x;
  12265. vertexArray[ offset + 1 ] = vertex.y;
  12266. vertexArray[ offset + 2 ] = vertex.z;
  12267. }
  12268. }
  12269. if ( dirtyColors ) {
  12270. for ( c = 0; c < cl; c ++ ) {
  12271. color = colors[ c ];
  12272. offset = c * 3;
  12273. colorArray[ offset ] = color.r;
  12274. colorArray[ offset + 1 ] = color.g;
  12275. colorArray[ offset + 2 ] = color.b;
  12276. }
  12277. }
  12278. if ( customAttributes ) {
  12279. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12280. customAttribute = customAttributes[ i ];
  12281. if ( customAttribute.needsUpdate &&
  12282. ( customAttribute.boundTo === undefined ||
  12283. customAttribute.boundTo === "vertices") ) {
  12284. cal = customAttribute.value.length;
  12285. offset = 0;
  12286. if ( customAttribute.size === 1 ) {
  12287. for ( ca = 0; ca < cal; ca ++ ) {
  12288. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12289. }
  12290. } else if ( customAttribute.size === 2 ) {
  12291. for ( ca = 0; ca < cal; ca ++ ) {
  12292. value = customAttribute.value[ ca ];
  12293. customAttribute.array[ offset ] = value.x;
  12294. customAttribute.array[ offset + 1 ] = value.y;
  12295. offset += 2;
  12296. }
  12297. } else if ( customAttribute.size === 3 ) {
  12298. if ( customAttribute.type === "c" ) {
  12299. for ( ca = 0; ca < cal; ca ++ ) {
  12300. value = customAttribute.value[ ca ];
  12301. customAttribute.array[ offset ] = value.r;
  12302. customAttribute.array[ offset + 1 ] = value.g;
  12303. customAttribute.array[ offset + 2 ] = value.b;
  12304. offset += 3;
  12305. }
  12306. } else {
  12307. for ( ca = 0; ca < cal; ca ++ ) {
  12308. value = customAttribute.value[ ca ];
  12309. customAttribute.array[ offset ] = value.x;
  12310. customAttribute.array[ offset + 1 ] = value.y;
  12311. customAttribute.array[ offset + 2 ] = value.z;
  12312. offset += 3;
  12313. }
  12314. }
  12315. } else if ( customAttribute.size === 4 ) {
  12316. for ( ca = 0; ca < cal; ca ++ ) {
  12317. value = customAttribute.value[ ca ];
  12318. customAttribute.array[ offset ] = value.x;
  12319. customAttribute.array[ offset + 1 ] = value.y;
  12320. customAttribute.array[ offset + 2 ] = value.z;
  12321. customAttribute.array[ offset + 3 ] = value.w;
  12322. offset += 4;
  12323. }
  12324. }
  12325. }
  12326. }
  12327. }
  12328. }
  12329. if ( dirtyVertices || object.sortParticles ) {
  12330. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12331. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12332. }
  12333. if ( dirtyColors || object.sortParticles ) {
  12334. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12335. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12336. }
  12337. if ( customAttributes ) {
  12338. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12339. customAttribute = customAttributes[ i ];
  12340. if ( customAttribute.needsUpdate || object.sortParticles ) {
  12341. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12342. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12343. }
  12344. }
  12345. }
  12346. };
  12347. function setLineBuffers ( geometry, hint ) {
  12348. var v, c, d, vertex, offset, color,
  12349. vertices = geometry.vertices,
  12350. colors = geometry.colors,
  12351. lineDistances = geometry.lineDistances,
  12352. vl = vertices.length,
  12353. cl = colors.length,
  12354. dl = lineDistances.length,
  12355. vertexArray = geometry.__vertexArray,
  12356. colorArray = geometry.__colorArray,
  12357. lineDistanceArray = geometry.__lineDistanceArray,
  12358. dirtyVertices = geometry.verticesNeedUpdate,
  12359. dirtyColors = geometry.colorsNeedUpdate,
  12360. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  12361. customAttributes = geometry.__webglCustomAttributesList,
  12362. i, il,
  12363. a, ca, cal, value,
  12364. customAttribute;
  12365. if ( dirtyVertices ) {
  12366. for ( v = 0; v < vl; v ++ ) {
  12367. vertex = vertices[ v ];
  12368. offset = v * 3;
  12369. vertexArray[ offset ] = vertex.x;
  12370. vertexArray[ offset + 1 ] = vertex.y;
  12371. vertexArray[ offset + 2 ] = vertex.z;
  12372. }
  12373. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12374. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12375. }
  12376. if ( dirtyColors ) {
  12377. for ( c = 0; c < cl; c ++ ) {
  12378. color = colors[ c ];
  12379. offset = c * 3;
  12380. colorArray[ offset ] = color.r;
  12381. colorArray[ offset + 1 ] = color.g;
  12382. colorArray[ offset + 2 ] = color.b;
  12383. }
  12384. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12385. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12386. }
  12387. if ( dirtyLineDistances ) {
  12388. for ( d = 0; d < dl; d ++ ) {
  12389. lineDistanceArray[ d ] = lineDistances[ d ];
  12390. }
  12391. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  12392. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  12393. }
  12394. if ( customAttributes ) {
  12395. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12396. customAttribute = customAttributes[ i ];
  12397. if ( customAttribute.needsUpdate &&
  12398. ( customAttribute.boundTo === undefined ||
  12399. customAttribute.boundTo === "vertices" ) ) {
  12400. offset = 0;
  12401. cal = customAttribute.value.length;
  12402. if ( customAttribute.size === 1 ) {
  12403. for ( ca = 0; ca < cal; ca ++ ) {
  12404. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12405. }
  12406. } else if ( customAttribute.size === 2 ) {
  12407. for ( ca = 0; ca < cal; ca ++ ) {
  12408. value = customAttribute.value[ ca ];
  12409. customAttribute.array[ offset ] = value.x;
  12410. customAttribute.array[ offset + 1 ] = value.y;
  12411. offset += 2;
  12412. }
  12413. } else if ( customAttribute.size === 3 ) {
  12414. if ( customAttribute.type === "c" ) {
  12415. for ( ca = 0; ca < cal; ca ++ ) {
  12416. value = customAttribute.value[ ca ];
  12417. customAttribute.array[ offset ] = value.r;
  12418. customAttribute.array[ offset + 1 ] = value.g;
  12419. customAttribute.array[ offset + 2 ] = value.b;
  12420. offset += 3;
  12421. }
  12422. } else {
  12423. for ( ca = 0; ca < cal; ca ++ ) {
  12424. value = customAttribute.value[ ca ];
  12425. customAttribute.array[ offset ] = value.x;
  12426. customAttribute.array[ offset + 1 ] = value.y;
  12427. customAttribute.array[ offset + 2 ] = value.z;
  12428. offset += 3;
  12429. }
  12430. }
  12431. } else if ( customAttribute.size === 4 ) {
  12432. for ( ca = 0; ca < cal; ca ++ ) {
  12433. value = customAttribute.value[ ca ];
  12434. customAttribute.array[ offset ] = value.x;
  12435. customAttribute.array[ offset + 1 ] = value.y;
  12436. customAttribute.array[ offset + 2 ] = value.z;
  12437. customAttribute.array[ offset + 3 ] = value.w;
  12438. offset += 4;
  12439. }
  12440. }
  12441. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12442. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12443. }
  12444. }
  12445. }
  12446. };
  12447. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12448. if ( ! geometryGroup.__inittedArrays ) {
  12449. return;
  12450. }
  12451. var normalType = bufferGuessNormalType( material ),
  12452. vertexColorType = bufferGuessVertexColorType( material ),
  12453. uvType = bufferGuessUVType( material ),
  12454. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12455. var f, fl, fi, face,
  12456. vertexNormals, faceNormal, normal,
  12457. vertexColors, faceColor,
  12458. vertexTangents,
  12459. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12460. c1, c2, c3, c4,
  12461. sw1, sw2, sw3, sw4,
  12462. si1, si2, si3, si4,
  12463. sa1, sa2, sa3, sa4,
  12464. sb1, sb2, sb3, sb4,
  12465. m, ml, i, il,
  12466. vn, uvi, uv2i,
  12467. vk, vkl, vka,
  12468. nka, chf, faceVertexNormals,
  12469. a,
  12470. vertexIndex = 0,
  12471. offset = 0,
  12472. offset_uv = 0,
  12473. offset_uv2 = 0,
  12474. offset_face = 0,
  12475. offset_normal = 0,
  12476. offset_tangent = 0,
  12477. offset_line = 0,
  12478. offset_color = 0,
  12479. offset_skin = 0,
  12480. offset_morphTarget = 0,
  12481. offset_custom = 0,
  12482. offset_customSrc = 0,
  12483. value,
  12484. vertexArray = geometryGroup.__vertexArray,
  12485. uvArray = geometryGroup.__uvArray,
  12486. uv2Array = geometryGroup.__uv2Array,
  12487. normalArray = geometryGroup.__normalArray,
  12488. tangentArray = geometryGroup.__tangentArray,
  12489. colorArray = geometryGroup.__colorArray,
  12490. skinIndexArray = geometryGroup.__skinIndexArray,
  12491. skinWeightArray = geometryGroup.__skinWeightArray,
  12492. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12493. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12494. customAttributes = geometryGroup.__webglCustomAttributesList,
  12495. customAttribute,
  12496. faceArray = geometryGroup.__faceArray,
  12497. lineArray = geometryGroup.__lineArray,
  12498. geometry = object.geometry, // this is shared for all chunks
  12499. dirtyVertices = geometry.verticesNeedUpdate,
  12500. dirtyElements = geometry.elementsNeedUpdate,
  12501. dirtyUvs = geometry.uvsNeedUpdate,
  12502. dirtyNormals = geometry.normalsNeedUpdate,
  12503. dirtyTangents = geometry.tangentsNeedUpdate,
  12504. dirtyColors = geometry.colorsNeedUpdate,
  12505. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12506. vertices = geometry.vertices,
  12507. chunk_faces3 = geometryGroup.faces3,
  12508. obj_faces = geometry.faces,
  12509. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12510. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12511. obj_colors = geometry.colors,
  12512. obj_skinIndices = geometry.skinIndices,
  12513. obj_skinWeights = geometry.skinWeights,
  12514. morphTargets = geometry.morphTargets,
  12515. morphNormals = geometry.morphNormals;
  12516. if ( dirtyVertices ) {
  12517. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12518. face = obj_faces[ chunk_faces3[ f ] ];
  12519. v1 = vertices[ face.a ];
  12520. v2 = vertices[ face.b ];
  12521. v3 = vertices[ face.c ];
  12522. vertexArray[ offset ] = v1.x;
  12523. vertexArray[ offset + 1 ] = v1.y;
  12524. vertexArray[ offset + 2 ] = v1.z;
  12525. vertexArray[ offset + 3 ] = v2.x;
  12526. vertexArray[ offset + 4 ] = v2.y;
  12527. vertexArray[ offset + 5 ] = v2.z;
  12528. vertexArray[ offset + 6 ] = v3.x;
  12529. vertexArray[ offset + 7 ] = v3.y;
  12530. vertexArray[ offset + 8 ] = v3.z;
  12531. offset += 9;
  12532. }
  12533. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12534. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12535. }
  12536. if ( dirtyMorphTargets ) {
  12537. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  12538. offset_morphTarget = 0;
  12539. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12540. chf = chunk_faces3[ f ];
  12541. face = obj_faces[ chf ];
  12542. // morph positions
  12543. v1 = morphTargets[ vk ].vertices[ face.a ];
  12544. v2 = morphTargets[ vk ].vertices[ face.b ];
  12545. v3 = morphTargets[ vk ].vertices[ face.c ];
  12546. vka = morphTargetsArrays[ vk ];
  12547. vka[ offset_morphTarget ] = v1.x;
  12548. vka[ offset_morphTarget + 1 ] = v1.y;
  12549. vka[ offset_morphTarget + 2 ] = v1.z;
  12550. vka[ offset_morphTarget + 3 ] = v2.x;
  12551. vka[ offset_morphTarget + 4 ] = v2.y;
  12552. vka[ offset_morphTarget + 5 ] = v2.z;
  12553. vka[ offset_morphTarget + 6 ] = v3.x;
  12554. vka[ offset_morphTarget + 7 ] = v3.y;
  12555. vka[ offset_morphTarget + 8 ] = v3.z;
  12556. // morph normals
  12557. if ( material.morphNormals ) {
  12558. if ( needsSmoothNormals ) {
  12559. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12560. n1 = faceVertexNormals.a;
  12561. n2 = faceVertexNormals.b;
  12562. n3 = faceVertexNormals.c;
  12563. } else {
  12564. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12565. n2 = n1;
  12566. n3 = n1;
  12567. }
  12568. nka = morphNormalsArrays[ vk ];
  12569. nka[ offset_morphTarget ] = n1.x;
  12570. nka[ offset_morphTarget + 1 ] = n1.y;
  12571. nka[ offset_morphTarget + 2 ] = n1.z;
  12572. nka[ offset_morphTarget + 3 ] = n2.x;
  12573. nka[ offset_morphTarget + 4 ] = n2.y;
  12574. nka[ offset_morphTarget + 5 ] = n2.z;
  12575. nka[ offset_morphTarget + 6 ] = n3.x;
  12576. nka[ offset_morphTarget + 7 ] = n3.y;
  12577. nka[ offset_morphTarget + 8 ] = n3.z;
  12578. }
  12579. //
  12580. offset_morphTarget += 9;
  12581. }
  12582. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  12583. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  12584. if ( material.morphNormals ) {
  12585. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  12586. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  12587. }
  12588. }
  12589. }
  12590. if ( obj_skinWeights.length ) {
  12591. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12592. face = obj_faces[ chunk_faces3[ f ] ];
  12593. // weights
  12594. sw1 = obj_skinWeights[ face.a ];
  12595. sw2 = obj_skinWeights[ face.b ];
  12596. sw3 = obj_skinWeights[ face.c ];
  12597. skinWeightArray[ offset_skin ] = sw1.x;
  12598. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12599. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12600. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12601. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12602. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12603. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12604. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12605. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12606. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12607. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12608. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12609. // indices
  12610. si1 = obj_skinIndices[ face.a ];
  12611. si2 = obj_skinIndices[ face.b ];
  12612. si3 = obj_skinIndices[ face.c ];
  12613. skinIndexArray[ offset_skin ] = si1.x;
  12614. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12615. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12616. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12617. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12618. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12619. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12620. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12621. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12622. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12623. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12624. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12625. offset_skin += 12;
  12626. }
  12627. if ( offset_skin > 0 ) {
  12628. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12629. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  12630. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12631. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  12632. }
  12633. }
  12634. if ( dirtyColors && vertexColorType ) {
  12635. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12636. face = obj_faces[ chunk_faces3[ f ] ];
  12637. vertexColors = face.vertexColors;
  12638. faceColor = face.color;
  12639. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  12640. c1 = vertexColors[ 0 ];
  12641. c2 = vertexColors[ 1 ];
  12642. c3 = vertexColors[ 2 ];
  12643. } else {
  12644. c1 = faceColor;
  12645. c2 = faceColor;
  12646. c3 = faceColor;
  12647. }
  12648. colorArray[ offset_color ] = c1.r;
  12649. colorArray[ offset_color + 1 ] = c1.g;
  12650. colorArray[ offset_color + 2 ] = c1.b;
  12651. colorArray[ offset_color + 3 ] = c2.r;
  12652. colorArray[ offset_color + 4 ] = c2.g;
  12653. colorArray[ offset_color + 5 ] = c2.b;
  12654. colorArray[ offset_color + 6 ] = c3.r;
  12655. colorArray[ offset_color + 7 ] = c3.g;
  12656. colorArray[ offset_color + 8 ] = c3.b;
  12657. offset_color += 9;
  12658. }
  12659. if ( offset_color > 0 ) {
  12660. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12661. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12662. }
  12663. }
  12664. if ( dirtyTangents && geometry.hasTangents ) {
  12665. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12666. face = obj_faces[ chunk_faces3[ f ] ];
  12667. vertexTangents = face.vertexTangents;
  12668. t1 = vertexTangents[ 0 ];
  12669. t2 = vertexTangents[ 1 ];
  12670. t3 = vertexTangents[ 2 ];
  12671. tangentArray[ offset_tangent ] = t1.x;
  12672. tangentArray[ offset_tangent + 1 ] = t1.y;
  12673. tangentArray[ offset_tangent + 2 ] = t1.z;
  12674. tangentArray[ offset_tangent + 3 ] = t1.w;
  12675. tangentArray[ offset_tangent + 4 ] = t2.x;
  12676. tangentArray[ offset_tangent + 5 ] = t2.y;
  12677. tangentArray[ offset_tangent + 6 ] = t2.z;
  12678. tangentArray[ offset_tangent + 7 ] = t2.w;
  12679. tangentArray[ offset_tangent + 8 ] = t3.x;
  12680. tangentArray[ offset_tangent + 9 ] = t3.y;
  12681. tangentArray[ offset_tangent + 10 ] = t3.z;
  12682. tangentArray[ offset_tangent + 11 ] = t3.w;
  12683. offset_tangent += 12;
  12684. }
  12685. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12686. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  12687. }
  12688. if ( dirtyNormals && normalType ) {
  12689. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12690. face = obj_faces[ chunk_faces3[ f ] ];
  12691. vertexNormals = face.vertexNormals;
  12692. faceNormal = face.normal;
  12693. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  12694. for ( i = 0; i < 3; i ++ ) {
  12695. vn = vertexNormals[ i ];
  12696. normalArray[ offset_normal ] = vn.x;
  12697. normalArray[ offset_normal + 1 ] = vn.y;
  12698. normalArray[ offset_normal + 2 ] = vn.z;
  12699. offset_normal += 3;
  12700. }
  12701. } else {
  12702. for ( i = 0; i < 3; i ++ ) {
  12703. normalArray[ offset_normal ] = faceNormal.x;
  12704. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12705. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12706. offset_normal += 3;
  12707. }
  12708. }
  12709. }
  12710. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12711. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12712. }
  12713. if ( dirtyUvs && obj_uvs && uvType ) {
  12714. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12715. fi = chunk_faces3[ f ];
  12716. uv = obj_uvs[ fi ];
  12717. if ( uv === undefined ) continue;
  12718. for ( i = 0; i < 3; i ++ ) {
  12719. uvi = uv[ i ];
  12720. uvArray[ offset_uv ] = uvi.x;
  12721. uvArray[ offset_uv + 1 ] = uvi.y;
  12722. offset_uv += 2;
  12723. }
  12724. }
  12725. if ( offset_uv > 0 ) {
  12726. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12727. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  12728. }
  12729. }
  12730. if ( dirtyUvs && obj_uvs2 && uvType ) {
  12731. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12732. fi = chunk_faces3[ f ];
  12733. uv2 = obj_uvs2[ fi ];
  12734. if ( uv2 === undefined ) continue;
  12735. for ( i = 0; i < 3; i ++ ) {
  12736. uv2i = uv2[ i ];
  12737. uv2Array[ offset_uv2 ] = uv2i.x;
  12738. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12739. offset_uv2 += 2;
  12740. }
  12741. }
  12742. if ( offset_uv2 > 0 ) {
  12743. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12744. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  12745. }
  12746. }
  12747. if ( dirtyElements ) {
  12748. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12749. faceArray[ offset_face ] = vertexIndex;
  12750. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12751. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  12752. offset_face += 3;
  12753. lineArray[ offset_line ] = vertexIndex;
  12754. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12755. lineArray[ offset_line + 2 ] = vertexIndex;
  12756. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  12757. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12758. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12759. offset_line += 6;
  12760. vertexIndex += 3;
  12761. }
  12762. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12763. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  12764. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12765. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  12766. }
  12767. if ( customAttributes ) {
  12768. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12769. customAttribute = customAttributes[ i ];
  12770. if ( ! customAttribute.__original.needsUpdate ) continue;
  12771. offset_custom = 0;
  12772. offset_customSrc = 0;
  12773. if ( customAttribute.size === 1 ) {
  12774. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12775. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12776. face = obj_faces[ chunk_faces3[ f ] ];
  12777. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12778. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12779. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12780. offset_custom += 3;
  12781. }
  12782. } else if ( customAttribute.boundTo === "faces" ) {
  12783. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12784. value = customAttribute.value[ chunk_faces3[ f ] ];
  12785. customAttribute.array[ offset_custom ] = value;
  12786. customAttribute.array[ offset_custom + 1 ] = value;
  12787. customAttribute.array[ offset_custom + 2 ] = value;
  12788. offset_custom += 3;
  12789. }
  12790. }
  12791. } else if ( customAttribute.size === 2 ) {
  12792. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12793. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12794. face = obj_faces[ chunk_faces3[ f ] ];
  12795. v1 = customAttribute.value[ face.a ];
  12796. v2 = customAttribute.value[ face.b ];
  12797. v3 = customAttribute.value[ face.c ];
  12798. customAttribute.array[ offset_custom ] = v1.x;
  12799. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12800. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12801. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12802. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12803. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12804. offset_custom += 6;
  12805. }
  12806. } else if ( customAttribute.boundTo === "faces" ) {
  12807. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12808. value = customAttribute.value[ chunk_faces3[ f ] ];
  12809. v1 = value;
  12810. v2 = value;
  12811. v3 = value;
  12812. customAttribute.array[ offset_custom ] = v1.x;
  12813. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12814. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12815. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12816. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12817. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12818. offset_custom += 6;
  12819. }
  12820. }
  12821. } else if ( customAttribute.size === 3 ) {
  12822. var pp;
  12823. if ( customAttribute.type === "c" ) {
  12824. pp = [ "r", "g", "b" ];
  12825. } else {
  12826. pp = [ "x", "y", "z" ];
  12827. }
  12828. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12829. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12830. face = obj_faces[ chunk_faces3[ f ] ];
  12831. v1 = customAttribute.value[ face.a ];
  12832. v2 = customAttribute.value[ face.b ];
  12833. v3 = customAttribute.value[ face.c ];
  12834. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12835. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12836. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12837. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12838. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12839. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12840. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12841. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12842. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12843. offset_custom += 9;
  12844. }
  12845. } else if ( customAttribute.boundTo === "faces" ) {
  12846. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12847. value = customAttribute.value[ chunk_faces3[ f ] ];
  12848. v1 = value;
  12849. v2 = value;
  12850. v3 = value;
  12851. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12852. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12853. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12854. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12855. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12856. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12857. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12858. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12859. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12860. offset_custom += 9;
  12861. }
  12862. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12863. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12864. value = customAttribute.value[ chunk_faces3[ f ] ];
  12865. v1 = value[ 0 ];
  12866. v2 = value[ 1 ];
  12867. v3 = value[ 2 ];
  12868. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12869. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12870. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12871. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12872. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12873. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12874. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12875. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12876. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12877. offset_custom += 9;
  12878. }
  12879. }
  12880. } else if ( customAttribute.size === 4 ) {
  12881. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12882. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12883. face = obj_faces[ chunk_faces3[ f ] ];
  12884. v1 = customAttribute.value[ face.a ];
  12885. v2 = customAttribute.value[ face.b ];
  12886. v3 = customAttribute.value[ face.c ];
  12887. customAttribute.array[ offset_custom ] = v1.x;
  12888. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12889. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12890. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12891. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12892. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12893. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12894. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12895. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12896. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12897. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12898. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12899. offset_custom += 12;
  12900. }
  12901. } else if ( customAttribute.boundTo === "faces" ) {
  12902. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12903. value = customAttribute.value[ chunk_faces3[ f ] ];
  12904. v1 = value;
  12905. v2 = value;
  12906. v3 = value;
  12907. customAttribute.array[ offset_custom ] = v1.x;
  12908. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12909. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12910. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12911. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12912. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12913. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12914. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12915. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12916. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12917. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12918. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12919. offset_custom += 12;
  12920. }
  12921. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12922. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12923. value = customAttribute.value[ chunk_faces3[ f ] ];
  12924. v1 = value[ 0 ];
  12925. v2 = value[ 1 ];
  12926. v3 = value[ 2 ];
  12927. customAttribute.array[ offset_custom ] = v1.x;
  12928. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12929. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12930. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12931. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12932. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12933. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12934. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12935. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12936. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12937. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12938. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12939. offset_custom += 12;
  12940. }
  12941. }
  12942. }
  12943. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12944. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12945. }
  12946. }
  12947. if ( dispose ) {
  12948. delete geometryGroup.__inittedArrays;
  12949. delete geometryGroup.__colorArray;
  12950. delete geometryGroup.__normalArray;
  12951. delete geometryGroup.__tangentArray;
  12952. delete geometryGroup.__uvArray;
  12953. delete geometryGroup.__uv2Array;
  12954. delete geometryGroup.__faceArray;
  12955. delete geometryGroup.__vertexArray;
  12956. delete geometryGroup.__lineArray;
  12957. delete geometryGroup.__skinIndexArray;
  12958. delete geometryGroup.__skinWeightArray;
  12959. }
  12960. };
  12961. function setDirectBuffers ( geometry, hint, dispose ) {
  12962. var attributes = geometry.attributes;
  12963. var attributeName, attributeItem;
  12964. for ( attributeName in attributes ) {
  12965. attributeItem = attributes[ attributeName ];
  12966. if ( attributeItem.needsUpdate ) {
  12967. if ( attributeName === 'index' ) {
  12968. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  12969. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  12970. } else {
  12971. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  12972. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  12973. }
  12974. attributeItem.needsUpdate = false;
  12975. }
  12976. if ( dispose && ! attributeItem.dynamic ) {
  12977. attributeItem.array = null;
  12978. }
  12979. }
  12980. };
  12981. // Buffer rendering
  12982. this.renderBufferImmediate = function ( object, program, material ) {
  12983. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  12984. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  12985. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  12986. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  12987. if ( object.hasPositions ) {
  12988. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  12989. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12990. _gl.enableVertexAttribArray( program.attributes.position );
  12991. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12992. }
  12993. if ( object.hasNormals ) {
  12994. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  12995. if ( material.shading === THREE.FlatShading ) {
  12996. var nx, ny, nz,
  12997. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  12998. normalArray,
  12999. i, il = object.count * 3;
  13000. for( i = 0; i < il; i += 9 ) {
  13001. normalArray = object.normalArray;
  13002. nax = normalArray[ i ];
  13003. nay = normalArray[ i + 1 ];
  13004. naz = normalArray[ i + 2 ];
  13005. nbx = normalArray[ i + 3 ];
  13006. nby = normalArray[ i + 4 ];
  13007. nbz = normalArray[ i + 5 ];
  13008. ncx = normalArray[ i + 6 ];
  13009. ncy = normalArray[ i + 7 ];
  13010. ncz = normalArray[ i + 8 ];
  13011. nx = ( nax + nbx + ncx ) / 3;
  13012. ny = ( nay + nby + ncy ) / 3;
  13013. nz = ( naz + nbz + ncz ) / 3;
  13014. normalArray[ i ] = nx;
  13015. normalArray[ i + 1 ] = ny;
  13016. normalArray[ i + 2 ] = nz;
  13017. normalArray[ i + 3 ] = nx;
  13018. normalArray[ i + 4 ] = ny;
  13019. normalArray[ i + 5 ] = nz;
  13020. normalArray[ i + 6 ] = nx;
  13021. normalArray[ i + 7 ] = ny;
  13022. normalArray[ i + 8 ] = nz;
  13023. }
  13024. }
  13025. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13026. _gl.enableVertexAttribArray( program.attributes.normal );
  13027. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13028. }
  13029. if ( object.hasUvs && material.map ) {
  13030. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13031. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13032. _gl.enableVertexAttribArray( program.attributes.uv );
  13033. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13034. }
  13035. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13036. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13037. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13038. _gl.enableVertexAttribArray( program.attributes.color );
  13039. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13040. }
  13041. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13042. object.count = 0;
  13043. };
  13044. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13045. if ( material.visible === false ) return;
  13046. var linewidth, a, attribute;
  13047. var attributeItem, attributeName, attributePointer, attributeSize;
  13048. var program = setProgram( camera, lights, fog, material, object );
  13049. var programAttributes = program.attributes;
  13050. var geometryAttributes = geometry.attributes;
  13051. var updateBuffers = false,
  13052. wireframeBit = material.wireframe ? 1 : 0,
  13053. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13054. if ( geometryHash !== _currentGeometryGroupHash ) {
  13055. _currentGeometryGroupHash = geometryHash;
  13056. updateBuffers = true;
  13057. }
  13058. if ( updateBuffers ) {
  13059. disableAttributes();
  13060. }
  13061. // render mesh
  13062. if ( object instanceof THREE.Mesh ) {
  13063. var index = geometryAttributes[ "index" ];
  13064. // indexed triangles
  13065. if ( index ) {
  13066. var offsets = geometry.offsets;
  13067. // if there is more than 1 chunk
  13068. // must set attribute pointers to use new offsets for each chunk
  13069. // even if geometry and materials didn't change
  13070. if ( offsets.length > 1 ) updateBuffers = true;
  13071. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13072. var startIndex = offsets[ i ].index;
  13073. if ( updateBuffers ) {
  13074. for ( attributeName in programAttributes ) {
  13075. attributePointer = programAttributes[ attributeName ];
  13076. attributeItem = geometryAttributes[ attributeName ];
  13077. if ( attributePointer >= 0 ) {
  13078. if ( attributeItem ) {
  13079. attributeSize = attributeItem.itemSize;
  13080. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13081. enableAttribute( attributePointer );
  13082. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13083. } else if ( material.defaultAttributeValues ) {
  13084. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13085. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13086. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13087. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13088. }
  13089. }
  13090. }
  13091. }
  13092. // indices
  13093. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13094. }
  13095. // render indexed triangles
  13096. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  13097. _this.info.render.calls ++;
  13098. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13099. _this.info.render.faces += offsets[ i ].count / 3;
  13100. }
  13101. // non-indexed triangles
  13102. } else {
  13103. if ( updateBuffers ) {
  13104. for ( attributeName in programAttributes ) {
  13105. if ( attributeName === 'index') continue;
  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, 0 );
  13114. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  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. }
  13124. var position = geometry.attributes[ "position" ];
  13125. // render non-indexed triangles
  13126. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  13127. _this.info.render.calls ++;
  13128. _this.info.render.vertices += position.numItems / 3;
  13129. _this.info.render.faces += position.numItems / 3 / 3;
  13130. }
  13131. // render particles
  13132. } else if ( object instanceof THREE.ParticleSystem ) {
  13133. if ( updateBuffers ) {
  13134. for ( attributeName in programAttributes ) {
  13135. attributePointer = programAttributes[ attributeName ];
  13136. attributeItem = geometryAttributes[ attributeName ];
  13137. if ( attributePointer >= 0 ) {
  13138. if ( attributeItem ) {
  13139. attributeSize = attributeItem.itemSize;
  13140. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13141. enableAttribute( attributePointer );
  13142. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13143. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13144. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13145. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13146. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13147. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13148. }
  13149. }
  13150. }
  13151. }
  13152. var position = geometryAttributes[ "position" ];
  13153. // render particles
  13154. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  13155. _this.info.render.calls ++;
  13156. _this.info.render.points += position.numItems / 3;
  13157. }
  13158. } else if ( object instanceof THREE.Line ) {
  13159. if ( updateBuffers ) {
  13160. for ( attributeName in programAttributes ) {
  13161. attributePointer = programAttributes[ attributeName ];
  13162. attributeItem = geometryAttributes[ attributeName ];
  13163. if ( attributePointer >= 0 ) {
  13164. if ( attributeItem ) {
  13165. attributeSize = attributeItem.itemSize;
  13166. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13167. enableAttribute( attributePointer );
  13168. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13169. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13170. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13171. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13172. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13173. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13174. }
  13175. }
  13176. }
  13177. }
  13178. // render lines
  13179. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13180. setLineWidth( material.linewidth );
  13181. var position = geometryAttributes[ "position" ];
  13182. _gl.drawArrays( primitives, 0, position.numItems / 3 );
  13183. _this.info.render.calls ++;
  13184. _this.info.render.points += position.numItems;
  13185. }
  13186. }
  13187. };
  13188. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13189. if ( material.visible === false ) return;
  13190. var linewidth, a, attribute, i, il;
  13191. var program = setProgram( camera, lights, fog, material, object );
  13192. var attributes = program.attributes;
  13193. var updateBuffers = false,
  13194. wireframeBit = material.wireframe ? 1 : 0,
  13195. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13196. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13197. _currentGeometryGroupHash = geometryGroupHash;
  13198. updateBuffers = true;
  13199. }
  13200. if ( updateBuffers ) {
  13201. disableAttributes();
  13202. }
  13203. // vertices
  13204. if ( !material.morphTargets && attributes.position >= 0 ) {
  13205. if ( updateBuffers ) {
  13206. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13207. enableAttribute( attributes.position );
  13208. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13209. }
  13210. } else {
  13211. if ( object.morphTargetBase ) {
  13212. setupMorphTargets( material, geometryGroup, object );
  13213. }
  13214. }
  13215. if ( updateBuffers ) {
  13216. // custom attributes
  13217. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13218. if ( geometryGroup.__webglCustomAttributesList ) {
  13219. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13220. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13221. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13222. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13223. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13224. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13225. }
  13226. }
  13227. }
  13228. // colors
  13229. if ( attributes.color >= 0 ) {
  13230. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  13231. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13232. enableAttribute( attributes.color );
  13233. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13234. } else if ( material.defaultAttributeValues ) {
  13235. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  13236. }
  13237. }
  13238. // normals
  13239. if ( attributes.normal >= 0 ) {
  13240. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13241. enableAttribute( attributes.normal );
  13242. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13243. }
  13244. // tangents
  13245. if ( attributes.tangent >= 0 ) {
  13246. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13247. enableAttribute( attributes.tangent );
  13248. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13249. }
  13250. // uvs
  13251. if ( attributes.uv >= 0 ) {
  13252. if ( object.geometry.faceVertexUvs[0] ) {
  13253. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13254. enableAttribute( attributes.uv );
  13255. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13256. } else if ( material.defaultAttributeValues ) {
  13257. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  13258. }
  13259. }
  13260. if ( attributes.uv2 >= 0 ) {
  13261. if ( object.geometry.faceVertexUvs[1] ) {
  13262. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13263. enableAttribute( attributes.uv2 );
  13264. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13265. } else if ( material.defaultAttributeValues ) {
  13266. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  13267. }
  13268. }
  13269. if ( material.skinning &&
  13270. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13271. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13272. enableAttribute( attributes.skinIndex );
  13273. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13274. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13275. enableAttribute( attributes.skinWeight );
  13276. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13277. }
  13278. // line distances
  13279. if ( attributes.lineDistance >= 0 ) {
  13280. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13281. enableAttribute( attributes.lineDistance );
  13282. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13283. }
  13284. }
  13285. // render mesh
  13286. if ( object instanceof THREE.Mesh ) {
  13287. // wireframe
  13288. if ( material.wireframe ) {
  13289. setLineWidth( material.wireframeLinewidth );
  13290. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13291. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  13292. // triangles
  13293. } else {
  13294. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13295. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  13296. }
  13297. _this.info.render.calls ++;
  13298. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13299. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13300. // render lines
  13301. } else if ( object instanceof THREE.Line ) {
  13302. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13303. setLineWidth( material.linewidth );
  13304. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  13305. _this.info.render.calls ++;
  13306. // render particles
  13307. } else if ( object instanceof THREE.ParticleSystem ) {
  13308. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13309. _this.info.render.calls ++;
  13310. _this.info.render.points += geometryGroup.__webglParticleCount;
  13311. }
  13312. };
  13313. function enableAttribute( attribute ) {
  13314. if ( ! _enabledAttributes[ attribute ] ) {
  13315. _gl.enableVertexAttribArray( attribute );
  13316. _enabledAttributes[ attribute ] = true;
  13317. }
  13318. };
  13319. function disableAttributes() {
  13320. for ( var attribute in _enabledAttributes ) {
  13321. if ( _enabledAttributes[ attribute ] ) {
  13322. _gl.disableVertexAttribArray( attribute );
  13323. _enabledAttributes[ attribute ] = false;
  13324. }
  13325. }
  13326. };
  13327. function setupMorphTargets ( material, geometryGroup, object ) {
  13328. // set base
  13329. var attributes = material.program.attributes;
  13330. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13331. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13332. enableAttribute( attributes.position );
  13333. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13334. } else if ( attributes.position >= 0 ) {
  13335. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13336. enableAttribute( attributes.position );
  13337. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13338. }
  13339. if ( object.morphTargetForcedOrder.length ) {
  13340. // set forced order
  13341. var m = 0;
  13342. var order = object.morphTargetForcedOrder;
  13343. var influences = object.morphTargetInfluences;
  13344. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13345. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13346. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13347. enableAttribute( attributes[ "morphTarget" + m ] );
  13348. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13349. }
  13350. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13351. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13352. enableAttribute( attributes[ "morphNormal" + m ] );
  13353. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13354. }
  13355. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13356. m ++;
  13357. }
  13358. } else {
  13359. // find the most influencing
  13360. var influence, activeInfluenceIndices = [];
  13361. var influences = object.morphTargetInfluences;
  13362. var i, il = influences.length;
  13363. for ( i = 0; i < il; i ++ ) {
  13364. influence = influences[ i ];
  13365. if ( influence > 0 ) {
  13366. activeInfluenceIndices.push( [ influence, i ] );
  13367. }
  13368. }
  13369. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13370. activeInfluenceIndices.sort( numericalSort );
  13371. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13372. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13373. activeInfluenceIndices.sort( numericalSort );
  13374. } else if ( activeInfluenceIndices.length === 0 ) {
  13375. activeInfluenceIndices.push( [ 0, 0 ] );
  13376. };
  13377. var influenceIndex, m = 0;
  13378. while ( m < material.numSupportedMorphTargets ) {
  13379. if ( activeInfluenceIndices[ m ] ) {
  13380. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13381. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13382. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13383. enableAttribute( attributes[ "morphTarget" + m ] );
  13384. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13385. }
  13386. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13387. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13388. enableAttribute( attributes[ "morphNormal" + m ] );
  13389. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13390. }
  13391. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13392. } else {
  13393. /*
  13394. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13395. if ( material.morphNormals ) {
  13396. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13397. }
  13398. */
  13399. object.__webglMorphTargetInfluences[ m ] = 0;
  13400. }
  13401. m ++;
  13402. }
  13403. }
  13404. // load updated influences uniform
  13405. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13406. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13407. }
  13408. };
  13409. // Sorting
  13410. function painterSortStable ( a, b ) {
  13411. if ( a.z !== b.z ) {
  13412. return b.z - a.z;
  13413. } else {
  13414. return a.id - b.id;
  13415. }
  13416. };
  13417. function numericalSort ( a, b ) {
  13418. return b[ 0 ] - a[ 0 ];
  13419. };
  13420. // Rendering
  13421. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13422. if ( camera instanceof THREE.Camera === false ) {
  13423. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13424. return;
  13425. }
  13426. var i, il,
  13427. webglObject, object,
  13428. renderList,
  13429. lights = scene.__lights,
  13430. fog = scene.fog;
  13431. // reset caching for this frame
  13432. _currentMaterialId = -1;
  13433. _lightsNeedUpdate = true;
  13434. // update scene graph
  13435. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13436. // update camera matrices and frustum
  13437. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13438. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13439. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13440. _frustum.setFromMatrix( _projScreenMatrix );
  13441. // update WebGL objects
  13442. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13443. // custom render plugins (pre pass)
  13444. renderPlugins( this.renderPluginsPre, scene, camera );
  13445. //
  13446. _this.info.render.calls = 0;
  13447. _this.info.render.vertices = 0;
  13448. _this.info.render.faces = 0;
  13449. _this.info.render.points = 0;
  13450. this.setRenderTarget( renderTarget );
  13451. if ( this.autoClear || forceClear ) {
  13452. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13453. }
  13454. // set matrices for regular objects (frustum culled)
  13455. renderList = scene.__webglObjects;
  13456. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13457. webglObject = renderList[ i ];
  13458. object = webglObject.object;
  13459. webglObject.id = i;
  13460. webglObject.render = false;
  13461. if ( object.visible ) {
  13462. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  13463. setupMatrices( object, camera );
  13464. unrollBufferMaterial( webglObject );
  13465. webglObject.render = true;
  13466. if ( this.sortObjects === true ) {
  13467. if ( object.renderDepth !== null ) {
  13468. webglObject.z = object.renderDepth;
  13469. } else {
  13470. _vector3.getPositionFromMatrix( object.matrixWorld );
  13471. _vector3.applyProjection( _projScreenMatrix );
  13472. webglObject.z = _vector3.z;
  13473. }
  13474. }
  13475. }
  13476. }
  13477. }
  13478. if ( this.sortObjects ) {
  13479. renderList.sort( painterSortStable );
  13480. }
  13481. // set matrices for immediate objects
  13482. renderList = scene.__webglObjectsImmediate;
  13483. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13484. webglObject = renderList[ i ];
  13485. object = webglObject.object;
  13486. if ( object.visible ) {
  13487. setupMatrices( object, camera );
  13488. unrollImmediateBufferMaterial( webglObject );
  13489. }
  13490. }
  13491. if ( scene.overrideMaterial ) {
  13492. var material = scene.overrideMaterial;
  13493. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13494. this.setDepthTest( material.depthTest );
  13495. this.setDepthWrite( material.depthWrite );
  13496. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13497. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13498. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13499. } else {
  13500. var material = null;
  13501. // opaque pass (front-to-back order)
  13502. this.setBlending( THREE.NoBlending );
  13503. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13504. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13505. // transparent pass (back-to-front order)
  13506. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13507. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13508. }
  13509. // custom render plugins (post pass)
  13510. renderPlugins( this.renderPluginsPost, scene, camera );
  13511. // Generate mipmap if we're using any kind of mipmap filtering
  13512. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13513. updateRenderTargetMipmap( renderTarget );
  13514. }
  13515. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13516. this.setDepthTest( true );
  13517. this.setDepthWrite( true );
  13518. // _gl.finish();
  13519. };
  13520. function renderPlugins( plugins, scene, camera ) {
  13521. if ( ! plugins.length ) return;
  13522. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13523. // reset state for plugin (to start from clean slate)
  13524. _currentProgram = null;
  13525. _currentCamera = null;
  13526. _oldBlending = -1;
  13527. _oldDepthTest = -1;
  13528. _oldDepthWrite = -1;
  13529. _oldDoubleSided = -1;
  13530. _oldFlipSided = -1;
  13531. _currentGeometryGroupHash = -1;
  13532. _currentMaterialId = -1;
  13533. _lightsNeedUpdate = true;
  13534. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13535. // reset state after plugin (anything could have changed)
  13536. _currentProgram = null;
  13537. _currentCamera = null;
  13538. _oldBlending = -1;
  13539. _oldDepthTest = -1;
  13540. _oldDepthWrite = -1;
  13541. _oldDoubleSided = -1;
  13542. _oldFlipSided = -1;
  13543. _currentGeometryGroupHash = -1;
  13544. _currentMaterialId = -1;
  13545. _lightsNeedUpdate = true;
  13546. }
  13547. };
  13548. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13549. var webglObject, object, buffer, material, start, end, delta;
  13550. if ( reverse ) {
  13551. start = renderList.length - 1;
  13552. end = -1;
  13553. delta = -1;
  13554. } else {
  13555. start = 0;
  13556. end = renderList.length;
  13557. delta = 1;
  13558. }
  13559. for ( var i = start; i !== end; i += delta ) {
  13560. webglObject = renderList[ i ];
  13561. if ( webglObject.render ) {
  13562. object = webglObject.object;
  13563. buffer = webglObject.buffer;
  13564. if ( overrideMaterial ) {
  13565. material = overrideMaterial;
  13566. } else {
  13567. material = webglObject[ materialType ];
  13568. if ( ! material ) continue;
  13569. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13570. _this.setDepthTest( material.depthTest );
  13571. _this.setDepthWrite( material.depthWrite );
  13572. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13573. }
  13574. _this.setMaterialFaces( material );
  13575. if ( buffer instanceof THREE.BufferGeometry ) {
  13576. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  13577. } else {
  13578. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  13579. }
  13580. }
  13581. }
  13582. };
  13583. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13584. var webglObject, object, material, program;
  13585. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13586. webglObject = renderList[ i ];
  13587. object = webglObject.object;
  13588. if ( object.visible ) {
  13589. if ( overrideMaterial ) {
  13590. material = overrideMaterial;
  13591. } else {
  13592. material = webglObject[ materialType ];
  13593. if ( ! material ) continue;
  13594. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13595. _this.setDepthTest( material.depthTest );
  13596. _this.setDepthWrite( material.depthWrite );
  13597. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13598. }
  13599. _this.renderImmediateObject( camera, lights, fog, material, object );
  13600. }
  13601. }
  13602. };
  13603. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13604. var program = setProgram( camera, lights, fog, material, object );
  13605. _currentGeometryGroupHash = -1;
  13606. _this.setMaterialFaces( material );
  13607. if ( object.immediateRenderCallback ) {
  13608. object.immediateRenderCallback( program, _gl, _frustum );
  13609. } else {
  13610. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13611. }
  13612. };
  13613. function unrollImmediateBufferMaterial ( globject ) {
  13614. var object = globject.object,
  13615. material = object.material;
  13616. if ( material.transparent ) {
  13617. globject.transparent = material;
  13618. globject.opaque = null;
  13619. } else {
  13620. globject.opaque = material;
  13621. globject.transparent = null;
  13622. }
  13623. };
  13624. function unrollBufferMaterial ( globject ) {
  13625. var object = globject.object,
  13626. buffer = globject.buffer,
  13627. material, materialIndex, meshMaterial;
  13628. meshMaterial = object.material;
  13629. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  13630. materialIndex = buffer.materialIndex;
  13631. material = meshMaterial.materials[ materialIndex ];
  13632. if ( material.transparent ) {
  13633. globject.transparent = material;
  13634. globject.opaque = null;
  13635. } else {
  13636. globject.opaque = material;
  13637. globject.transparent = null;
  13638. }
  13639. } else {
  13640. material = meshMaterial;
  13641. if ( material ) {
  13642. if ( material.transparent ) {
  13643. globject.transparent = material;
  13644. globject.opaque = null;
  13645. } else {
  13646. globject.opaque = material;
  13647. globject.transparent = null;
  13648. }
  13649. }
  13650. }
  13651. };
  13652. // Geometry splitting
  13653. function sortFacesByMaterial ( geometry, material ) {
  13654. var f, fl, face, materialIndex, vertices,
  13655. groupHash, hash_map = {};
  13656. var numMorphTargets = geometry.morphTargets.length;
  13657. var numMorphNormals = geometry.morphNormals.length;
  13658. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  13659. geometry.geometryGroups = {};
  13660. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  13661. face = geometry.faces[ f ];
  13662. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  13663. if ( hash_map[ materialIndex ] === undefined ) {
  13664. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  13665. }
  13666. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13667. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13668. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13669. }
  13670. vertices = 3;
  13671. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  13672. hash_map[ materialIndex ].counter += 1;
  13673. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13674. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13675. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13676. }
  13677. }
  13678. geometry.geometryGroups[ groupHash ].faces3.push( f );
  13679. geometry.geometryGroups[ groupHash ].vertices += vertices;
  13680. }
  13681. geometry.geometryGroupsList = [];
  13682. for ( var g in geometry.geometryGroups ) {
  13683. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  13684. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  13685. }
  13686. };
  13687. // Objects refresh
  13688. this.initWebGLObjects = function ( scene ) {
  13689. if ( !scene.__webglObjects ) {
  13690. scene.__webglObjects = [];
  13691. scene.__webglObjectsImmediate = [];
  13692. scene.__webglSprites = [];
  13693. scene.__webglFlares = [];
  13694. }
  13695. while ( scene.__objectsAdded.length ) {
  13696. addObject( scene.__objectsAdded[ 0 ], scene );
  13697. scene.__objectsAdded.splice( 0, 1 );
  13698. }
  13699. while ( scene.__objectsRemoved.length ) {
  13700. removeObject( scene.__objectsRemoved[ 0 ], scene );
  13701. scene.__objectsRemoved.splice( 0, 1 );
  13702. }
  13703. // update must be called after objects adding / removal
  13704. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  13705. var object = scene.__webglObjects[ o ].object;
  13706. // TODO: Remove this hack (WebGLRenderer refactoring)
  13707. if ( object.__webglInit === undefined ) {
  13708. if ( object.__webglActive !== undefined ) {
  13709. removeObject( object, scene );
  13710. }
  13711. addObject( object, scene );
  13712. }
  13713. updateObject( object );
  13714. }
  13715. };
  13716. // Objects adding
  13717. function addObject( object, scene ) {
  13718. var g, geometry, material, geometryGroup;
  13719. if ( object.__webglInit === undefined ) {
  13720. object.__webglInit = true;
  13721. object._modelViewMatrix = new THREE.Matrix4();
  13722. object._normalMatrix = new THREE.Matrix3();
  13723. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  13724. object.geometry.__webglInit = true;
  13725. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  13726. }
  13727. geometry = object.geometry;
  13728. if ( geometry === undefined ) {
  13729. // fail silently for now
  13730. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13731. initDirectBuffers( geometry );
  13732. } else if ( object instanceof THREE.Mesh ) {
  13733. material = object.material;
  13734. if ( geometry.geometryGroups === undefined ) {
  13735. sortFacesByMaterial( geometry, material );
  13736. }
  13737. // create separate VBOs per geometry chunk
  13738. for ( g in geometry.geometryGroups ) {
  13739. geometryGroup = geometry.geometryGroups[ g ];
  13740. // initialise VBO on the first access
  13741. if ( ! geometryGroup.__webglVertexBuffer ) {
  13742. createMeshBuffers( geometryGroup );
  13743. initMeshBuffers( geometryGroup, object );
  13744. geometry.verticesNeedUpdate = true;
  13745. geometry.morphTargetsNeedUpdate = true;
  13746. geometry.elementsNeedUpdate = true;
  13747. geometry.uvsNeedUpdate = true;
  13748. geometry.normalsNeedUpdate = true;
  13749. geometry.tangentsNeedUpdate = true;
  13750. geometry.colorsNeedUpdate = true;
  13751. }
  13752. }
  13753. } else if ( object instanceof THREE.Line ) {
  13754. if ( ! geometry.__webglVertexBuffer ) {
  13755. createLineBuffers( geometry );
  13756. initLineBuffers( geometry, object );
  13757. geometry.verticesNeedUpdate = true;
  13758. geometry.colorsNeedUpdate = true;
  13759. geometry.lineDistancesNeedUpdate = true;
  13760. }
  13761. } else if ( object instanceof THREE.ParticleSystem ) {
  13762. if ( ! geometry.__webglVertexBuffer ) {
  13763. createParticleBuffers( geometry );
  13764. initParticleBuffers( geometry, object );
  13765. geometry.verticesNeedUpdate = true;
  13766. geometry.colorsNeedUpdate = true;
  13767. }
  13768. }
  13769. }
  13770. if ( object.__webglActive === undefined ) {
  13771. if ( object instanceof THREE.Mesh ) {
  13772. geometry = object.geometry;
  13773. if ( geometry instanceof THREE.BufferGeometry ) {
  13774. addBuffer( scene.__webglObjects, geometry, object );
  13775. } else if ( geometry instanceof THREE.Geometry ) {
  13776. for ( g in geometry.geometryGroups ) {
  13777. geometryGroup = geometry.geometryGroups[ g ];
  13778. addBuffer( scene.__webglObjects, geometryGroup, object );
  13779. }
  13780. }
  13781. } else if ( object instanceof THREE.Line ||
  13782. object instanceof THREE.ParticleSystem ) {
  13783. geometry = object.geometry;
  13784. addBuffer( scene.__webglObjects, geometry, object );
  13785. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13786. addBufferImmediate( scene.__webglObjectsImmediate, object );
  13787. } else if ( object instanceof THREE.Sprite ) {
  13788. scene.__webglSprites.push( object );
  13789. } else if ( object instanceof THREE.LensFlare ) {
  13790. scene.__webglFlares.push( object );
  13791. }
  13792. object.__webglActive = true;
  13793. }
  13794. };
  13795. function addBuffer( objlist, buffer, object ) {
  13796. objlist.push(
  13797. {
  13798. id: null,
  13799. buffer: buffer,
  13800. object: object,
  13801. opaque: null,
  13802. transparent: null,
  13803. z: 0
  13804. }
  13805. );
  13806. };
  13807. function addBufferImmediate( objlist, object ) {
  13808. objlist.push(
  13809. {
  13810. id: null,
  13811. object: object,
  13812. opaque: null,
  13813. transparent: null,
  13814. z: 0
  13815. }
  13816. );
  13817. };
  13818. // Objects updates
  13819. function updateObject( object ) {
  13820. var geometry = object.geometry,
  13821. geometryGroup, customAttributesDirty, material;
  13822. if ( geometry instanceof THREE.BufferGeometry ) {
  13823. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13824. } else if ( object instanceof THREE.Mesh ) {
  13825. // check all geometry groups
  13826. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  13827. geometryGroup = geometry.geometryGroupsList[ i ];
  13828. material = getBufferMaterial( object, geometryGroup );
  13829. if ( geometry.buffersNeedUpdate ) {
  13830. initMeshBuffers( geometryGroup, object );
  13831. }
  13832. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13833. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  13834. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13835. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  13836. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  13837. }
  13838. }
  13839. geometry.verticesNeedUpdate = false;
  13840. geometry.morphTargetsNeedUpdate = false;
  13841. geometry.elementsNeedUpdate = false;
  13842. geometry.uvsNeedUpdate = false;
  13843. geometry.normalsNeedUpdate = false;
  13844. geometry.colorsNeedUpdate = false;
  13845. geometry.tangentsNeedUpdate = false;
  13846. geometry.buffersNeedUpdate = false;
  13847. material.attributes && clearCustomAttributes( material );
  13848. } else if ( object instanceof THREE.Line ) {
  13849. material = getBufferMaterial( object, geometry );
  13850. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13851. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  13852. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  13853. }
  13854. geometry.verticesNeedUpdate = false;
  13855. geometry.colorsNeedUpdate = false;
  13856. geometry.lineDistancesNeedUpdate = false;
  13857. material.attributes && clearCustomAttributes( material );
  13858. } else if ( object instanceof THREE.ParticleSystem ) {
  13859. material = getBufferMaterial( object, geometry );
  13860. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13861. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  13862. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  13863. }
  13864. geometry.verticesNeedUpdate = false;
  13865. geometry.colorsNeedUpdate = false;
  13866. material.attributes && clearCustomAttributes( material );
  13867. }
  13868. };
  13869. // Objects updates - custom attributes check
  13870. function areCustomAttributesDirty( material ) {
  13871. for ( var a in material.attributes ) {
  13872. if ( material.attributes[ a ].needsUpdate ) return true;
  13873. }
  13874. return false;
  13875. };
  13876. function clearCustomAttributes( material ) {
  13877. for ( var a in material.attributes ) {
  13878. material.attributes[ a ].needsUpdate = false;
  13879. }
  13880. };
  13881. // Objects removal
  13882. function removeObject( object, scene ) {
  13883. if ( object instanceof THREE.Mesh ||
  13884. object instanceof THREE.ParticleSystem ||
  13885. object instanceof THREE.Line ) {
  13886. removeInstances( scene.__webglObjects, object );
  13887. } else if ( object instanceof THREE.Sprite ) {
  13888. removeInstancesDirect( scene.__webglSprites, object );
  13889. } else if ( object instanceof THREE.LensFlare ) {
  13890. removeInstancesDirect( scene.__webglFlares, object );
  13891. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13892. removeInstances( scene.__webglObjectsImmediate, object );
  13893. }
  13894. delete object.__webglActive;
  13895. };
  13896. function removeInstances( objlist, object ) {
  13897. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13898. if ( objlist[ o ].object === object ) {
  13899. objlist.splice( o, 1 );
  13900. }
  13901. }
  13902. };
  13903. function removeInstancesDirect( objlist, object ) {
  13904. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13905. if ( objlist[ o ] === object ) {
  13906. objlist.splice( o, 1 );
  13907. }
  13908. }
  13909. };
  13910. // Materials
  13911. this.initMaterial = function ( material, lights, fog, object ) {
  13912. material.addEventListener( 'dispose', onMaterialDispose );
  13913. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  13914. if ( material instanceof THREE.MeshDepthMaterial ) {
  13915. shaderID = 'depth';
  13916. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13917. shaderID = 'normal';
  13918. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  13919. shaderID = 'basic';
  13920. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13921. shaderID = 'lambert';
  13922. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13923. shaderID = 'phong';
  13924. } else if ( material instanceof THREE.LineBasicMaterial ) {
  13925. shaderID = 'basic';
  13926. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13927. shaderID = 'dashed';
  13928. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  13929. shaderID = 'particle_basic';
  13930. }
  13931. if ( shaderID ) {
  13932. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  13933. }
  13934. // heuristics to create shader parameters according to lights in the scene
  13935. // (not to blow over maxLights budget)
  13936. maxLightCount = allocateLights( lights );
  13937. maxShadows = allocateShadows( lights );
  13938. maxBones = allocateBones( object );
  13939. parameters = {
  13940. map: !!material.map,
  13941. envMap: !!material.envMap,
  13942. lightMap: !!material.lightMap,
  13943. bumpMap: !!material.bumpMap,
  13944. normalMap: !!material.normalMap,
  13945. specularMap: !!material.specularMap,
  13946. vertexColors: material.vertexColors,
  13947. fog: fog,
  13948. useFog: material.fog,
  13949. fogExp: fog instanceof THREE.FogExp2,
  13950. sizeAttenuation: material.sizeAttenuation,
  13951. skinning: material.skinning,
  13952. maxBones: maxBones,
  13953. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  13954. morphTargets: material.morphTargets,
  13955. morphNormals: material.morphNormals,
  13956. maxMorphTargets: this.maxMorphTargets,
  13957. maxMorphNormals: this.maxMorphNormals,
  13958. maxDirLights: maxLightCount.directional,
  13959. maxPointLights: maxLightCount.point,
  13960. maxSpotLights: maxLightCount.spot,
  13961. maxHemiLights: maxLightCount.hemi,
  13962. maxShadows: maxShadows,
  13963. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  13964. shadowMapType: this.shadowMapType,
  13965. shadowMapDebug: this.shadowMapDebug,
  13966. shadowMapCascade: this.shadowMapCascade,
  13967. alphaTest: material.alphaTest,
  13968. metal: material.metal,
  13969. perPixel: material.perPixel,
  13970. wrapAround: material.wrapAround,
  13971. doubleSided: material.side === THREE.DoubleSide,
  13972. flipSided: material.side === THREE.BackSide
  13973. };
  13974. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters, material.index0AttributeName );
  13975. var attributes = material.program.attributes;
  13976. if ( material.morphTargets ) {
  13977. material.numSupportedMorphTargets = 0;
  13978. var id, base = "morphTarget";
  13979. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  13980. id = base + i;
  13981. if ( attributes[ id ] >= 0 ) {
  13982. material.numSupportedMorphTargets ++;
  13983. }
  13984. }
  13985. }
  13986. if ( material.morphNormals ) {
  13987. material.numSupportedMorphNormals = 0;
  13988. var id, base = "morphNormal";
  13989. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  13990. id = base + i;
  13991. if ( attributes[ id ] >= 0 ) {
  13992. material.numSupportedMorphNormals ++;
  13993. }
  13994. }
  13995. }
  13996. material.uniformsList = [];
  13997. for ( u in material.uniforms ) {
  13998. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  13999. }
  14000. };
  14001. function setMaterialShaders( material, shaders ) {
  14002. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14003. material.vertexShader = shaders.vertexShader;
  14004. material.fragmentShader = shaders.fragmentShader;
  14005. };
  14006. function setProgram( camera, lights, fog, material, object ) {
  14007. _usedTextureUnits = 0;
  14008. if ( material.needsUpdate ) {
  14009. if ( material.program ) deallocateMaterial( material );
  14010. _this.initMaterial( material, lights, fog, object );
  14011. material.needsUpdate = false;
  14012. }
  14013. if ( material.morphTargets ) {
  14014. if ( ! object.__webglMorphTargetInfluences ) {
  14015. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14016. }
  14017. }
  14018. var refreshMaterial = false;
  14019. var program = material.program,
  14020. p_uniforms = program.uniforms,
  14021. m_uniforms = material.uniforms;
  14022. if ( program !== _currentProgram ) {
  14023. _gl.useProgram( program );
  14024. _currentProgram = program;
  14025. refreshMaterial = true;
  14026. }
  14027. if ( material.id !== _currentMaterialId ) {
  14028. _currentMaterialId = material.id;
  14029. refreshMaterial = true;
  14030. }
  14031. if ( refreshMaterial || camera !== _currentCamera ) {
  14032. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14033. if ( camera !== _currentCamera ) _currentCamera = camera;
  14034. }
  14035. // skinning uniforms must be set even if material didn't change
  14036. // auto-setting of texture unit for bone texture must go before other textures
  14037. // not sure why, but otherwise weird things happen
  14038. if ( material.skinning ) {
  14039. if ( _supportsBoneTextures && object.useVertexTexture ) {
  14040. if ( p_uniforms.boneTexture !== null ) {
  14041. var textureUnit = getTextureUnit();
  14042. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14043. _this.setTexture( object.boneTexture, textureUnit );
  14044. }
  14045. if ( p_uniforms.boneTextureWidth !== null ) {
  14046. _gl.uniform1i( p_uniforms.boneTextureWidth, object.boneTextureWidth );
  14047. }
  14048. if ( p_uniforms.boneTextureHeight !== null ) {
  14049. _gl.uniform1i( p_uniforms.boneTextureHeight, object.boneTextureHeight );
  14050. }
  14051. } else {
  14052. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14053. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  14054. }
  14055. }
  14056. }
  14057. if ( refreshMaterial ) {
  14058. // refresh uniforms common to several materials
  14059. if ( fog && material.fog ) {
  14060. refreshUniformsFog( m_uniforms, fog );
  14061. }
  14062. if ( material instanceof THREE.MeshPhongMaterial ||
  14063. material instanceof THREE.MeshLambertMaterial ||
  14064. material.lights ) {
  14065. if ( _lightsNeedUpdate ) {
  14066. setupLights( program, lights );
  14067. _lightsNeedUpdate = false;
  14068. }
  14069. refreshUniformsLights( m_uniforms, _lights );
  14070. }
  14071. if ( material instanceof THREE.MeshBasicMaterial ||
  14072. material instanceof THREE.MeshLambertMaterial ||
  14073. material instanceof THREE.MeshPhongMaterial ) {
  14074. refreshUniformsCommon( m_uniforms, material );
  14075. }
  14076. // refresh single material specific uniforms
  14077. if ( material instanceof THREE.LineBasicMaterial ) {
  14078. refreshUniformsLine( m_uniforms, material );
  14079. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14080. refreshUniformsLine( m_uniforms, material );
  14081. refreshUniformsDash( m_uniforms, material );
  14082. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  14083. refreshUniformsParticle( m_uniforms, material );
  14084. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14085. refreshUniformsPhong( m_uniforms, material );
  14086. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14087. refreshUniformsLambert( m_uniforms, material );
  14088. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14089. m_uniforms.mNear.value = camera.near;
  14090. m_uniforms.mFar.value = camera.far;
  14091. m_uniforms.opacity.value = material.opacity;
  14092. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14093. m_uniforms.opacity.value = material.opacity;
  14094. }
  14095. if ( object.receiveShadow && ! material._shadowPass ) {
  14096. refreshUniformsShadow( m_uniforms, lights );
  14097. }
  14098. // load common uniforms
  14099. loadUniformsGeneric( program, material.uniformsList );
  14100. // load material specific uniforms
  14101. // (shader material also gets them for the sake of genericity)
  14102. if ( material instanceof THREE.ShaderMaterial ||
  14103. material instanceof THREE.MeshPhongMaterial ||
  14104. material.envMap ) {
  14105. if ( p_uniforms.cameraPosition !== null ) {
  14106. _vector3.getPositionFromMatrix( camera.matrixWorld );
  14107. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14108. }
  14109. }
  14110. if ( material instanceof THREE.MeshPhongMaterial ||
  14111. material instanceof THREE.MeshLambertMaterial ||
  14112. material instanceof THREE.ShaderMaterial ||
  14113. material.skinning ) {
  14114. if ( p_uniforms.viewMatrix !== null ) {
  14115. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14116. }
  14117. }
  14118. }
  14119. loadUniformsMatrices( p_uniforms, object );
  14120. if ( p_uniforms.modelMatrix !== null ) {
  14121. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14122. }
  14123. return program;
  14124. };
  14125. // Uniforms (refresh uniforms objects)
  14126. function refreshUniformsCommon ( uniforms, material ) {
  14127. uniforms.opacity.value = material.opacity;
  14128. if ( _this.gammaInput ) {
  14129. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14130. } else {
  14131. uniforms.diffuse.value = material.color;
  14132. }
  14133. uniforms.map.value = material.map;
  14134. uniforms.lightMap.value = material.lightMap;
  14135. uniforms.specularMap.value = material.specularMap;
  14136. if ( material.bumpMap ) {
  14137. uniforms.bumpMap.value = material.bumpMap;
  14138. uniforms.bumpScale.value = material.bumpScale;
  14139. }
  14140. if ( material.normalMap ) {
  14141. uniforms.normalMap.value = material.normalMap;
  14142. uniforms.normalScale.value.copy( material.normalScale );
  14143. }
  14144. // uv repeat and offset setting priorities
  14145. // 1. color map
  14146. // 2. specular map
  14147. // 3. normal map
  14148. // 4. bump map
  14149. var uvScaleMap;
  14150. if ( material.map ) {
  14151. uvScaleMap = material.map;
  14152. } else if ( material.specularMap ) {
  14153. uvScaleMap = material.specularMap;
  14154. } else if ( material.normalMap ) {
  14155. uvScaleMap = material.normalMap;
  14156. } else if ( material.bumpMap ) {
  14157. uvScaleMap = material.bumpMap;
  14158. }
  14159. if ( uvScaleMap !== undefined ) {
  14160. var offset = uvScaleMap.offset;
  14161. var repeat = uvScaleMap.repeat;
  14162. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14163. }
  14164. uniforms.envMap.value = material.envMap;
  14165. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14166. if ( _this.gammaInput ) {
  14167. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14168. uniforms.reflectivity.value = material.reflectivity;
  14169. } else {
  14170. uniforms.reflectivity.value = material.reflectivity;
  14171. }
  14172. uniforms.refractionRatio.value = material.refractionRatio;
  14173. uniforms.combine.value = material.combine;
  14174. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14175. };
  14176. function refreshUniformsLine ( uniforms, material ) {
  14177. uniforms.diffuse.value = material.color;
  14178. uniforms.opacity.value = material.opacity;
  14179. };
  14180. function refreshUniformsDash ( uniforms, material ) {
  14181. uniforms.dashSize.value = material.dashSize;
  14182. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14183. uniforms.scale.value = material.scale;
  14184. };
  14185. function refreshUniformsParticle ( uniforms, material ) {
  14186. uniforms.psColor.value = material.color;
  14187. uniforms.opacity.value = material.opacity;
  14188. uniforms.size.value = material.size;
  14189. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14190. uniforms.map.value = material.map;
  14191. };
  14192. function refreshUniformsFog ( uniforms, fog ) {
  14193. uniforms.fogColor.value = fog.color;
  14194. if ( fog instanceof THREE.Fog ) {
  14195. uniforms.fogNear.value = fog.near;
  14196. uniforms.fogFar.value = fog.far;
  14197. } else if ( fog instanceof THREE.FogExp2 ) {
  14198. uniforms.fogDensity.value = fog.density;
  14199. }
  14200. };
  14201. function refreshUniformsPhong ( uniforms, material ) {
  14202. uniforms.shininess.value = material.shininess;
  14203. if ( _this.gammaInput ) {
  14204. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14205. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14206. uniforms.specular.value.copyGammaToLinear( material.specular );
  14207. } else {
  14208. uniforms.ambient.value = material.ambient;
  14209. uniforms.emissive.value = material.emissive;
  14210. uniforms.specular.value = material.specular;
  14211. }
  14212. if ( material.wrapAround ) {
  14213. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14214. }
  14215. };
  14216. function refreshUniformsLambert ( uniforms, material ) {
  14217. if ( _this.gammaInput ) {
  14218. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14219. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14220. } else {
  14221. uniforms.ambient.value = material.ambient;
  14222. uniforms.emissive.value = material.emissive;
  14223. }
  14224. if ( material.wrapAround ) {
  14225. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14226. }
  14227. };
  14228. function refreshUniformsLights ( uniforms, lights ) {
  14229. uniforms.ambientLightColor.value = lights.ambient;
  14230. uniforms.directionalLightColor.value = lights.directional.colors;
  14231. uniforms.directionalLightDirection.value = lights.directional.positions;
  14232. uniforms.pointLightColor.value = lights.point.colors;
  14233. uniforms.pointLightPosition.value = lights.point.positions;
  14234. uniforms.pointLightDistance.value = lights.point.distances;
  14235. uniforms.spotLightColor.value = lights.spot.colors;
  14236. uniforms.spotLightPosition.value = lights.spot.positions;
  14237. uniforms.spotLightDistance.value = lights.spot.distances;
  14238. uniforms.spotLightDirection.value = lights.spot.directions;
  14239. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14240. uniforms.spotLightExponent.value = lights.spot.exponents;
  14241. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14242. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14243. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14244. };
  14245. function refreshUniformsShadow ( uniforms, lights ) {
  14246. if ( uniforms.shadowMatrix ) {
  14247. var j = 0;
  14248. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14249. var light = lights[ i ];
  14250. if ( ! light.castShadow ) continue;
  14251. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14252. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14253. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14254. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14255. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14256. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14257. j ++;
  14258. }
  14259. }
  14260. }
  14261. };
  14262. // Uniforms (load to GPU)
  14263. function loadUniformsMatrices ( uniforms, object ) {
  14264. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14265. if ( uniforms.normalMatrix ) {
  14266. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14267. }
  14268. };
  14269. function getTextureUnit() {
  14270. var textureUnit = _usedTextureUnits;
  14271. if ( textureUnit >= _maxTextures ) {
  14272. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14273. }
  14274. _usedTextureUnits += 1;
  14275. return textureUnit;
  14276. };
  14277. function loadUniformsGeneric ( program, uniforms ) {
  14278. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14279. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14280. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14281. if ( !location ) continue;
  14282. uniform = uniforms[ j ][ 0 ];
  14283. type = uniform.type;
  14284. value = uniform.value;
  14285. if ( type === "i" ) { // single integer
  14286. _gl.uniform1i( location, value );
  14287. } else if ( type === "f" ) { // single float
  14288. _gl.uniform1f( location, value );
  14289. } else if ( type === "v2" ) { // single THREE.Vector2
  14290. _gl.uniform2f( location, value.x, value.y );
  14291. } else if ( type === "v3" ) { // single THREE.Vector3
  14292. _gl.uniform3f( location, value.x, value.y, value.z );
  14293. } else if ( type === "v4" ) { // single THREE.Vector4
  14294. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14295. } else if ( type === "c" ) { // single THREE.Color
  14296. _gl.uniform3f( location, value.r, value.g, value.b );
  14297. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14298. _gl.uniform1iv( location, value );
  14299. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14300. _gl.uniform3iv( location, value );
  14301. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14302. _gl.uniform1fv( location, value );
  14303. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14304. _gl.uniform3fv( location, value );
  14305. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14306. if ( uniform._array === undefined ) {
  14307. uniform._array = new Float32Array( 2 * value.length );
  14308. }
  14309. for ( i = 0, il = value.length; i < il; i ++ ) {
  14310. offset = i * 2;
  14311. uniform._array[ offset ] = value[ i ].x;
  14312. uniform._array[ offset + 1 ] = value[ i ].y;
  14313. }
  14314. _gl.uniform2fv( location, uniform._array );
  14315. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14316. if ( uniform._array === undefined ) {
  14317. uniform._array = new Float32Array( 3 * value.length );
  14318. }
  14319. for ( i = 0, il = value.length; i < il; i ++ ) {
  14320. offset = i * 3;
  14321. uniform._array[ offset ] = value[ i ].x;
  14322. uniform._array[ offset + 1 ] = value[ i ].y;
  14323. uniform._array[ offset + 2 ] = value[ i ].z;
  14324. }
  14325. _gl.uniform3fv( location, uniform._array );
  14326. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14327. if ( uniform._array === undefined ) {
  14328. uniform._array = new Float32Array( 4 * value.length );
  14329. }
  14330. for ( i = 0, il = value.length; i < il; i ++ ) {
  14331. offset = i * 4;
  14332. uniform._array[ offset ] = value[ i ].x;
  14333. uniform._array[ offset + 1 ] = value[ i ].y;
  14334. uniform._array[ offset + 2 ] = value[ i ].z;
  14335. uniform._array[ offset + 3 ] = value[ i ].w;
  14336. }
  14337. _gl.uniform4fv( location, uniform._array );
  14338. } else if ( type === "m4") { // single THREE.Matrix4
  14339. if ( uniform._array === undefined ) {
  14340. uniform._array = new Float32Array( 16 );
  14341. }
  14342. value.flattenToArray( uniform._array );
  14343. _gl.uniformMatrix4fv( location, false, uniform._array );
  14344. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14345. if ( uniform._array === undefined ) {
  14346. uniform._array = new Float32Array( 16 * value.length );
  14347. }
  14348. for ( i = 0, il = value.length; i < il; i ++ ) {
  14349. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14350. }
  14351. _gl.uniformMatrix4fv( location, false, uniform._array );
  14352. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14353. texture = value;
  14354. textureUnit = getTextureUnit();
  14355. _gl.uniform1i( location, textureUnit );
  14356. if ( !texture ) continue;
  14357. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14358. setCubeTexture( texture, textureUnit );
  14359. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14360. setCubeTextureDynamic( texture, textureUnit );
  14361. } else {
  14362. _this.setTexture( texture, textureUnit );
  14363. }
  14364. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14365. if ( uniform._array === undefined ) {
  14366. uniform._array = [];
  14367. }
  14368. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14369. uniform._array[ i ] = getTextureUnit();
  14370. }
  14371. _gl.uniform1iv( location, uniform._array );
  14372. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14373. texture = uniform.value[ i ];
  14374. textureUnit = uniform._array[ i ];
  14375. if ( !texture ) continue;
  14376. _this.setTexture( texture, textureUnit );
  14377. }
  14378. } else {
  14379. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  14380. }
  14381. }
  14382. };
  14383. function setupMatrices ( object, camera ) {
  14384. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14385. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14386. };
  14387. //
  14388. function setColorGamma( array, offset, color, intensitySq ) {
  14389. array[ offset ] = color.r * color.r * intensitySq;
  14390. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14391. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14392. };
  14393. function setColorLinear( array, offset, color, intensity ) {
  14394. array[ offset ] = color.r * intensity;
  14395. array[ offset + 1 ] = color.g * intensity;
  14396. array[ offset + 2 ] = color.b * intensity;
  14397. };
  14398. function setupLights ( program, lights ) {
  14399. var l, ll, light, n,
  14400. r = 0, g = 0, b = 0,
  14401. color, skyColor, groundColor,
  14402. intensity, intensitySq,
  14403. position,
  14404. distance,
  14405. zlights = _lights,
  14406. dirColors = zlights.directional.colors,
  14407. dirPositions = zlights.directional.positions,
  14408. pointColors = zlights.point.colors,
  14409. pointPositions = zlights.point.positions,
  14410. pointDistances = zlights.point.distances,
  14411. spotColors = zlights.spot.colors,
  14412. spotPositions = zlights.spot.positions,
  14413. spotDistances = zlights.spot.distances,
  14414. spotDirections = zlights.spot.directions,
  14415. spotAnglesCos = zlights.spot.anglesCos,
  14416. spotExponents = zlights.spot.exponents,
  14417. hemiSkyColors = zlights.hemi.skyColors,
  14418. hemiGroundColors = zlights.hemi.groundColors,
  14419. hemiPositions = zlights.hemi.positions,
  14420. dirLength = 0,
  14421. pointLength = 0,
  14422. spotLength = 0,
  14423. hemiLength = 0,
  14424. dirCount = 0,
  14425. pointCount = 0,
  14426. spotCount = 0,
  14427. hemiCount = 0,
  14428. dirOffset = 0,
  14429. pointOffset = 0,
  14430. spotOffset = 0,
  14431. hemiOffset = 0;
  14432. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14433. light = lights[ l ];
  14434. if ( light.onlyShadow ) continue;
  14435. color = light.color;
  14436. intensity = light.intensity;
  14437. distance = light.distance;
  14438. if ( light instanceof THREE.AmbientLight ) {
  14439. if ( ! light.visible ) continue;
  14440. if ( _this.gammaInput ) {
  14441. r += color.r * color.r;
  14442. g += color.g * color.g;
  14443. b += color.b * color.b;
  14444. } else {
  14445. r += color.r;
  14446. g += color.g;
  14447. b += color.b;
  14448. }
  14449. } else if ( light instanceof THREE.DirectionalLight ) {
  14450. dirCount += 1;
  14451. if ( ! light.visible ) continue;
  14452. _direction.getPositionFromMatrix( light.matrixWorld );
  14453. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14454. _direction.sub( _vector3 );
  14455. _direction.normalize();
  14456. // skip lights with undefined direction
  14457. // these create troubles in OpenGL (making pixel black)
  14458. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14459. dirOffset = dirLength * 3;
  14460. dirPositions[ dirOffset ] = _direction.x;
  14461. dirPositions[ dirOffset + 1 ] = _direction.y;
  14462. dirPositions[ dirOffset + 2 ] = _direction.z;
  14463. if ( _this.gammaInput ) {
  14464. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14465. } else {
  14466. setColorLinear( dirColors, dirOffset, color, intensity );
  14467. }
  14468. dirLength += 1;
  14469. } else if ( light instanceof THREE.PointLight ) {
  14470. pointCount += 1;
  14471. if ( ! light.visible ) continue;
  14472. pointOffset = pointLength * 3;
  14473. if ( _this.gammaInput ) {
  14474. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14475. } else {
  14476. setColorLinear( pointColors, pointOffset, color, intensity );
  14477. }
  14478. _vector3.getPositionFromMatrix( light.matrixWorld );
  14479. pointPositions[ pointOffset ] = _vector3.x;
  14480. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14481. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14482. pointDistances[ pointLength ] = distance;
  14483. pointLength += 1;
  14484. } else if ( light instanceof THREE.SpotLight ) {
  14485. spotCount += 1;
  14486. if ( ! light.visible ) continue;
  14487. spotOffset = spotLength * 3;
  14488. if ( _this.gammaInput ) {
  14489. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14490. } else {
  14491. setColorLinear( spotColors, spotOffset, color, intensity );
  14492. }
  14493. _vector3.getPositionFromMatrix( light.matrixWorld );
  14494. spotPositions[ spotOffset ] = _vector3.x;
  14495. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14496. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14497. spotDistances[ spotLength ] = distance;
  14498. _direction.copy( _vector3 );
  14499. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14500. _direction.sub( _vector3 );
  14501. _direction.normalize();
  14502. spotDirections[ spotOffset ] = _direction.x;
  14503. spotDirections[ spotOffset + 1 ] = _direction.y;
  14504. spotDirections[ spotOffset + 2 ] = _direction.z;
  14505. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14506. spotExponents[ spotLength ] = light.exponent;
  14507. spotLength += 1;
  14508. } else if ( light instanceof THREE.HemisphereLight ) {
  14509. hemiCount += 1;
  14510. if ( ! light.visible ) continue;
  14511. _direction.getPositionFromMatrix( light.matrixWorld );
  14512. _direction.normalize();
  14513. // skip lights with undefined direction
  14514. // these create troubles in OpenGL (making pixel black)
  14515. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14516. hemiOffset = hemiLength * 3;
  14517. hemiPositions[ hemiOffset ] = _direction.x;
  14518. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14519. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14520. skyColor = light.color;
  14521. groundColor = light.groundColor;
  14522. if ( _this.gammaInput ) {
  14523. intensitySq = intensity * intensity;
  14524. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14525. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14526. } else {
  14527. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14528. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14529. }
  14530. hemiLength += 1;
  14531. }
  14532. }
  14533. // null eventual remains from removed lights
  14534. // (this is to avoid if in shader)
  14535. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14536. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14537. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14538. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14539. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14540. zlights.directional.length = dirLength;
  14541. zlights.point.length = pointLength;
  14542. zlights.spot.length = spotLength;
  14543. zlights.hemi.length = hemiLength;
  14544. zlights.ambient[ 0 ] = r;
  14545. zlights.ambient[ 1 ] = g;
  14546. zlights.ambient[ 2 ] = b;
  14547. };
  14548. // GL state setting
  14549. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14550. if ( cullFace === THREE.CullFaceNone ) {
  14551. _gl.disable( _gl.CULL_FACE );
  14552. } else {
  14553. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14554. _gl.frontFace( _gl.CW );
  14555. } else {
  14556. _gl.frontFace( _gl.CCW );
  14557. }
  14558. if ( cullFace === THREE.CullFaceBack ) {
  14559. _gl.cullFace( _gl.BACK );
  14560. } else if ( cullFace === THREE.CullFaceFront ) {
  14561. _gl.cullFace( _gl.FRONT );
  14562. } else {
  14563. _gl.cullFace( _gl.FRONT_AND_BACK );
  14564. }
  14565. _gl.enable( _gl.CULL_FACE );
  14566. }
  14567. };
  14568. this.setMaterialFaces = function ( material ) {
  14569. var doubleSided = material.side === THREE.DoubleSide;
  14570. var flipSided = material.side === THREE.BackSide;
  14571. if ( _oldDoubleSided !== doubleSided ) {
  14572. if ( doubleSided ) {
  14573. _gl.disable( _gl.CULL_FACE );
  14574. } else {
  14575. _gl.enable( _gl.CULL_FACE );
  14576. }
  14577. _oldDoubleSided = doubleSided;
  14578. }
  14579. if ( _oldFlipSided !== flipSided ) {
  14580. if ( flipSided ) {
  14581. _gl.frontFace( _gl.CW );
  14582. } else {
  14583. _gl.frontFace( _gl.CCW );
  14584. }
  14585. _oldFlipSided = flipSided;
  14586. }
  14587. };
  14588. this.setDepthTest = function ( depthTest ) {
  14589. if ( _oldDepthTest !== depthTest ) {
  14590. if ( depthTest ) {
  14591. _gl.enable( _gl.DEPTH_TEST );
  14592. } else {
  14593. _gl.disable( _gl.DEPTH_TEST );
  14594. }
  14595. _oldDepthTest = depthTest;
  14596. }
  14597. };
  14598. this.setDepthWrite = function ( depthWrite ) {
  14599. if ( _oldDepthWrite !== depthWrite ) {
  14600. _gl.depthMask( depthWrite );
  14601. _oldDepthWrite = depthWrite;
  14602. }
  14603. };
  14604. function setLineWidth ( width ) {
  14605. if ( width !== _oldLineWidth ) {
  14606. _gl.lineWidth( width );
  14607. _oldLineWidth = width;
  14608. }
  14609. };
  14610. function setPolygonOffset ( polygonoffset, factor, units ) {
  14611. if ( _oldPolygonOffset !== polygonoffset ) {
  14612. if ( polygonoffset ) {
  14613. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  14614. } else {
  14615. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  14616. }
  14617. _oldPolygonOffset = polygonoffset;
  14618. }
  14619. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  14620. _gl.polygonOffset( factor, units );
  14621. _oldPolygonOffsetFactor = factor;
  14622. _oldPolygonOffsetUnits = units;
  14623. }
  14624. };
  14625. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  14626. if ( blending !== _oldBlending ) {
  14627. if ( blending === THREE.NoBlending ) {
  14628. _gl.disable( _gl.BLEND );
  14629. } else if ( blending === THREE.AdditiveBlending ) {
  14630. _gl.enable( _gl.BLEND );
  14631. _gl.blendEquation( _gl.FUNC_ADD );
  14632. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  14633. } else if ( blending === THREE.SubtractiveBlending ) {
  14634. // TODO: Find blendFuncSeparate() combination
  14635. _gl.enable( _gl.BLEND );
  14636. _gl.blendEquation( _gl.FUNC_ADD );
  14637. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  14638. } else if ( blending === THREE.MultiplyBlending ) {
  14639. // TODO: Find blendFuncSeparate() combination
  14640. _gl.enable( _gl.BLEND );
  14641. _gl.blendEquation( _gl.FUNC_ADD );
  14642. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  14643. } else if ( blending === THREE.CustomBlending ) {
  14644. _gl.enable( _gl.BLEND );
  14645. } else {
  14646. _gl.enable( _gl.BLEND );
  14647. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  14648. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  14649. }
  14650. _oldBlending = blending;
  14651. }
  14652. if ( blending === THREE.CustomBlending ) {
  14653. if ( blendEquation !== _oldBlendEquation ) {
  14654. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  14655. _oldBlendEquation = blendEquation;
  14656. }
  14657. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  14658. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  14659. _oldBlendSrc = blendSrc;
  14660. _oldBlendDst = blendDst;
  14661. }
  14662. } else {
  14663. _oldBlendEquation = null;
  14664. _oldBlendSrc = null;
  14665. _oldBlendDst = null;
  14666. }
  14667. };
  14668. // Defines
  14669. function generateDefines ( defines ) {
  14670. var value, chunk, chunks = [];
  14671. for ( var d in defines ) {
  14672. value = defines[ d ];
  14673. if ( value === false ) continue;
  14674. chunk = "#define " + d + " " + value;
  14675. chunks.push( chunk );
  14676. }
  14677. return chunks.join( "\n" );
  14678. };
  14679. // Shaders
  14680. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters, index0AttributeName ) {
  14681. var p, pl, d, program, code;
  14682. var chunks = [];
  14683. // Generate code
  14684. if ( shaderID ) {
  14685. chunks.push( shaderID );
  14686. } else {
  14687. chunks.push( fragmentShader );
  14688. chunks.push( vertexShader );
  14689. }
  14690. for ( d in defines ) {
  14691. chunks.push( d );
  14692. chunks.push( defines[ d ] );
  14693. }
  14694. for ( p in parameters ) {
  14695. chunks.push( p );
  14696. chunks.push( parameters[ p ] );
  14697. }
  14698. code = chunks.join();
  14699. // Check if code has been already compiled
  14700. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  14701. var programInfo = _programs[ p ];
  14702. if ( programInfo.code === code ) {
  14703. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  14704. programInfo.usedTimes ++;
  14705. return programInfo.program;
  14706. }
  14707. }
  14708. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  14709. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  14710. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  14711. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  14712. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  14713. }
  14714. // console.log( "building new program " );
  14715. //
  14716. var customDefines = generateDefines( defines );
  14717. //
  14718. program = _gl.createProgram();
  14719. var prefix_vertex = [
  14720. "precision " + _precision + " float;",
  14721. "precision " + _precision + " int;",
  14722. customDefines,
  14723. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  14724. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14725. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14726. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14727. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14728. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14729. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14730. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14731. "#define MAX_SHADOWS " + parameters.maxShadows,
  14732. "#define MAX_BONES " + parameters.maxBones,
  14733. parameters.map ? "#define USE_MAP" : "",
  14734. parameters.envMap ? "#define USE_ENVMAP" : "",
  14735. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14736. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14737. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14738. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14739. parameters.vertexColors ? "#define USE_COLOR" : "",
  14740. parameters.skinning ? "#define USE_SKINNING" : "",
  14741. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  14742. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  14743. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  14744. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14745. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14746. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14747. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14748. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14749. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14750. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14751. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14752. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  14753. "uniform mat4 modelMatrix;",
  14754. "uniform mat4 modelViewMatrix;",
  14755. "uniform mat4 projectionMatrix;",
  14756. "uniform mat4 viewMatrix;",
  14757. "uniform mat3 normalMatrix;",
  14758. "uniform vec3 cameraPosition;",
  14759. "attribute vec3 position;",
  14760. "attribute vec3 normal;",
  14761. "attribute vec2 uv;",
  14762. "attribute vec2 uv2;",
  14763. "#ifdef USE_COLOR",
  14764. "attribute vec3 color;",
  14765. "#endif",
  14766. "#ifdef USE_MORPHTARGETS",
  14767. "attribute vec3 morphTarget0;",
  14768. "attribute vec3 morphTarget1;",
  14769. "attribute vec3 morphTarget2;",
  14770. "attribute vec3 morphTarget3;",
  14771. "#ifdef USE_MORPHNORMALS",
  14772. "attribute vec3 morphNormal0;",
  14773. "attribute vec3 morphNormal1;",
  14774. "attribute vec3 morphNormal2;",
  14775. "attribute vec3 morphNormal3;",
  14776. "#else",
  14777. "attribute vec3 morphTarget4;",
  14778. "attribute vec3 morphTarget5;",
  14779. "attribute vec3 morphTarget6;",
  14780. "attribute vec3 morphTarget7;",
  14781. "#endif",
  14782. "#endif",
  14783. "#ifdef USE_SKINNING",
  14784. "attribute vec4 skinIndex;",
  14785. "attribute vec4 skinWeight;",
  14786. "#endif",
  14787. ""
  14788. ].join("\n");
  14789. var prefix_fragment = [
  14790. "precision " + _precision + " float;",
  14791. "precision " + _precision + " int;",
  14792. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  14793. customDefines,
  14794. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14795. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14796. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14797. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14798. "#define MAX_SHADOWS " + parameters.maxShadows,
  14799. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  14800. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14801. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14802. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14803. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  14804. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  14805. parameters.map ? "#define USE_MAP" : "",
  14806. parameters.envMap ? "#define USE_ENVMAP" : "",
  14807. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14808. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14809. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14810. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14811. parameters.vertexColors ? "#define USE_COLOR" : "",
  14812. parameters.metal ? "#define METAL" : "",
  14813. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14814. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14815. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14816. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14817. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14818. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14819. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14820. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14821. "uniform mat4 viewMatrix;",
  14822. "uniform vec3 cameraPosition;",
  14823. ""
  14824. ].join("\n");
  14825. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  14826. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  14827. _gl.attachShader( program, glVertexShader );
  14828. _gl.attachShader( program, glFragmentShader );
  14829. //Force a particular attribute to index 0.
  14830. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  14831. //And, color, for example is often automatically bound to index 0 so disabling it
  14832. if ( index0AttributeName ) {
  14833. _gl.bindAttribLocation( program, 0, index0AttributeName );
  14834. }
  14835. _gl.linkProgram( program );
  14836. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  14837. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  14838. console.error( "Program Info Log: " + _gl.getProgramInfoLog( program ) );
  14839. }
  14840. // clean up
  14841. _gl.deleteShader( glFragmentShader );
  14842. _gl.deleteShader( glVertexShader );
  14843. // console.log( prefix_fragment + fragmentShader );
  14844. // console.log( prefix_vertex + vertexShader );
  14845. program.uniforms = {};
  14846. program.attributes = {};
  14847. var identifiers, u, a, i;
  14848. // cache uniform locations
  14849. identifiers = [
  14850. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  14851. 'morphTargetInfluences'
  14852. ];
  14853. if ( parameters.useVertexTexture ) {
  14854. identifiers.push( 'boneTexture' );
  14855. identifiers.push( 'boneTextureWidth' );
  14856. identifiers.push( 'boneTextureHeight' );
  14857. } else {
  14858. identifiers.push( 'boneGlobalMatrices' );
  14859. }
  14860. for ( u in uniforms ) {
  14861. identifiers.push( u );
  14862. }
  14863. cacheUniformLocations( program, identifiers );
  14864. // cache attributes locations
  14865. identifiers = [
  14866. "position", "normal", "uv", "uv2", "tangent", "color",
  14867. "skinIndex", "skinWeight", "lineDistance"
  14868. ];
  14869. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  14870. identifiers.push( "morphTarget" + i );
  14871. }
  14872. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  14873. identifiers.push( "morphNormal" + i );
  14874. }
  14875. for ( a in attributes ) {
  14876. identifiers.push( a );
  14877. }
  14878. cacheAttributeLocations( program, identifiers );
  14879. program.id = _programs_counter ++;
  14880. _programs.push( { program: program, code: code, usedTimes: 1 } );
  14881. _this.info.memory.programs = _programs.length;
  14882. return program;
  14883. };
  14884. // Shader parameters cache
  14885. function cacheUniformLocations ( program, identifiers ) {
  14886. var i, l, id;
  14887. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14888. id = identifiers[ i ];
  14889. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  14890. }
  14891. };
  14892. function cacheAttributeLocations ( program, identifiers ) {
  14893. var i, l, id;
  14894. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14895. id = identifiers[ i ];
  14896. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  14897. }
  14898. };
  14899. function addLineNumbers ( string ) {
  14900. var chunks = string.split( "\n" );
  14901. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  14902. // Chrome reports shader errors on lines
  14903. // starting counting from 1
  14904. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  14905. }
  14906. return chunks.join( "\n" );
  14907. };
  14908. function getShader ( type, string ) {
  14909. var shader;
  14910. if ( type === "fragment" ) {
  14911. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  14912. } else if ( type === "vertex" ) {
  14913. shader = _gl.createShader( _gl.VERTEX_SHADER );
  14914. }
  14915. _gl.shaderSource( shader, string );
  14916. _gl.compileShader( shader );
  14917. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  14918. console.error( _gl.getShaderInfoLog( shader ) );
  14919. console.error( addLineNumbers( string ) );
  14920. return null;
  14921. }
  14922. return shader;
  14923. };
  14924. // Textures
  14925. function isPowerOfTwo ( value ) {
  14926. return ( value & ( value - 1 ) ) === 0;
  14927. };
  14928. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14929. if ( isImagePowerOfTwo ) {
  14930. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14931. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14932. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14933. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14934. } else {
  14935. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14936. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14937. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14938. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14939. }
  14940. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  14941. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  14942. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  14943. texture.__oldAnisotropy = texture.anisotropy;
  14944. }
  14945. }
  14946. };
  14947. this.setTexture = function ( texture, slot ) {
  14948. if ( texture.needsUpdate ) {
  14949. if ( ! texture.__webglInit ) {
  14950. texture.__webglInit = true;
  14951. texture.addEventListener( 'dispose', onTextureDispose );
  14952. texture.__webglTexture = _gl.createTexture();
  14953. _this.info.memory.textures ++;
  14954. }
  14955. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14956. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14957. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14958. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14959. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14960. var image = texture.image,
  14961. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14962. glFormat = paramThreeToGL( texture.format ),
  14963. glType = paramThreeToGL( texture.type );
  14964. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  14965. var mipmap, mipmaps = texture.mipmaps;
  14966. if ( texture instanceof THREE.DataTexture ) {
  14967. // use manually created mipmaps if available
  14968. // if there are no manual mipmaps
  14969. // set 0 level mipmap and then use GL to generate other mipmap levels
  14970. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14971. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14972. mipmap = mipmaps[ i ];
  14973. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14974. }
  14975. texture.generateMipmaps = false;
  14976. } else {
  14977. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14978. }
  14979. } else if ( texture instanceof THREE.CompressedTexture ) {
  14980. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14981. mipmap = mipmaps[ i ];
  14982. if ( texture.format!==THREE.RGBAFormat ) {
  14983. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14984. } else {
  14985. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14986. }
  14987. }
  14988. } else { // regular Texture (image, video, canvas)
  14989. // use manually created mipmaps if available
  14990. // if there are no manual mipmaps
  14991. // set 0 level mipmap and then use GL to generate other mipmap levels
  14992. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14993. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14994. mipmap = mipmaps[ i ];
  14995. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  14996. }
  14997. texture.generateMipmaps = false;
  14998. } else {
  14999. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  15000. }
  15001. }
  15002. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15003. texture.needsUpdate = false;
  15004. if ( texture.onUpdate ) texture.onUpdate();
  15005. } else {
  15006. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15007. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15008. }
  15009. };
  15010. function clampToMaxSize ( image, maxSize ) {
  15011. if ( image.width <= maxSize && image.height <= maxSize ) {
  15012. return image;
  15013. }
  15014. // Warning: Scaling through the canvas will only work with images that use
  15015. // premultiplied alpha.
  15016. var maxDimension = Math.max( image.width, image.height );
  15017. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15018. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15019. var canvas = document.createElement( 'canvas' );
  15020. canvas.width = newWidth;
  15021. canvas.height = newHeight;
  15022. var ctx = canvas.getContext( "2d" );
  15023. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15024. return canvas;
  15025. }
  15026. function setCubeTexture ( texture, slot ) {
  15027. if ( texture.image.length === 6 ) {
  15028. if ( texture.needsUpdate ) {
  15029. if ( ! texture.image.__webglTextureCube ) {
  15030. texture.addEventListener( 'dispose', onTextureDispose );
  15031. texture.image.__webglTextureCube = _gl.createTexture();
  15032. _this.info.memory.textures ++;
  15033. }
  15034. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15035. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15036. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15037. var isCompressed = texture instanceof THREE.CompressedTexture;
  15038. var cubeImage = [];
  15039. for ( var i = 0; i < 6; i ++ ) {
  15040. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15041. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15042. } else {
  15043. cubeImage[ i ] = texture.image[ i ];
  15044. }
  15045. }
  15046. var image = cubeImage[ 0 ],
  15047. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  15048. glFormat = paramThreeToGL( texture.format ),
  15049. glType = paramThreeToGL( texture.type );
  15050. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15051. for ( var i = 0; i < 6; i ++ ) {
  15052. if( !isCompressed ) {
  15053. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15054. } else {
  15055. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15056. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15057. mipmap = mipmaps[ j ];
  15058. if ( texture.format!==THREE.RGBAFormat ) {
  15059. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15060. } else {
  15061. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15062. }
  15063. }
  15064. }
  15065. }
  15066. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15067. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15068. }
  15069. texture.needsUpdate = false;
  15070. if ( texture.onUpdate ) texture.onUpdate();
  15071. } else {
  15072. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15073. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15074. }
  15075. }
  15076. };
  15077. function setCubeTextureDynamic ( texture, slot ) {
  15078. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15079. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15080. };
  15081. // Render targets
  15082. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15083. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15084. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15085. };
  15086. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15087. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15088. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15089. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15090. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15091. /* For some reason this is not working. Defaulting to RGBA4.
  15092. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15093. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15094. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15095. */
  15096. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15097. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15098. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15099. } else {
  15100. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15101. }
  15102. };
  15103. this.setRenderTarget = function ( renderTarget ) {
  15104. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15105. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15106. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15107. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15108. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15109. renderTarget.__webglTexture = _gl.createTexture();
  15110. _this.info.memory.textures ++;
  15111. // Setup texture, create render and frame buffers
  15112. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  15113. glFormat = paramThreeToGL( renderTarget.format ),
  15114. glType = paramThreeToGL( renderTarget.type );
  15115. if ( isCube ) {
  15116. renderTarget.__webglFramebuffer = [];
  15117. renderTarget.__webglRenderbuffer = [];
  15118. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15119. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15120. for ( var i = 0; i < 6; i ++ ) {
  15121. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15122. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15123. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15124. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15125. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15126. }
  15127. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15128. } else {
  15129. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15130. if ( renderTarget.shareDepthFrom ) {
  15131. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15132. } else {
  15133. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15134. }
  15135. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15136. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15137. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15138. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15139. if ( renderTarget.shareDepthFrom ) {
  15140. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15141. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15142. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15143. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15144. }
  15145. } else {
  15146. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15147. }
  15148. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15149. }
  15150. // Release everything
  15151. if ( isCube ) {
  15152. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15153. } else {
  15154. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15155. }
  15156. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15157. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15158. }
  15159. var framebuffer, width, height, vx, vy;
  15160. if ( renderTarget ) {
  15161. if ( isCube ) {
  15162. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15163. } else {
  15164. framebuffer = renderTarget.__webglFramebuffer;
  15165. }
  15166. width = renderTarget.width;
  15167. height = renderTarget.height;
  15168. vx = 0;
  15169. vy = 0;
  15170. } else {
  15171. framebuffer = null;
  15172. width = _viewportWidth;
  15173. height = _viewportHeight;
  15174. vx = _viewportX;
  15175. vy = _viewportY;
  15176. }
  15177. if ( framebuffer !== _currentFramebuffer ) {
  15178. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15179. _gl.viewport( vx, vy, width, height );
  15180. _currentFramebuffer = framebuffer;
  15181. }
  15182. _currentWidth = width;
  15183. _currentHeight = height;
  15184. };
  15185. function updateRenderTargetMipmap ( renderTarget ) {
  15186. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15187. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15188. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15189. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15190. } else {
  15191. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15192. _gl.generateMipmap( _gl.TEXTURE_2D );
  15193. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15194. }
  15195. };
  15196. // Fallback filters for non-power-of-2 textures
  15197. function filterFallback ( f ) {
  15198. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15199. return _gl.NEAREST;
  15200. }
  15201. return _gl.LINEAR;
  15202. };
  15203. // Map three.js constants to WebGL constants
  15204. function paramThreeToGL ( p ) {
  15205. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15206. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15207. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15208. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15209. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15210. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15211. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15212. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15213. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15214. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15215. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15216. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15217. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15218. if ( p === THREE.ByteType ) return _gl.BYTE;
  15219. if ( p === THREE.ShortType ) return _gl.SHORT;
  15220. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15221. if ( p === THREE.IntType ) return _gl.INT;
  15222. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15223. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15224. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15225. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15226. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15227. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15228. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15229. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15230. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15231. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15232. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15233. if ( p === THREE.OneFactor ) return _gl.ONE;
  15234. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15235. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15236. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15237. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15238. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15239. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15240. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15241. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15242. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15243. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15244. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15245. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15246. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15247. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15248. }
  15249. return 0;
  15250. };
  15251. // Allocations
  15252. function allocateBones ( object ) {
  15253. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15254. return 1024;
  15255. } else {
  15256. // default for when object is not specified
  15257. // ( for example when prebuilding shader
  15258. // to be used with multiple objects )
  15259. //
  15260. // - leave some extra space for other uniforms
  15261. // - limit here is ANGLE's 254 max uniform vectors
  15262. // (up to 54 should be safe)
  15263. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15264. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15265. var maxBones = nVertexMatrices;
  15266. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15267. maxBones = Math.min( object.bones.length, maxBones );
  15268. if ( maxBones < object.bones.length ) {
  15269. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15270. }
  15271. }
  15272. return maxBones;
  15273. }
  15274. };
  15275. function allocateLights( lights ) {
  15276. var dirLights = 0;
  15277. var pointLights = 0;
  15278. var spotLights = 0;
  15279. var hemiLights = 0;
  15280. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15281. var light = lights[ l ];
  15282. if ( light.onlyShadow ) continue;
  15283. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15284. if ( light instanceof THREE.PointLight ) pointLights ++;
  15285. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15286. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15287. }
  15288. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15289. };
  15290. function allocateShadows( lights ) {
  15291. var maxShadows = 0;
  15292. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  15293. var light = lights[ l ];
  15294. if ( ! light.castShadow ) continue;
  15295. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15296. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15297. }
  15298. return maxShadows;
  15299. };
  15300. // Initialization
  15301. function initGL() {
  15302. try {
  15303. var attributes = {
  15304. alpha: _alpha,
  15305. premultipliedAlpha: _premultipliedAlpha,
  15306. antialias: _antialias,
  15307. stencil: _stencil,
  15308. preserveDrawingBuffer: _preserveDrawingBuffer
  15309. };
  15310. _gl = _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  15311. if ( _gl === null ) {
  15312. throw 'Error creating WebGL context.';
  15313. }
  15314. } catch ( error ) {
  15315. console.error( error );
  15316. }
  15317. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15318. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15319. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15320. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15321. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15322. if ( ! _glExtensionTextureFloat ) {
  15323. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15324. }
  15325. if ( ! _glExtensionStandardDerivatives ) {
  15326. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15327. }
  15328. if ( ! _glExtensionTextureFilterAnisotropic ) {
  15329. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15330. }
  15331. if ( ! _glExtensionCompressedTextureS3TC ) {
  15332. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15333. }
  15334. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15335. _gl.getShaderPrecisionFormat = function() {
  15336. return {
  15337. "rangeMin" : 1,
  15338. "rangeMax" : 1,
  15339. "precision" : 1
  15340. };
  15341. }
  15342. }
  15343. };
  15344. function setDefaultGLState () {
  15345. _gl.clearColor( 0, 0, 0, 1 );
  15346. _gl.clearDepth( 1 );
  15347. _gl.clearStencil( 0 );
  15348. _gl.enable( _gl.DEPTH_TEST );
  15349. _gl.depthFunc( _gl.LEQUAL );
  15350. _gl.frontFace( _gl.CCW );
  15351. _gl.cullFace( _gl.BACK );
  15352. _gl.enable( _gl.CULL_FACE );
  15353. _gl.enable( _gl.BLEND );
  15354. _gl.blendEquation( _gl.FUNC_ADD );
  15355. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15356. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  15357. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15358. };
  15359. // default plugins (order is important)
  15360. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15361. this.addPrePlugin( this.shadowMapPlugin );
  15362. this.addPostPlugin( new THREE.SpritePlugin() );
  15363. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15364. };
  15365. /**
  15366. * @author szimek / https://github.com/szimek/
  15367. * @author alteredq / http://alteredqualia.com/
  15368. */
  15369. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15370. this.width = width;
  15371. this.height = height;
  15372. options = options || {};
  15373. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15374. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15375. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15376. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15377. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15378. this.offset = new THREE.Vector2( 0, 0 );
  15379. this.repeat = new THREE.Vector2( 1, 1 );
  15380. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15381. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15382. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15383. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15384. this.generateMipmaps = true;
  15385. this.shareDepthFrom = null;
  15386. };
  15387. THREE.WebGLRenderTarget.prototype = {
  15388. constructor: THREE.WebGLRenderTarget,
  15389. clone: function () {
  15390. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15391. tmp.wrapS = this.wrapS;
  15392. tmp.wrapT = this.wrapT;
  15393. tmp.magFilter = this.magFilter;
  15394. tmp.minFilter = this.minFilter;
  15395. tmp.anisotropy = this.anisotropy;
  15396. tmp.offset.copy( this.offset );
  15397. tmp.repeat.copy( this.repeat );
  15398. tmp.format = this.format;
  15399. tmp.type = this.type;
  15400. tmp.depthBuffer = this.depthBuffer;
  15401. tmp.stencilBuffer = this.stencilBuffer;
  15402. tmp.generateMipmaps = this.generateMipmaps;
  15403. tmp.shareDepthFrom = this.shareDepthFrom;
  15404. return tmp;
  15405. },
  15406. dispose: function () {
  15407. this.dispatchEvent( { type: 'dispose' } );
  15408. }
  15409. };
  15410. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  15411. /**
  15412. * @author alteredq / http://alteredqualia.com
  15413. */
  15414. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15415. THREE.WebGLRenderTarget.call( this, width, height, options );
  15416. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15417. };
  15418. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15419. /**
  15420. * @author mrdoob / http://mrdoob.com/
  15421. */
  15422. THREE.RenderableVertex = function () {
  15423. this.positionWorld = new THREE.Vector3();
  15424. this.positionScreen = new THREE.Vector4();
  15425. this.visible = true;
  15426. };
  15427. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15428. this.positionWorld.copy( vertex.positionWorld );
  15429. this.positionScreen.copy( vertex.positionScreen );
  15430. };
  15431. /**
  15432. * @author mrdoob / http://mrdoob.com/
  15433. */
  15434. THREE.RenderableFace3 = function () {
  15435. this.id = 0;
  15436. this.v1 = new THREE.RenderableVertex();
  15437. this.v2 = new THREE.RenderableVertex();
  15438. this.v3 = new THREE.RenderableVertex();
  15439. this.centroidModel = new THREE.Vector3();
  15440. this.normalModel = new THREE.Vector3();
  15441. this.normalModelView = new THREE.Vector3();
  15442. this.vertexNormalsLength = 0;
  15443. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15444. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15445. this.color = null;
  15446. this.material = null;
  15447. this.uvs = [[]];
  15448. this.z = 0;
  15449. };
  15450. /**
  15451. * @author mrdoob / http://mrdoob.com/
  15452. */
  15453. THREE.RenderableObject = function () {
  15454. this.id = 0;
  15455. this.object = null;
  15456. this.z = 0;
  15457. };
  15458. /**
  15459. * @author mrdoob / http://mrdoob.com/
  15460. */
  15461. THREE.RenderableSprite = function () {
  15462. this.id = 0;
  15463. this.object = null;
  15464. this.x = 0;
  15465. this.y = 0;
  15466. this.z = 0;
  15467. this.rotation = 0;
  15468. this.scale = new THREE.Vector2();
  15469. this.material = null;
  15470. };
  15471. /**
  15472. * @author mrdoob / http://mrdoob.com/
  15473. */
  15474. THREE.RenderableLine = function () {
  15475. this.id = 0;
  15476. this.v1 = new THREE.RenderableVertex();
  15477. this.v2 = new THREE.RenderableVertex();
  15478. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  15479. this.material = null;
  15480. this.z = 0;
  15481. };
  15482. /**
  15483. * @author mrdoob / http://mrdoob.com/
  15484. * @author alteredq / http://alteredqualia.com/
  15485. */
  15486. THREE.GeometryUtils = {
  15487. // Merge two geometries or geometry and geometry from object (using object's transform)
  15488. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  15489. var matrix, normalMatrix,
  15490. vertexOffset = geometry1.vertices.length,
  15491. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15492. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15493. vertices1 = geometry1.vertices,
  15494. vertices2 = geometry2.vertices,
  15495. faces1 = geometry1.faces,
  15496. faces2 = geometry2.faces,
  15497. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15498. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15499. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  15500. if ( object2 instanceof THREE.Mesh ) {
  15501. object2.matrixAutoUpdate && object2.updateMatrix();
  15502. matrix = object2.matrix;
  15503. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  15504. }
  15505. // vertices
  15506. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15507. var vertex = vertices2[ i ];
  15508. var vertexCopy = vertex.clone();
  15509. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15510. vertices1.push( vertexCopy );
  15511. }
  15512. // faces
  15513. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15514. var face = faces2[ i ], faceCopy, normal, color,
  15515. faceVertexNormals = face.vertexNormals,
  15516. faceVertexColors = face.vertexColors;
  15517. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15518. faceCopy.normal.copy( face.normal );
  15519. if ( normalMatrix ) {
  15520. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15521. }
  15522. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15523. normal = faceVertexNormals[ j ].clone();
  15524. if ( normalMatrix ) {
  15525. normal.applyMatrix3( normalMatrix ).normalize();
  15526. }
  15527. faceCopy.vertexNormals.push( normal );
  15528. }
  15529. faceCopy.color.copy( face.color );
  15530. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15531. color = faceVertexColors[ j ];
  15532. faceCopy.vertexColors.push( color.clone() );
  15533. }
  15534. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  15535. faceCopy.centroid.copy( face.centroid );
  15536. if ( matrix ) {
  15537. faceCopy.centroid.applyMatrix4( matrix );
  15538. }
  15539. faces1.push( faceCopy );
  15540. }
  15541. // uvs
  15542. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15543. var uv = uvs2[ i ], uvCopy = [];
  15544. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15545. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15546. }
  15547. uvs1.push( uvCopy );
  15548. }
  15549. },
  15550. // Get random point in triangle (via barycentric coordinates)
  15551. // (uniform distribution)
  15552. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15553. randomPointInTriangle: function () {
  15554. var vector = new THREE.Vector3();
  15555. return function ( vectorA, vectorB, vectorC ) {
  15556. var point = new THREE.Vector3();
  15557. var a = THREE.Math.random16();
  15558. var b = THREE.Math.random16();
  15559. if ( ( a + b ) > 1 ) {
  15560. a = 1 - a;
  15561. b = 1 - b;
  15562. }
  15563. var c = 1 - a - b;
  15564. point.copy( vectorA );
  15565. point.multiplyScalar( a );
  15566. vector.copy( vectorB );
  15567. vector.multiplyScalar( b );
  15568. point.add( vector );
  15569. vector.copy( vectorC );
  15570. vector.multiplyScalar( c );
  15571. point.add( vector );
  15572. return point;
  15573. };
  15574. }(),
  15575. // Get random point in face (triangle / quad)
  15576. // (uniform distribution)
  15577. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15578. var vA, vB, vC, vD;
  15579. vA = geometry.vertices[ face.a ];
  15580. vB = geometry.vertices[ face.b ];
  15581. vC = geometry.vertices[ face.c ];
  15582. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15583. },
  15584. // Get uniformly distributed random points in mesh
  15585. // - create array with cumulative sums of face areas
  15586. // - pick random number from 0 to total area
  15587. // - find corresponding place in area array by binary search
  15588. // - get random point in face
  15589. randomPointsInGeometry: function ( geometry, n ) {
  15590. var face, i,
  15591. faces = geometry.faces,
  15592. vertices = geometry.vertices,
  15593. il = faces.length,
  15594. totalArea = 0,
  15595. cumulativeAreas = [],
  15596. vA, vB, vC, vD;
  15597. // precompute face areas
  15598. for ( i = 0; i < il; i ++ ) {
  15599. face = faces[ i ];
  15600. vA = vertices[ face.a ];
  15601. vB = vertices[ face.b ];
  15602. vC = vertices[ face.c ];
  15603. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  15604. totalArea += face._area;
  15605. cumulativeAreas[ i ] = totalArea;
  15606. }
  15607. // binary search cumulative areas array
  15608. function binarySearchIndices( value ) {
  15609. function binarySearch( start, end ) {
  15610. // return closest larger index
  15611. // if exact number is not found
  15612. if ( end < start )
  15613. return start;
  15614. var mid = start + Math.floor( ( end - start ) / 2 );
  15615. if ( cumulativeAreas[ mid ] > value ) {
  15616. return binarySearch( start, mid - 1 );
  15617. } else if ( cumulativeAreas[ mid ] < value ) {
  15618. return binarySearch( mid + 1, end );
  15619. } else {
  15620. return mid;
  15621. }
  15622. }
  15623. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  15624. return result;
  15625. }
  15626. // pick random face weighted by face area
  15627. var r, index,
  15628. result = [];
  15629. var stats = {};
  15630. for ( i = 0; i < n; i ++ ) {
  15631. r = THREE.Math.random16() * totalArea;
  15632. index = binarySearchIndices( r );
  15633. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  15634. if ( ! stats[ index ] ) {
  15635. stats[ index ] = 1;
  15636. } else {
  15637. stats[ index ] += 1;
  15638. }
  15639. }
  15640. return result;
  15641. },
  15642. // Get triangle area (half of parallelogram)
  15643. // http://mathworld.wolfram.com/TriangleArea.html
  15644. triangleArea: function () {
  15645. var vector1 = new THREE.Vector3();
  15646. var vector2 = new THREE.Vector3();
  15647. return function ( vectorA, vectorB, vectorC ) {
  15648. vector1.subVectors( vectorB, vectorA );
  15649. vector2.subVectors( vectorC, vectorA );
  15650. vector1.cross( vector2 );
  15651. return 0.5 * vector1.length();
  15652. };
  15653. }(),
  15654. // Center geometry so that 0,0,0 is in center of bounding box
  15655. center: function ( geometry ) {
  15656. geometry.computeBoundingBox();
  15657. var bb = geometry.boundingBox;
  15658. var offset = new THREE.Vector3();
  15659. offset.addVectors( bb.min, bb.max );
  15660. offset.multiplyScalar( -0.5 );
  15661. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  15662. geometry.computeBoundingBox();
  15663. return offset;
  15664. },
  15665. triangulateQuads: function ( geometry ) {
  15666. var i, il, j, jl;
  15667. var faces = [];
  15668. var faceVertexUvs = [];
  15669. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15670. faceVertexUvs[ i ] = [];
  15671. }
  15672. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15673. var face = geometry.faces[ i ];
  15674. faces.push( face );
  15675. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15676. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15677. }
  15678. }
  15679. geometry.faces = faces;
  15680. geometry.faceVertexUvs = faceVertexUvs;
  15681. geometry.computeCentroids();
  15682. geometry.computeFaceNormals();
  15683. geometry.computeVertexNormals();
  15684. if ( geometry.hasTangents ) geometry.computeTangents();
  15685. }
  15686. };
  15687. /**
  15688. * @author alteredq / http://alteredqualia.com/
  15689. * @author mrdoob / http://mrdoob.com/
  15690. */
  15691. THREE.ImageUtils = {
  15692. crossOrigin: 'anonymous',
  15693. loadTexture: function ( url, mapping, onLoad, onError ) {
  15694. var loader = new THREE.ImageLoader();
  15695. loader.crossOrigin = this.crossOrigin;
  15696. var texture = new THREE.Texture( undefined, mapping );
  15697. var image = loader.load( url, function () {
  15698. texture.needsUpdate = true;
  15699. if ( onLoad ) onLoad( texture );
  15700. } );
  15701. texture.image = image;
  15702. texture.sourceFile = url;
  15703. return texture;
  15704. },
  15705. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15706. var texture = new THREE.CompressedTexture();
  15707. texture.mapping = mapping;
  15708. var request = new XMLHttpRequest();
  15709. request.onload = function () {
  15710. var buffer = request.response;
  15711. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15712. texture.format = dds.format;
  15713. texture.mipmaps = dds.mipmaps;
  15714. texture.image.width = dds.width;
  15715. texture.image.height = dds.height;
  15716. // gl.generateMipmap fails for compressed textures
  15717. // mipmaps must be embedded in the DDS file
  15718. // or texture filters must not use mipmapping
  15719. texture.generateMipmaps = false;
  15720. texture.needsUpdate = true;
  15721. if ( onLoad ) onLoad( texture );
  15722. }
  15723. request.onerror = onError;
  15724. request.open( 'GET', url, true );
  15725. request.responseType = "arraybuffer";
  15726. request.send( null );
  15727. return texture;
  15728. },
  15729. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15730. var images = [];
  15731. images.loadCount = 0;
  15732. var texture = new THREE.Texture();
  15733. texture.image = images;
  15734. if ( mapping !== undefined ) texture.mapping = mapping;
  15735. // no flipping needed for cube textures
  15736. texture.flipY = false;
  15737. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15738. var cubeImage = new Image();
  15739. images[ i ] = cubeImage;
  15740. cubeImage.onload = function () {
  15741. images.loadCount += 1;
  15742. if ( images.loadCount === 6 ) {
  15743. texture.needsUpdate = true;
  15744. if ( onLoad ) onLoad( texture );
  15745. }
  15746. };
  15747. cubeImage.onerror = onError;
  15748. cubeImage.crossOrigin = this.crossOrigin;
  15749. cubeImage.src = array[ i ];
  15750. }
  15751. return texture;
  15752. },
  15753. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15754. var images = [];
  15755. images.loadCount = 0;
  15756. var texture = new THREE.CompressedTexture();
  15757. texture.image = images;
  15758. if ( mapping !== undefined ) texture.mapping = mapping;
  15759. // no flipping for cube textures
  15760. // (also flipping doesn't work for compressed textures )
  15761. texture.flipY = false;
  15762. // can't generate mipmaps for compressed textures
  15763. // mips must be embedded in DDS files
  15764. texture.generateMipmaps = false;
  15765. var generateCubeFaceCallback = function ( rq, img ) {
  15766. return function () {
  15767. var buffer = rq.response;
  15768. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15769. img.format = dds.format;
  15770. img.mipmaps = dds.mipmaps;
  15771. img.width = dds.width;
  15772. img.height = dds.height;
  15773. images.loadCount += 1;
  15774. if ( images.loadCount === 6 ) {
  15775. texture.format = dds.format;
  15776. texture.needsUpdate = true;
  15777. if ( onLoad ) onLoad( texture );
  15778. }
  15779. }
  15780. }
  15781. // compressed cubemap textures as 6 separate DDS files
  15782. if ( array instanceof Array ) {
  15783. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15784. var cubeImage = {};
  15785. images[ i ] = cubeImage;
  15786. var request = new XMLHttpRequest();
  15787. request.onload = generateCubeFaceCallback( request, cubeImage );
  15788. request.onerror = onError;
  15789. var url = array[ i ];
  15790. request.open( 'GET', url, true );
  15791. request.responseType = "arraybuffer";
  15792. request.send( null );
  15793. }
  15794. // compressed cubemap texture stored in a single DDS file
  15795. } else {
  15796. var url = array;
  15797. var request = new XMLHttpRequest();
  15798. request.onload = function( ) {
  15799. var buffer = request.response;
  15800. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15801. if ( dds.isCubemap ) {
  15802. var faces = dds.mipmaps.length / dds.mipmapCount;
  15803. for ( var f = 0; f < faces; f ++ ) {
  15804. images[ f ] = { mipmaps : [] };
  15805. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15806. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15807. images[ f ].format = dds.format;
  15808. images[ f ].width = dds.width;
  15809. images[ f ].height = dds.height;
  15810. }
  15811. }
  15812. texture.format = dds.format;
  15813. texture.needsUpdate = true;
  15814. if ( onLoad ) onLoad( texture );
  15815. }
  15816. }
  15817. request.onerror = onError;
  15818. request.open( 'GET', url, true );
  15819. request.responseType = "arraybuffer";
  15820. request.send( null );
  15821. }
  15822. return texture;
  15823. },
  15824. loadDDSTexture: function ( url, mapping, onLoad, onError ) {
  15825. var images = [];
  15826. images.loadCount = 0;
  15827. var texture = new THREE.CompressedTexture();
  15828. texture.image = images;
  15829. if ( mapping !== undefined ) texture.mapping = mapping;
  15830. // no flipping for cube textures
  15831. // (also flipping doesn't work for compressed textures )
  15832. texture.flipY = false;
  15833. // can't generate mipmaps for compressed textures
  15834. // mips must be embedded in DDS files
  15835. texture.generateMipmaps = false;
  15836. {
  15837. var request = new XMLHttpRequest();
  15838. request.onload = function( ) {
  15839. var buffer = request.response;
  15840. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15841. if ( dds.isCubemap ) {
  15842. var faces = dds.mipmaps.length / dds.mipmapCount;
  15843. for ( var f = 0; f < faces; f ++ ) {
  15844. images[ f ] = { mipmaps : [] };
  15845. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15846. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15847. images[ f ].format = dds.format;
  15848. images[ f ].width = dds.width;
  15849. images[ f ].height = dds.height;
  15850. }
  15851. }
  15852. } else {
  15853. texture.image.width = dds.width;
  15854. texture.image.height = dds.height;
  15855. texture.mipmaps = dds.mipmaps;
  15856. }
  15857. texture.format = dds.format;
  15858. texture.needsUpdate = true;
  15859. if ( onLoad ) onLoad( texture );
  15860. }
  15861. request.onerror = onError;
  15862. request.open( 'GET', url, true );
  15863. request.responseType = "arraybuffer";
  15864. request.send( null );
  15865. }
  15866. return texture;
  15867. },
  15868. parseDDS: function ( buffer, loadMipmaps ) {
  15869. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15870. // Adapted from @toji's DDS utils
  15871. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15872. // All values and structures referenced from:
  15873. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15874. var DDS_MAGIC = 0x20534444;
  15875. var DDSD_CAPS = 0x1,
  15876. DDSD_HEIGHT = 0x2,
  15877. DDSD_WIDTH = 0x4,
  15878. DDSD_PITCH = 0x8,
  15879. DDSD_PIXELFORMAT = 0x1000,
  15880. DDSD_MIPMAPCOUNT = 0x20000,
  15881. DDSD_LINEARSIZE = 0x80000,
  15882. DDSD_DEPTH = 0x800000;
  15883. var DDSCAPS_COMPLEX = 0x8,
  15884. DDSCAPS_MIPMAP = 0x400000,
  15885. DDSCAPS_TEXTURE = 0x1000;
  15886. var DDSCAPS2_CUBEMAP = 0x200,
  15887. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15888. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15889. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15890. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15891. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15892. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15893. DDSCAPS2_VOLUME = 0x200000;
  15894. var DDPF_ALPHAPIXELS = 0x1,
  15895. DDPF_ALPHA = 0x2,
  15896. DDPF_FOURCC = 0x4,
  15897. DDPF_RGB = 0x40,
  15898. DDPF_YUV = 0x200,
  15899. DDPF_LUMINANCE = 0x20000;
  15900. function fourCCToInt32( value ) {
  15901. return value.charCodeAt(0) +
  15902. (value.charCodeAt(1) << 8) +
  15903. (value.charCodeAt(2) << 16) +
  15904. (value.charCodeAt(3) << 24);
  15905. }
  15906. function int32ToFourCC( value ) {
  15907. return String.fromCharCode(
  15908. value & 0xff,
  15909. (value >> 8) & 0xff,
  15910. (value >> 16) & 0xff,
  15911. (value >> 24) & 0xff
  15912. );
  15913. }
  15914. function loadARGBMip( buffer, dataOffset, width, height ) {
  15915. var dataLength = width*height*4;
  15916. var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength );
  15917. var byteArray = new Uint8Array( dataLength );
  15918. var dst = 0;
  15919. var src = 0;
  15920. for ( var y = 0; y < height; y++ ) {
  15921. for ( var x = 0; x < width; x++ ) {
  15922. var b = srcBuffer[src]; src++;
  15923. var g = srcBuffer[src]; src++;
  15924. var r = srcBuffer[src]; src++;
  15925. var a = srcBuffer[src]; src++;
  15926. byteArray[dst] = r; dst++; //r
  15927. byteArray[dst] = g; dst++; //g
  15928. byteArray[dst] = b; dst++; //b
  15929. byteArray[dst] = a; dst++; //a
  15930. }
  15931. }
  15932. return byteArray;
  15933. }
  15934. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15935. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15936. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15937. var headerLengthInt = 31; // The header length in 32 bit ints
  15938. // Offsets into the header array
  15939. var off_magic = 0;
  15940. var off_size = 1;
  15941. var off_flags = 2;
  15942. var off_height = 3;
  15943. var off_width = 4;
  15944. var off_mipmapCount = 7;
  15945. var off_pfFlags = 20;
  15946. var off_pfFourCC = 21;
  15947. var off_RGBBitCount = 22;
  15948. var off_RBitMask = 23;
  15949. var off_GBitMask = 24;
  15950. var off_BBitMask = 25;
  15951. var off_ABitMask = 26;
  15952. var off_caps = 27;
  15953. var off_caps2 = 28;
  15954. var off_caps3 = 29;
  15955. var off_caps4 = 30;
  15956. // Parse header
  15957. var header = new Int32Array( buffer, 0, headerLengthInt );
  15958. if ( header[ off_magic ] !== DDS_MAGIC ) {
  15959. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  15960. return dds;
  15961. }
  15962. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  15963. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  15964. return dds;
  15965. }
  15966. var blockBytes;
  15967. var fourCC = header[ off_pfFourCC ];
  15968. var isRGBAUncompressed = false;
  15969. switch ( fourCC ) {
  15970. case FOURCC_DXT1:
  15971. blockBytes = 8;
  15972. dds.format = THREE.RGB_S3TC_DXT1_Format;
  15973. break;
  15974. case FOURCC_DXT3:
  15975. blockBytes = 16;
  15976. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  15977. break;
  15978. case FOURCC_DXT5:
  15979. blockBytes = 16;
  15980. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  15981. break;
  15982. default:
  15983. if( header[off_RGBBitCount] ==32
  15984. && header[off_RBitMask]&0xff0000
  15985. && header[off_GBitMask]&0xff00
  15986. && header[off_BBitMask]&0xff
  15987. && header[off_ABitMask]&0xff000000 ) {
  15988. isRGBAUncompressed = true;
  15989. blockBytes = 64;
  15990. dds.format = THREE.RGBAFormat;
  15991. } else {
  15992. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  15993. return dds;
  15994. }
  15995. }
  15996. dds.mipmapCount = 1;
  15997. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  15998. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  15999. }
  16000. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  16001. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  16002. dds.width = header[ off_width ];
  16003. dds.height = header[ off_height ];
  16004. var dataOffset = header[ off_size ] + 4;
  16005. // Extract mipmaps buffers
  16006. var width = dds.width;
  16007. var height = dds.height;
  16008. var faces = dds.isCubemap ? 6 : 1;
  16009. for ( var face = 0; face < faces; face ++ ) {
  16010. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16011. if( isRGBAUncompressed ) {
  16012. var byteArray = loadARGBMip( buffer, dataOffset, width, height );
  16013. var dataLength = byteArray.length;
  16014. } else {
  16015. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16016. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16017. }
  16018. var mipmap = { "data": byteArray, "width": width, "height": height };
  16019. dds.mipmaps.push( mipmap );
  16020. dataOffset += dataLength;
  16021. width = Math.max( width * 0.5, 1 );
  16022. height = Math.max( height * 0.5, 1 );
  16023. }
  16024. width = dds.width;
  16025. height = dds.height;
  16026. }
  16027. return dds;
  16028. },
  16029. getNormalMap: function ( image, depth ) {
  16030. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16031. var cross = function ( a, b ) {
  16032. 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 ] ];
  16033. }
  16034. var subtract = function ( a, b ) {
  16035. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16036. }
  16037. var normalize = function ( a ) {
  16038. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16039. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16040. }
  16041. depth = depth | 1;
  16042. var width = image.width;
  16043. var height = image.height;
  16044. var canvas = document.createElement( 'canvas' );
  16045. canvas.width = width;
  16046. canvas.height = height;
  16047. var context = canvas.getContext( '2d' );
  16048. context.drawImage( image, 0, 0 );
  16049. var data = context.getImageData( 0, 0, width, height ).data;
  16050. var imageData = context.createImageData( width, height );
  16051. var output = imageData.data;
  16052. for ( var x = 0; x < width; x ++ ) {
  16053. for ( var y = 0; y < height; y ++ ) {
  16054. var ly = y - 1 < 0 ? 0 : y - 1;
  16055. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16056. var lx = x - 1 < 0 ? 0 : x - 1;
  16057. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16058. var points = [];
  16059. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16060. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16061. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16062. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16063. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16064. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16065. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16066. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16067. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16068. var normals = [];
  16069. var num_points = points.length;
  16070. for ( var i = 0; i < num_points; i ++ ) {
  16071. var v1 = points[ i ];
  16072. var v2 = points[ ( i + 1 ) % num_points ];
  16073. v1 = subtract( v1, origin );
  16074. v2 = subtract( v2, origin );
  16075. normals.push( normalize( cross( v1, v2 ) ) );
  16076. }
  16077. var normal = [ 0, 0, 0 ];
  16078. for ( var i = 0; i < normals.length; i ++ ) {
  16079. normal[ 0 ] += normals[ i ][ 0 ];
  16080. normal[ 1 ] += normals[ i ][ 1 ];
  16081. normal[ 2 ] += normals[ i ][ 2 ];
  16082. }
  16083. normal[ 0 ] /= normals.length;
  16084. normal[ 1 ] /= normals.length;
  16085. normal[ 2 ] /= normals.length;
  16086. var idx = ( y * width + x ) * 4;
  16087. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16088. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16089. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16090. output[ idx + 3 ] = 255;
  16091. }
  16092. }
  16093. context.putImageData( imageData, 0, 0 );
  16094. return canvas;
  16095. },
  16096. generateDataTexture: function ( width, height, color ) {
  16097. var size = width * height;
  16098. var data = new Uint8Array( 3 * size );
  16099. var r = Math.floor( color.r * 255 );
  16100. var g = Math.floor( color.g * 255 );
  16101. var b = Math.floor( color.b * 255 );
  16102. for ( var i = 0; i < size; i ++ ) {
  16103. data[ i * 3 ] = r;
  16104. data[ i * 3 + 1 ] = g;
  16105. data[ i * 3 + 2 ] = b;
  16106. }
  16107. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16108. texture.needsUpdate = true;
  16109. return texture;
  16110. }
  16111. };
  16112. /**
  16113. * @author alteredq / http://alteredqualia.com/
  16114. */
  16115. THREE.SceneUtils = {
  16116. createMultiMaterialObject: function ( geometry, materials ) {
  16117. var group = new THREE.Object3D();
  16118. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16119. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16120. }
  16121. return group;
  16122. },
  16123. detach : function ( child, parent, scene ) {
  16124. child.applyMatrix( parent.matrixWorld );
  16125. parent.remove( child );
  16126. scene.add( child );
  16127. },
  16128. attach: function ( child, scene, parent ) {
  16129. var matrixWorldInverse = new THREE.Matrix4();
  16130. matrixWorldInverse.getInverse( parent.matrixWorld );
  16131. child.applyMatrix( matrixWorldInverse );
  16132. scene.remove( child );
  16133. parent.add( child );
  16134. }
  16135. };
  16136. /**
  16137. * @author zz85 / http://www.lab4games.net/zz85/blog
  16138. * @author alteredq / http://alteredqualia.com/
  16139. *
  16140. * For Text operations in three.js (See TextGeometry)
  16141. *
  16142. * It uses techniques used in:
  16143. *
  16144. * typeface.js and canvastext
  16145. * For converting fonts and rendering with javascript
  16146. * http://typeface.neocracy.org
  16147. *
  16148. * Triangulation ported from AS3
  16149. * Simple Polygon Triangulation
  16150. * http://actionsnippet.com/?p=1462
  16151. *
  16152. * A Method to triangulate shapes with holes
  16153. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16154. *
  16155. */
  16156. THREE.FontUtils = {
  16157. faces : {},
  16158. // Just for now. face[weight][style]
  16159. face : "helvetiker",
  16160. weight: "normal",
  16161. style : "normal",
  16162. size : 150,
  16163. divisions : 10,
  16164. getFace : function() {
  16165. return this.faces[ this.face ][ this.weight ][ this.style ];
  16166. },
  16167. loadFace : function( data ) {
  16168. var family = data.familyName.toLowerCase();
  16169. var ThreeFont = this;
  16170. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16171. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16172. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16173. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16174. return data;
  16175. },
  16176. drawText : function( text ) {
  16177. var characterPts = [], allPts = [];
  16178. // RenderText
  16179. var i, p,
  16180. face = this.getFace(),
  16181. scale = this.size / face.resolution,
  16182. offset = 0,
  16183. chars = String( text ).split( '' ),
  16184. length = chars.length;
  16185. var fontPaths = [];
  16186. for ( i = 0; i < length; i ++ ) {
  16187. var path = new THREE.Path();
  16188. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16189. offset += ret.offset;
  16190. fontPaths.push( ret.path );
  16191. }
  16192. // get the width
  16193. var width = offset / 2;
  16194. //
  16195. // for ( p = 0; p < allPts.length; p++ ) {
  16196. //
  16197. // allPts[ p ].x -= width;
  16198. //
  16199. // }
  16200. //var extract = this.extractPoints( allPts, characterPts );
  16201. //extract.contour = allPts;
  16202. //extract.paths = fontPaths;
  16203. //extract.offset = width;
  16204. return { paths : fontPaths, offset : width };
  16205. },
  16206. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16207. var pts = [];
  16208. var i, i2, divisions,
  16209. outline, action, length,
  16210. scaleX, scaleY,
  16211. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16212. laste,
  16213. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16214. if ( !glyph ) return;
  16215. if ( glyph.o ) {
  16216. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16217. length = outline.length;
  16218. scaleX = scale;
  16219. scaleY = scale;
  16220. for ( i = 0; i < length; ) {
  16221. action = outline[ i ++ ];
  16222. //console.log( action );
  16223. switch( action ) {
  16224. case 'm':
  16225. // Move To
  16226. x = outline[ i++ ] * scaleX + offset;
  16227. y = outline[ i++ ] * scaleY;
  16228. path.moveTo( x, y );
  16229. break;
  16230. case 'l':
  16231. // Line To
  16232. x = outline[ i++ ] * scaleX + offset;
  16233. y = outline[ i++ ] * scaleY;
  16234. path.lineTo(x,y);
  16235. break;
  16236. case 'q':
  16237. // QuadraticCurveTo
  16238. cpx = outline[ i++ ] * scaleX + offset;
  16239. cpy = outline[ i++ ] * scaleY;
  16240. cpx1 = outline[ i++ ] * scaleX + offset;
  16241. cpy1 = outline[ i++ ] * scaleY;
  16242. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16243. laste = pts[ pts.length - 1 ];
  16244. if ( laste ) {
  16245. cpx0 = laste.x;
  16246. cpy0 = laste.y;
  16247. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16248. var t = i2 / divisions;
  16249. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16250. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16251. }
  16252. }
  16253. break;
  16254. case 'b':
  16255. // Cubic Bezier Curve
  16256. cpx = outline[ i++ ] * scaleX + offset;
  16257. cpy = outline[ i++ ] * scaleY;
  16258. cpx1 = outline[ i++ ] * scaleX + offset;
  16259. cpy1 = outline[ i++ ] * -scaleY;
  16260. cpx2 = outline[ i++ ] * scaleX + offset;
  16261. cpy2 = outline[ i++ ] * -scaleY;
  16262. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16263. laste = pts[ pts.length - 1 ];
  16264. if ( laste ) {
  16265. cpx0 = laste.x;
  16266. cpy0 = laste.y;
  16267. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16268. var t = i2 / divisions;
  16269. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16270. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16271. }
  16272. }
  16273. break;
  16274. }
  16275. }
  16276. }
  16277. return { offset: glyph.ha*scale, path:path};
  16278. }
  16279. };
  16280. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16281. // Parameters
  16282. parameters = parameters || {};
  16283. var size = parameters.size !== undefined ? parameters.size : 100;
  16284. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16285. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16286. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16287. var style = parameters.style !== undefined ? parameters.style : "normal";
  16288. THREE.FontUtils.size = size;
  16289. THREE.FontUtils.divisions = curveSegments;
  16290. THREE.FontUtils.face = font;
  16291. THREE.FontUtils.weight = weight;
  16292. THREE.FontUtils.style = style;
  16293. // Get a Font data json object
  16294. var data = THREE.FontUtils.drawText( text );
  16295. var paths = data.paths;
  16296. var shapes = [];
  16297. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16298. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16299. }
  16300. return shapes;
  16301. };
  16302. /**
  16303. * This code is a quick port of code written in C++ which was submitted to
  16304. * flipcode.com by John W. Ratcliff // July 22, 2000
  16305. * See original code and more information here:
  16306. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16307. *
  16308. * ported to actionscript by Zevan Rosser
  16309. * www.actionsnippet.com
  16310. *
  16311. * ported to javascript by Joshua Koo
  16312. * http://www.lab4games.net/zz85/blog
  16313. *
  16314. */
  16315. ( function( namespace ) {
  16316. var EPSILON = 0.0000000001;
  16317. // takes in an contour array and returns
  16318. var process = function( contour, indices ) {
  16319. var n = contour.length;
  16320. if ( n < 3 ) return null;
  16321. var result = [],
  16322. verts = [],
  16323. vertIndices = [];
  16324. /* we want a counter-clockwise polygon in verts */
  16325. var u, v, w;
  16326. if ( area( contour ) > 0.0 ) {
  16327. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16328. } else {
  16329. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16330. }
  16331. var nv = n;
  16332. /* remove nv - 2 vertices, creating 1 triangle every time */
  16333. var count = 2 * nv; /* error detection */
  16334. for( v = nv - 1; nv > 2; ) {
  16335. /* if we loop, it is probably a non-simple polygon */
  16336. if ( ( count-- ) <= 0 ) {
  16337. //** Triangulate: ERROR - probable bad polygon!
  16338. //throw ( "Warning, unable to triangulate polygon!" );
  16339. //return null;
  16340. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16341. console.log( "Warning, unable to triangulate polygon!" );
  16342. if ( indices ) return vertIndices;
  16343. return result;
  16344. }
  16345. /* three consecutive vertices in current polygon, <u,v,w> */
  16346. u = v; if ( nv <= u ) u = 0; /* previous */
  16347. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16348. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16349. if ( snip( contour, u, v, w, nv, verts ) ) {
  16350. var a, b, c, s, t;
  16351. /* true names of the vertices */
  16352. a = verts[ u ];
  16353. b = verts[ v ];
  16354. c = verts[ w ];
  16355. /* output Triangle */
  16356. result.push( [ contour[ a ],
  16357. contour[ b ],
  16358. contour[ c ] ] );
  16359. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16360. /* remove v from the remaining polygon */
  16361. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16362. verts[ s ] = verts[ t ];
  16363. }
  16364. nv--;
  16365. /* reset error detection counter */
  16366. count = 2 * nv;
  16367. }
  16368. }
  16369. if ( indices ) return vertIndices;
  16370. return result;
  16371. };
  16372. // calculate area of the contour polygon
  16373. var area = function ( contour ) {
  16374. var n = contour.length;
  16375. var a = 0.0;
  16376. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16377. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16378. }
  16379. return a * 0.5;
  16380. };
  16381. var snip = function ( contour, u, v, w, n, verts ) {
  16382. var p;
  16383. var ax, ay, bx, by;
  16384. var cx, cy, px, py;
  16385. ax = contour[ verts[ u ] ].x;
  16386. ay = contour[ verts[ u ] ].y;
  16387. bx = contour[ verts[ v ] ].x;
  16388. by = contour[ verts[ v ] ].y;
  16389. cx = contour[ verts[ w ] ].x;
  16390. cy = contour[ verts[ w ] ].y;
  16391. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16392. var aX, aY, bX, bY, cX, cY;
  16393. var apx, apy, bpx, bpy, cpx, cpy;
  16394. var cCROSSap, bCROSScp, aCROSSbp;
  16395. aX = cx - bx; aY = cy - by;
  16396. bX = ax - cx; bY = ay - cy;
  16397. cX = bx - ax; cY = by - ay;
  16398. for ( p = 0; p < n; p++ ) {
  16399. if( (p === u) || (p === v) || (p === w) ) continue;
  16400. px = contour[ verts[ p ] ].x
  16401. py = contour[ verts[ p ] ].y
  16402. apx = px - ax; apy = py - ay;
  16403. bpx = px - bx; bpy = py - by;
  16404. cpx = px - cx; cpy = py - cy;
  16405. // see if p is inside triangle abc
  16406. aCROSSbp = aX*bpy - aY*bpx;
  16407. cCROSSap = cX*apy - cY*apx;
  16408. bCROSScp = bX*cpy - bY*cpx;
  16409. if ( (aCROSSbp >= -EPSILON) && (bCROSScp >= -EPSILON) && (cCROSSap >= -EPSILON) ) return false;
  16410. }
  16411. return true;
  16412. };
  16413. namespace.Triangulate = process;
  16414. namespace.Triangulate.area = area;
  16415. return namespace;
  16416. })(THREE.FontUtils);
  16417. // To use the typeface.js face files, hook up the API
  16418. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16419. THREE.typeface_js = self._typeface_js;
  16420. /**
  16421. * @author zz85 / http://www.lab4games.net/zz85/blog
  16422. * Extensible curve object
  16423. *
  16424. * Some common of Curve methods
  16425. * .getPoint(t), getTangent(t)
  16426. * .getPointAt(u), getTagentAt(u)
  16427. * .getPoints(), .getSpacedPoints()
  16428. * .getLength()
  16429. * .updateArcLengths()
  16430. *
  16431. * This following classes subclasses THREE.Curve:
  16432. *
  16433. * -- 2d classes --
  16434. * THREE.LineCurve
  16435. * THREE.QuadraticBezierCurve
  16436. * THREE.CubicBezierCurve
  16437. * THREE.SplineCurve
  16438. * THREE.ArcCurve
  16439. * THREE.EllipseCurve
  16440. *
  16441. * -- 3d classes --
  16442. * THREE.LineCurve3
  16443. * THREE.QuadraticBezierCurve3
  16444. * THREE.CubicBezierCurve3
  16445. * THREE.SplineCurve3
  16446. * THREE.ClosedSplineCurve3
  16447. *
  16448. * A series of curves can be represented as a THREE.CurvePath
  16449. *
  16450. **/
  16451. /**************************************************************
  16452. * Abstract Curve base class
  16453. **************************************************************/
  16454. THREE.Curve = function () {
  16455. };
  16456. // Virtual base class method to overwrite and implement in subclasses
  16457. // - t [0 .. 1]
  16458. THREE.Curve.prototype.getPoint = function ( t ) {
  16459. console.log( "Warning, getPoint() not implemented!" );
  16460. return null;
  16461. };
  16462. // Get point at relative position in curve according to arc length
  16463. // - u [0 .. 1]
  16464. THREE.Curve.prototype.getPointAt = function ( u ) {
  16465. var t = this.getUtoTmapping( u );
  16466. return this.getPoint( t );
  16467. };
  16468. // Get sequence of points using getPoint( t )
  16469. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16470. if ( !divisions ) divisions = 5;
  16471. var d, pts = [];
  16472. for ( d = 0; d <= divisions; d ++ ) {
  16473. pts.push( this.getPoint( d / divisions ) );
  16474. }
  16475. return pts;
  16476. };
  16477. // Get sequence of points using getPointAt( u )
  16478. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16479. if ( !divisions ) divisions = 5;
  16480. var d, pts = [];
  16481. for ( d = 0; d <= divisions; d ++ ) {
  16482. pts.push( this.getPointAt( d / divisions ) );
  16483. }
  16484. return pts;
  16485. };
  16486. // Get total curve arc length
  16487. THREE.Curve.prototype.getLength = function () {
  16488. var lengths = this.getLengths();
  16489. return lengths[ lengths.length - 1 ];
  16490. };
  16491. // Get list of cumulative segment lengths
  16492. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16493. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16494. if ( this.cacheArcLengths
  16495. && ( this.cacheArcLengths.length == divisions + 1 )
  16496. && !this.needsUpdate) {
  16497. //console.log( "cached", this.cacheArcLengths );
  16498. return this.cacheArcLengths;
  16499. }
  16500. this.needsUpdate = false;
  16501. var cache = [];
  16502. var current, last = this.getPoint( 0 );
  16503. var p, sum = 0;
  16504. cache.push( 0 );
  16505. for ( p = 1; p <= divisions; p ++ ) {
  16506. current = this.getPoint ( p / divisions );
  16507. sum += current.distanceTo( last );
  16508. cache.push( sum );
  16509. last = current;
  16510. }
  16511. this.cacheArcLengths = cache;
  16512. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16513. };
  16514. THREE.Curve.prototype.updateArcLengths = function() {
  16515. this.needsUpdate = true;
  16516. this.getLengths();
  16517. };
  16518. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16519. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16520. var arcLengths = this.getLengths();
  16521. var i = 0, il = arcLengths.length;
  16522. var targetArcLength; // The targeted u distance value to get
  16523. if ( distance ) {
  16524. targetArcLength = distance;
  16525. } else {
  16526. targetArcLength = u * arcLengths[ il - 1 ];
  16527. }
  16528. //var time = Date.now();
  16529. // binary search for the index with largest value smaller than target u distance
  16530. var low = 0, high = il - 1, comparison;
  16531. while ( low <= high ) {
  16532. 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
  16533. comparison = arcLengths[ i ] - targetArcLength;
  16534. if ( comparison < 0 ) {
  16535. low = i + 1;
  16536. continue;
  16537. } else if ( comparison > 0 ) {
  16538. high = i - 1;
  16539. continue;
  16540. } else {
  16541. high = i;
  16542. break;
  16543. // DONE
  16544. }
  16545. }
  16546. i = high;
  16547. //console.log('b' , i, low, high, Date.now()- time);
  16548. if ( arcLengths[ i ] == targetArcLength ) {
  16549. var t = i / ( il - 1 );
  16550. return t;
  16551. }
  16552. // we could get finer grain at lengths, or use simple interpolatation between two points
  16553. var lengthBefore = arcLengths[ i ];
  16554. var lengthAfter = arcLengths[ i + 1 ];
  16555. var segmentLength = lengthAfter - lengthBefore;
  16556. // determine where we are between the 'before' and 'after' points
  16557. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16558. // add that fractional amount to t
  16559. var t = ( i + segmentFraction ) / ( il -1 );
  16560. return t;
  16561. };
  16562. // Returns a unit vector tangent at t
  16563. // In case any sub curve does not implement its tangent derivation,
  16564. // 2 points a small delta apart will be used to find its gradient
  16565. // which seems to give a reasonable approximation
  16566. THREE.Curve.prototype.getTangent = function( t ) {
  16567. var delta = 0.0001;
  16568. var t1 = t - delta;
  16569. var t2 = t + delta;
  16570. // Capping in case of danger
  16571. if ( t1 < 0 ) t1 = 0;
  16572. if ( t2 > 1 ) t2 = 1;
  16573. var pt1 = this.getPoint( t1 );
  16574. var pt2 = this.getPoint( t2 );
  16575. var vec = pt2.clone().sub(pt1);
  16576. return vec.normalize();
  16577. };
  16578. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16579. var t = this.getUtoTmapping( u );
  16580. return this.getTangent( t );
  16581. };
  16582. /**************************************************************
  16583. * Utils
  16584. **************************************************************/
  16585. THREE.Curve.Utils = {
  16586. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16587. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16588. },
  16589. // Puay Bing, thanks for helping with this derivative!
  16590. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16591. return -3 * p0 * (1 - t) * (1 - t) +
  16592. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16593. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16594. 3 * t * t * p3;
  16595. },
  16596. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16597. // To check if my formulas are correct
  16598. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16599. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16600. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16601. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16602. return h00 + h10 + h01 + h11;
  16603. },
  16604. // Catmull-Rom
  16605. interpolate: function( p0, p1, p2, p3, t ) {
  16606. var v0 = ( p2 - p0 ) * 0.5;
  16607. var v1 = ( p3 - p1 ) * 0.5;
  16608. var t2 = t * t;
  16609. var t3 = t * t2;
  16610. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16611. }
  16612. };
  16613. // TODO: Transformation for Curves?
  16614. /**************************************************************
  16615. * 3D Curves
  16616. **************************************************************/
  16617. // A Factory method for creating new curve subclasses
  16618. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16619. constructor.prototype = Object.create( THREE.Curve.prototype );
  16620. constructor.prototype.getPoint = getPointFunc;
  16621. return constructor;
  16622. };
  16623. /**
  16624. * @author zz85 / http://www.lab4games.net/zz85/blog
  16625. *
  16626. **/
  16627. /**************************************************************
  16628. * Curved Path - a curve path is simply a array of connected
  16629. * curves, but retains the api of a curve
  16630. **************************************************************/
  16631. THREE.CurvePath = function () {
  16632. this.curves = [];
  16633. this.bends = [];
  16634. this.autoClose = false; // Automatically closes the path
  16635. };
  16636. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16637. THREE.CurvePath.prototype.add = function ( curve ) {
  16638. this.curves.push( curve );
  16639. };
  16640. THREE.CurvePath.prototype.checkConnection = function() {
  16641. // TODO
  16642. // If the ending of curve is not connected to the starting
  16643. // or the next curve, then, this is not a real path
  16644. };
  16645. THREE.CurvePath.prototype.closePath = function() {
  16646. // TODO Test
  16647. // and verify for vector3 (needs to implement equals)
  16648. // Add a line curve if start and end of lines are not connected
  16649. var startPoint = this.curves[0].getPoint(0);
  16650. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16651. if (!startPoint.equals(endPoint)) {
  16652. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16653. }
  16654. };
  16655. // To get accurate point with reference to
  16656. // entire path distance at time t,
  16657. // following has to be done:
  16658. // 1. Length of each sub path have to be known
  16659. // 2. Locate and identify type of curve
  16660. // 3. Get t for the curve
  16661. // 4. Return curve.getPointAt(t')
  16662. THREE.CurvePath.prototype.getPoint = function( t ) {
  16663. var d = t * this.getLength();
  16664. var curveLengths = this.getCurveLengths();
  16665. var i = 0, diff, curve;
  16666. // To think about boundaries points.
  16667. while ( i < curveLengths.length ) {
  16668. if ( curveLengths[ i ] >= d ) {
  16669. diff = curveLengths[ i ] - d;
  16670. curve = this.curves[ i ];
  16671. var u = 1 - diff / curve.getLength();
  16672. return curve.getPointAt( u );
  16673. break;
  16674. }
  16675. i ++;
  16676. }
  16677. return null;
  16678. // loop where sum != 0, sum > d , sum+1 <d
  16679. };
  16680. /*
  16681. THREE.CurvePath.prototype.getTangent = function( t ) {
  16682. };*/
  16683. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16684. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16685. // getPoint() depends on getLength
  16686. THREE.CurvePath.prototype.getLength = function() {
  16687. var lens = this.getCurveLengths();
  16688. return lens[ lens.length - 1 ];
  16689. };
  16690. // Compute lengths and cache them
  16691. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16692. THREE.CurvePath.prototype.getCurveLengths = function() {
  16693. // We use cache values if curves and cache array are same length
  16694. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16695. return this.cacheLengths;
  16696. };
  16697. // Get length of subsurve
  16698. // Push sums into cached array
  16699. var lengths = [], sums = 0;
  16700. var i, il = this.curves.length;
  16701. for ( i = 0; i < il; i ++ ) {
  16702. sums += this.curves[ i ].getLength();
  16703. lengths.push( sums );
  16704. }
  16705. this.cacheLengths = lengths;
  16706. return lengths;
  16707. };
  16708. // Returns min and max coordinates, as well as centroid
  16709. THREE.CurvePath.prototype.getBoundingBox = function () {
  16710. var points = this.getPoints();
  16711. var maxX, maxY, maxZ;
  16712. var minX, minY, minZ;
  16713. maxX = maxY = Number.NEGATIVE_INFINITY;
  16714. minX = minY = Number.POSITIVE_INFINITY;
  16715. var p, i, il, sum;
  16716. var v3 = points[0] instanceof THREE.Vector3;
  16717. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16718. for ( i = 0, il = points.length; i < il; i ++ ) {
  16719. p = points[ i ];
  16720. if ( p.x > maxX ) maxX = p.x;
  16721. else if ( p.x < minX ) minX = p.x;
  16722. if ( p.y > maxY ) maxY = p.y;
  16723. else if ( p.y < minY ) minY = p.y;
  16724. if ( v3 ) {
  16725. if ( p.z > maxZ ) maxZ = p.z;
  16726. else if ( p.z < minZ ) minZ = p.z;
  16727. }
  16728. sum.add( p );
  16729. }
  16730. var ret = {
  16731. minX: minX,
  16732. minY: minY,
  16733. maxX: maxX,
  16734. maxY: maxY,
  16735. centroid: sum.divideScalar( il )
  16736. };
  16737. if ( v3 ) {
  16738. ret.maxZ = maxZ;
  16739. ret.minZ = minZ;
  16740. }
  16741. return ret;
  16742. };
  16743. /**************************************************************
  16744. * Create Geometries Helpers
  16745. **************************************************************/
  16746. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16747. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16748. var pts = this.getPoints( divisions, true );
  16749. return this.createGeometry( pts );
  16750. };
  16751. // Generate geometry from equidistance sampling along the path
  16752. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16753. var pts = this.getSpacedPoints( divisions, true );
  16754. return this.createGeometry( pts );
  16755. };
  16756. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16757. var geometry = new THREE.Geometry();
  16758. for ( var i = 0; i < points.length; i ++ ) {
  16759. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16760. }
  16761. return geometry;
  16762. };
  16763. /**************************************************************
  16764. * Bend / Wrap Helper Methods
  16765. **************************************************************/
  16766. // Wrap path / Bend modifiers?
  16767. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16768. this.bends.push( bendpath );
  16769. };
  16770. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16771. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16772. var i, il;
  16773. if ( !bends ) {
  16774. bends = this.bends;
  16775. }
  16776. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16777. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16778. }
  16779. return oldPts;
  16780. };
  16781. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16782. var oldPts = this.getSpacedPoints( segments );
  16783. var i, il;
  16784. if ( !bends ) {
  16785. bends = this.bends;
  16786. }
  16787. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16788. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16789. }
  16790. return oldPts;
  16791. };
  16792. // This returns getPoints() bend/wrapped around the contour of a path.
  16793. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16794. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16795. var bounds = this.getBoundingBox();
  16796. var i, il, p, oldX, oldY, xNorm;
  16797. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16798. p = oldPts[ i ];
  16799. oldX = p.x;
  16800. oldY = p.y;
  16801. xNorm = oldX / bounds.maxX;
  16802. // If using actual distance, for length > path, requires line extrusions
  16803. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16804. xNorm = path.getUtoTmapping( xNorm, oldX );
  16805. // check for out of bounds?
  16806. var pathPt = path.getPoint( xNorm );
  16807. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  16808. p.x = pathPt.x + normal.x;
  16809. p.y = pathPt.y + normal.y;
  16810. }
  16811. return oldPts;
  16812. };
  16813. /**
  16814. * @author alteredq / http://alteredqualia.com/
  16815. */
  16816. THREE.Gyroscope = function () {
  16817. THREE.Object3D.call( this );
  16818. };
  16819. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16820. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16821. this.matrixAutoUpdate && this.updateMatrix();
  16822. // update matrixWorld
  16823. if ( this.matrixWorldNeedsUpdate || force ) {
  16824. if ( this.parent ) {
  16825. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16826. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  16827. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  16828. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  16829. } else {
  16830. this.matrixWorld.copy( this.matrix );
  16831. }
  16832. this.matrixWorldNeedsUpdate = false;
  16833. force = true;
  16834. }
  16835. // update children
  16836. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16837. this.children[ i ].updateMatrixWorld( force );
  16838. }
  16839. };
  16840. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16841. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16842. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  16843. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  16844. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16845. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16846. /**
  16847. * @author zz85 / http://www.lab4games.net/zz85/blog
  16848. * Creates free form 2d path using series of points, lines or curves.
  16849. *
  16850. **/
  16851. THREE.Path = function ( points ) {
  16852. THREE.CurvePath.call(this);
  16853. this.actions = [];
  16854. if ( points ) {
  16855. this.fromPoints( points );
  16856. }
  16857. };
  16858. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16859. THREE.PathActions = {
  16860. MOVE_TO: 'moveTo',
  16861. LINE_TO: 'lineTo',
  16862. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16863. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16864. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16865. ARC: 'arc', // Circle
  16866. ELLIPSE: 'ellipse'
  16867. };
  16868. // TODO Clean up PATH API
  16869. // Create path using straight lines to connect all points
  16870. // - vectors: array of Vector2
  16871. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16872. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16873. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16874. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16875. };
  16876. };
  16877. // startPath() endPath()?
  16878. THREE.Path.prototype.moveTo = function ( x, y ) {
  16879. var args = Array.prototype.slice.call( arguments );
  16880. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16881. };
  16882. THREE.Path.prototype.lineTo = function ( x, y ) {
  16883. var args = Array.prototype.slice.call( arguments );
  16884. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16885. var x0 = lastargs[ lastargs.length - 2 ];
  16886. var y0 = lastargs[ lastargs.length - 1 ];
  16887. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16888. this.curves.push( curve );
  16889. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16890. };
  16891. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16892. var args = Array.prototype.slice.call( arguments );
  16893. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16894. var x0 = lastargs[ lastargs.length - 2 ];
  16895. var y0 = lastargs[ lastargs.length - 1 ];
  16896. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16897. new THREE.Vector2( aCPx, aCPy ),
  16898. new THREE.Vector2( aX, aY ) );
  16899. this.curves.push( curve );
  16900. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16901. };
  16902. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16903. aCP2x, aCP2y,
  16904. aX, aY ) {
  16905. var args = Array.prototype.slice.call( arguments );
  16906. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16907. var x0 = lastargs[ lastargs.length - 2 ];
  16908. var y0 = lastargs[ lastargs.length - 1 ];
  16909. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16910. new THREE.Vector2( aCP1x, aCP1y ),
  16911. new THREE.Vector2( aCP2x, aCP2y ),
  16912. new THREE.Vector2( aX, aY ) );
  16913. this.curves.push( curve );
  16914. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16915. };
  16916. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16917. var args = Array.prototype.slice.call( arguments );
  16918. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16919. var x0 = lastargs[ lastargs.length - 2 ];
  16920. var y0 = lastargs[ lastargs.length - 1 ];
  16921. //---
  16922. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16923. Array.prototype.push.apply( npts, pts );
  16924. var curve = new THREE.SplineCurve( npts );
  16925. this.curves.push( curve );
  16926. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16927. };
  16928. // FUTURE: Change the API or follow canvas API?
  16929. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16930. aStartAngle, aEndAngle, aClockwise ) {
  16931. var lastargs = this.actions[ this.actions.length - 1].args;
  16932. var x0 = lastargs[ lastargs.length - 2 ];
  16933. var y0 = lastargs[ lastargs.length - 1 ];
  16934. this.absarc(aX + x0, aY + y0, aRadius,
  16935. aStartAngle, aEndAngle, aClockwise );
  16936. };
  16937. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16938. aStartAngle, aEndAngle, aClockwise ) {
  16939. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16940. };
  16941. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16942. aStartAngle, aEndAngle, aClockwise ) {
  16943. var lastargs = this.actions[ this.actions.length - 1].args;
  16944. var x0 = lastargs[ lastargs.length - 2 ];
  16945. var y0 = lastargs[ lastargs.length - 1 ];
  16946. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16947. aStartAngle, aEndAngle, aClockwise );
  16948. };
  16949. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16950. aStartAngle, aEndAngle, aClockwise ) {
  16951. var args = Array.prototype.slice.call( arguments );
  16952. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16953. aStartAngle, aEndAngle, aClockwise );
  16954. this.curves.push( curve );
  16955. var lastPoint = curve.getPoint(1);
  16956. args.push(lastPoint.x);
  16957. args.push(lastPoint.y);
  16958. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16959. };
  16960. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16961. if ( ! divisions ) divisions = 40;
  16962. var points = [];
  16963. for ( var i = 0; i < divisions; i ++ ) {
  16964. points.push( this.getPoint( i / divisions ) );
  16965. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16966. }
  16967. // if ( closedPath ) {
  16968. //
  16969. // points.push( points[ 0 ] );
  16970. //
  16971. // }
  16972. return points;
  16973. };
  16974. /* Return an array of vectors based on contour of the path */
  16975. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16976. if (this.useSpacedPoints) {
  16977. console.log('tata');
  16978. return this.getSpacedPoints( divisions, closedPath );
  16979. }
  16980. divisions = divisions || 12;
  16981. var points = [];
  16982. var i, il, item, action, args;
  16983. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16984. laste, j,
  16985. t, tx, ty;
  16986. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16987. item = this.actions[ i ];
  16988. action = item.action;
  16989. args = item.args;
  16990. switch( action ) {
  16991. case THREE.PathActions.MOVE_TO:
  16992. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16993. break;
  16994. case THREE.PathActions.LINE_TO:
  16995. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16996. break;
  16997. case THREE.PathActions.QUADRATIC_CURVE_TO:
  16998. cpx = args[ 2 ];
  16999. cpy = args[ 3 ];
  17000. cpx1 = args[ 0 ];
  17001. cpy1 = args[ 1 ];
  17002. if ( points.length > 0 ) {
  17003. laste = points[ points.length - 1 ];
  17004. cpx0 = laste.x;
  17005. cpy0 = laste.y;
  17006. } else {
  17007. laste = this.actions[ i - 1 ].args;
  17008. cpx0 = laste[ laste.length - 2 ];
  17009. cpy0 = laste[ laste.length - 1 ];
  17010. }
  17011. for ( j = 1; j <= divisions; j ++ ) {
  17012. t = j / divisions;
  17013. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17014. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17015. points.push( new THREE.Vector2( tx, ty ) );
  17016. }
  17017. break;
  17018. case THREE.PathActions.BEZIER_CURVE_TO:
  17019. cpx = args[ 4 ];
  17020. cpy = args[ 5 ];
  17021. cpx1 = args[ 0 ];
  17022. cpy1 = args[ 1 ];
  17023. cpx2 = args[ 2 ];
  17024. cpy2 = args[ 3 ];
  17025. if ( points.length > 0 ) {
  17026. laste = points[ points.length - 1 ];
  17027. cpx0 = laste.x;
  17028. cpy0 = laste.y;
  17029. } else {
  17030. laste = this.actions[ i - 1 ].args;
  17031. cpx0 = laste[ laste.length - 2 ];
  17032. cpy0 = laste[ laste.length - 1 ];
  17033. }
  17034. for ( j = 1; j <= divisions; j ++ ) {
  17035. t = j / divisions;
  17036. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17037. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17038. points.push( new THREE.Vector2( tx, ty ) );
  17039. }
  17040. break;
  17041. case THREE.PathActions.CSPLINE_THRU:
  17042. laste = this.actions[ i - 1 ].args;
  17043. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17044. var spts = [ last ];
  17045. var n = divisions * args[ 0 ].length;
  17046. spts = spts.concat( args[ 0 ] );
  17047. var spline = new THREE.SplineCurve( spts );
  17048. for ( j = 1; j <= n; j ++ ) {
  17049. points.push( spline.getPointAt( j / n ) ) ;
  17050. }
  17051. break;
  17052. case THREE.PathActions.ARC:
  17053. var aX = args[ 0 ], aY = args[ 1 ],
  17054. aRadius = args[ 2 ],
  17055. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17056. aClockwise = !!args[ 5 ];
  17057. var deltaAngle = aEndAngle - aStartAngle;
  17058. var angle;
  17059. var tdivisions = divisions * 2;
  17060. for ( j = 1; j <= tdivisions; j ++ ) {
  17061. t = j / tdivisions;
  17062. if ( ! aClockwise ) {
  17063. t = 1 - t;
  17064. }
  17065. angle = aStartAngle + t * deltaAngle;
  17066. tx = aX + aRadius * Math.cos( angle );
  17067. ty = aY + aRadius * Math.sin( angle );
  17068. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17069. points.push( new THREE.Vector2( tx, ty ) );
  17070. }
  17071. //console.log(points);
  17072. break;
  17073. case THREE.PathActions.ELLIPSE:
  17074. var aX = args[ 0 ], aY = args[ 1 ],
  17075. xRadius = args[ 2 ],
  17076. yRadius = args[ 3 ],
  17077. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17078. aClockwise = !!args[ 6 ];
  17079. var deltaAngle = aEndAngle - aStartAngle;
  17080. var angle;
  17081. var tdivisions = divisions * 2;
  17082. for ( j = 1; j <= tdivisions; j ++ ) {
  17083. t = j / tdivisions;
  17084. if ( ! aClockwise ) {
  17085. t = 1 - t;
  17086. }
  17087. angle = aStartAngle + t * deltaAngle;
  17088. tx = aX + xRadius * Math.cos( angle );
  17089. ty = aY + yRadius * Math.sin( angle );
  17090. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17091. points.push( new THREE.Vector2( tx, ty ) );
  17092. }
  17093. //console.log(points);
  17094. break;
  17095. } // end switch
  17096. }
  17097. // Normalize to remove the closing point by default.
  17098. var lastPoint = points[ points.length - 1];
  17099. var EPSILON = 0.0000000001;
  17100. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17101. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17102. points.splice( points.length - 1, 1);
  17103. if ( closedPath ) {
  17104. points.push( points[ 0 ] );
  17105. }
  17106. return points;
  17107. };
  17108. // Breaks path into shapes
  17109. THREE.Path.prototype.toShapes = function( isCCW ) {
  17110. var i, il, item, action, args;
  17111. var subPaths = [], lastPath = new THREE.Path();
  17112. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17113. item = this.actions[ i ];
  17114. args = item.args;
  17115. action = item.action;
  17116. if ( action == THREE.PathActions.MOVE_TO ) {
  17117. if ( lastPath.actions.length != 0 ) {
  17118. subPaths.push( lastPath );
  17119. lastPath = new THREE.Path();
  17120. }
  17121. }
  17122. lastPath[ action ].apply( lastPath, args );
  17123. }
  17124. if ( lastPath.actions.length != 0 ) {
  17125. subPaths.push( lastPath );
  17126. }
  17127. // console.log(subPaths);
  17128. if ( subPaths.length == 0 ) return [];
  17129. var solid, tmpPath, tmpShape, shapes = [];
  17130. if ( subPaths.length == 1) {
  17131. tmpPath = subPaths[0];
  17132. tmpShape = new THREE.Shape();
  17133. tmpShape.actions = tmpPath.actions;
  17134. tmpShape.curves = tmpPath.curves;
  17135. shapes.push( tmpShape );
  17136. return shapes;
  17137. }
  17138. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17139. holesFirst = isCCW ? !holesFirst : holesFirst;
  17140. // console.log("Holes first", holesFirst);
  17141. if ( holesFirst ) {
  17142. tmpShape = new THREE.Shape();
  17143. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17144. tmpPath = subPaths[ i ];
  17145. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17146. solid = isCCW ? !solid : solid;
  17147. if ( solid ) {
  17148. tmpShape.actions = tmpPath.actions;
  17149. tmpShape.curves = tmpPath.curves;
  17150. shapes.push( tmpShape );
  17151. tmpShape = new THREE.Shape();
  17152. //console.log('cw', i);
  17153. } else {
  17154. tmpShape.holes.push( tmpPath );
  17155. //console.log('ccw', i);
  17156. }
  17157. }
  17158. } else {
  17159. // Shapes first
  17160. tmpShape = undefined;
  17161. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17162. tmpPath = subPaths[ i ];
  17163. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17164. solid = isCCW ? !solid : solid;
  17165. if ( solid ) {
  17166. if ( tmpShape ) shapes.push( tmpShape );
  17167. tmpShape = new THREE.Shape();
  17168. tmpShape.actions = tmpPath.actions;
  17169. tmpShape.curves = tmpPath.curves;
  17170. } else {
  17171. tmpShape.holes.push( tmpPath );
  17172. }
  17173. }
  17174. shapes.push( tmpShape );
  17175. }
  17176. //console.log("shape", shapes);
  17177. return shapes;
  17178. };
  17179. /**
  17180. * @author zz85 / http://www.lab4games.net/zz85/blog
  17181. * Defines a 2d shape plane using paths.
  17182. **/
  17183. // STEP 1 Create a path.
  17184. // STEP 2 Turn path into shape.
  17185. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17186. // STEP 3a - Extract points from each shape, turn to vertices
  17187. // STEP 3b - Triangulate each shape, add faces.
  17188. THREE.Shape = function () {
  17189. THREE.Path.apply( this, arguments );
  17190. this.holes = [];
  17191. };
  17192. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17193. // Convenience method to return ExtrudeGeometry
  17194. THREE.Shape.prototype.extrude = function ( options ) {
  17195. var extruded = new THREE.ExtrudeGeometry( this, options );
  17196. return extruded;
  17197. };
  17198. // Convenience method to return ShapeGeometry
  17199. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17200. var geometry = new THREE.ShapeGeometry( this, options );
  17201. return geometry;
  17202. };
  17203. // Get points of holes
  17204. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17205. var i, il = this.holes.length, holesPts = [];
  17206. for ( i = 0; i < il; i ++ ) {
  17207. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17208. }
  17209. return holesPts;
  17210. };
  17211. // Get points of holes (spaced by regular distance)
  17212. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17213. var i, il = this.holes.length, holesPts = [];
  17214. for ( i = 0; i < il; i ++ ) {
  17215. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17216. }
  17217. return holesPts;
  17218. };
  17219. // Get points of shape and holes (keypoints based on segments parameter)
  17220. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17221. return {
  17222. shape: this.getTransformedPoints( divisions ),
  17223. holes: this.getPointsHoles( divisions )
  17224. };
  17225. };
  17226. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17227. if (this.useSpacedPoints) {
  17228. return this.extractAllSpacedPoints(divisions);
  17229. }
  17230. return this.extractAllPoints(divisions);
  17231. };
  17232. //
  17233. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17234. //
  17235. // return {
  17236. //
  17237. // shape: this.transform( bend, divisions ),
  17238. // holes: this.getPointsHoles( divisions, bend )
  17239. //
  17240. // };
  17241. //
  17242. // };
  17243. // Get points of shape and holes (spaced by regular distance)
  17244. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17245. return {
  17246. shape: this.getTransformedSpacedPoints( divisions ),
  17247. holes: this.getSpacedPointsHoles( divisions )
  17248. };
  17249. };
  17250. /**************************************************************
  17251. * Utils
  17252. **************************************************************/
  17253. THREE.Shape.Utils = {
  17254. /*
  17255. contour - array of vector2 for contour
  17256. holes - array of array of vector2
  17257. */
  17258. removeHoles: function ( contour, holes ) {
  17259. var shape = contour.concat(); // work on this shape
  17260. var allpoints = shape.concat();
  17261. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17262. var prevShapeVert, nextShapeVert,
  17263. prevHoleVert, nextHoleVert,
  17264. holeIndex, shapeIndex,
  17265. shapeId, shapeGroup,
  17266. h, h2,
  17267. hole, shortest, d,
  17268. p, pts1, pts2,
  17269. tmpShape1, tmpShape2,
  17270. tmpHole1, tmpHole2,
  17271. verts = [];
  17272. for ( h = 0; h < holes.length; h ++ ) {
  17273. hole = holes[ h ];
  17274. /*
  17275. shapeholes[ h ].concat(); // preserves original
  17276. holes.push( hole );
  17277. */
  17278. Array.prototype.push.apply( allpoints, hole );
  17279. shortest = Number.POSITIVE_INFINITY;
  17280. // Find the shortest pair of pts between shape and hole
  17281. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17282. // Using distanceToSquared() intead of distanceTo() should speed a little
  17283. // since running square roots operations are reduced.
  17284. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17285. pts1 = hole[ h2 ];
  17286. var dist = [];
  17287. for ( p = 0; p < shape.length; p++ ) {
  17288. pts2 = shape[ p ];
  17289. d = pts1.distanceToSquared( pts2 );
  17290. dist.push( d );
  17291. if ( d < shortest ) {
  17292. shortest = d;
  17293. holeIndex = h2;
  17294. shapeIndex = p;
  17295. }
  17296. }
  17297. }
  17298. //console.log("shortest", shortest, dist);
  17299. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17300. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17301. var areaapts = [
  17302. hole[ holeIndex ],
  17303. shape[ shapeIndex ],
  17304. shape[ prevShapeVert ]
  17305. ];
  17306. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17307. var areabpts = [
  17308. hole[ holeIndex ],
  17309. hole[ prevHoleVert ],
  17310. shape[ shapeIndex ]
  17311. ];
  17312. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17313. var shapeOffset = 1;
  17314. var holeOffset = -1;
  17315. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17316. shapeIndex += shapeOffset;
  17317. holeIndex += holeOffset;
  17318. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17319. shapeIndex %= shape.length;
  17320. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17321. holeIndex %= hole.length;
  17322. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17323. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17324. areaapts = [
  17325. hole[ holeIndex ],
  17326. shape[ shapeIndex ],
  17327. shape[ prevShapeVert ]
  17328. ];
  17329. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17330. areabpts = [
  17331. hole[ holeIndex ],
  17332. hole[ prevHoleVert ],
  17333. shape[ shapeIndex ]
  17334. ];
  17335. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17336. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17337. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17338. // In case areas are not correct.
  17339. //console.log("USE THIS");
  17340. shapeIndex = oldShapeIndex;
  17341. holeIndex = oldHoleIndex ;
  17342. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17343. shapeIndex %= shape.length;
  17344. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17345. holeIndex %= hole.length;
  17346. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17347. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17348. } else {
  17349. //console.log("USE THAT ")
  17350. }
  17351. tmpShape1 = shape.slice( 0, shapeIndex );
  17352. tmpShape2 = shape.slice( shapeIndex );
  17353. tmpHole1 = hole.slice( holeIndex );
  17354. tmpHole2 = hole.slice( 0, holeIndex );
  17355. // Should check orders here again?
  17356. var trianglea = [
  17357. hole[ holeIndex ],
  17358. shape[ shapeIndex ],
  17359. shape[ prevShapeVert ]
  17360. ];
  17361. var triangleb = [
  17362. hole[ holeIndex ] ,
  17363. hole[ prevHoleVert ],
  17364. shape[ shapeIndex ]
  17365. ];
  17366. verts.push( trianglea );
  17367. verts.push( triangleb );
  17368. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17369. }
  17370. return {
  17371. shape:shape, /* shape with no holes */
  17372. isolatedPts: verts, /* isolated faces */
  17373. allpoints: allpoints
  17374. }
  17375. },
  17376. triangulateShape: function ( contour, holes ) {
  17377. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17378. var shape = shapeWithoutHoles.shape,
  17379. allpoints = shapeWithoutHoles.allpoints,
  17380. isolatedPts = shapeWithoutHoles.isolatedPts;
  17381. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17382. // 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.
  17383. //console.log( "triangles",triangles, triangles.length );
  17384. //console.log( "allpoints",allpoints, allpoints.length );
  17385. var i, il, f, face,
  17386. key, index,
  17387. allPointsMap = {},
  17388. isolatedPointsMap = {};
  17389. // prepare all points map
  17390. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17391. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17392. if ( allPointsMap[ key ] !== undefined ) {
  17393. console.log( "Duplicate point", key );
  17394. }
  17395. allPointsMap[ key ] = i;
  17396. }
  17397. // check all face vertices against all points map
  17398. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17399. face = triangles[ i ];
  17400. for ( f = 0; f < 3; f ++ ) {
  17401. key = face[ f ].x + ":" + face[ f ].y;
  17402. index = allPointsMap[ key ];
  17403. if ( index !== undefined ) {
  17404. face[ f ] = index;
  17405. }
  17406. }
  17407. }
  17408. // check isolated points vertices against all points map
  17409. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17410. face = isolatedPts[ i ];
  17411. for ( f = 0; f < 3; f ++ ) {
  17412. key = face[ f ].x + ":" + face[ f ].y;
  17413. index = allPointsMap[ key ];
  17414. if ( index !== undefined ) {
  17415. face[ f ] = index;
  17416. }
  17417. }
  17418. }
  17419. return triangles.concat( isolatedPts );
  17420. }, // end triangulate shapes
  17421. /*
  17422. triangulate2 : function( pts, holes ) {
  17423. // For use with Poly2Tri.js
  17424. var allpts = pts.concat();
  17425. var shape = [];
  17426. for (var p in pts) {
  17427. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17428. }
  17429. var swctx = new js.poly2tri.SweepContext(shape);
  17430. for (var h in holes) {
  17431. var aHole = holes[h];
  17432. var newHole = []
  17433. for (i in aHole) {
  17434. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17435. allpts.push(aHole[i]);
  17436. }
  17437. swctx.AddHole(newHole);
  17438. }
  17439. var find;
  17440. var findIndexForPt = function (pt) {
  17441. find = new THREE.Vector2(pt.x, pt.y);
  17442. var p;
  17443. for (p=0, pl = allpts.length; p<pl; p++) {
  17444. if (allpts[p].equals(find)) return p;
  17445. }
  17446. return -1;
  17447. };
  17448. // triangulate
  17449. js.poly2tri.sweep.Triangulate(swctx);
  17450. var triangles = swctx.GetTriangles();
  17451. var tr ;
  17452. var facesPts = [];
  17453. for (var t in triangles) {
  17454. tr = triangles[t];
  17455. facesPts.push([
  17456. findIndexForPt(tr.GetPoint(0)),
  17457. findIndexForPt(tr.GetPoint(1)),
  17458. findIndexForPt(tr.GetPoint(2))
  17459. ]);
  17460. }
  17461. // console.log(facesPts);
  17462. // console.log("triangles", triangles.length, triangles);
  17463. // Returns array of faces with 3 element each
  17464. return facesPts;
  17465. },
  17466. */
  17467. isClockWise: function ( pts ) {
  17468. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17469. },
  17470. // Bezier Curves formulas obtained from
  17471. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17472. // Quad Bezier Functions
  17473. b2p0: function ( t, p ) {
  17474. var k = 1 - t;
  17475. return k * k * p;
  17476. },
  17477. b2p1: function ( t, p ) {
  17478. return 2 * ( 1 - t ) * t * p;
  17479. },
  17480. b2p2: function ( t, p ) {
  17481. return t * t * p;
  17482. },
  17483. b2: function ( t, p0, p1, p2 ) {
  17484. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17485. },
  17486. // Cubic Bezier Functions
  17487. b3p0: function ( t, p ) {
  17488. var k = 1 - t;
  17489. return k * k * k * p;
  17490. },
  17491. b3p1: function ( t, p ) {
  17492. var k = 1 - t;
  17493. return 3 * k * k * t * p;
  17494. },
  17495. b3p2: function ( t, p ) {
  17496. var k = 1 - t;
  17497. return 3 * k * t * t * p;
  17498. },
  17499. b3p3: function ( t, p ) {
  17500. return t * t * t * p;
  17501. },
  17502. b3: function ( t, p0, p1, p2, p3 ) {
  17503. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17504. }
  17505. };
  17506. /**************************************************************
  17507. * Line
  17508. **************************************************************/
  17509. THREE.LineCurve = function ( v1, v2 ) {
  17510. this.v1 = v1;
  17511. this.v2 = v2;
  17512. };
  17513. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17514. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17515. var point = this.v2.clone().sub(this.v1);
  17516. point.multiplyScalar( t ).add( this.v1 );
  17517. return point;
  17518. };
  17519. // Line curve is linear, so we can overwrite default getPointAt
  17520. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17521. return this.getPoint( u );
  17522. };
  17523. THREE.LineCurve.prototype.getTangent = function( t ) {
  17524. var tangent = this.v2.clone().sub(this.v1);
  17525. return tangent.normalize();
  17526. };
  17527. /**************************************************************
  17528. * Quadratic Bezier curve
  17529. **************************************************************/
  17530. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17531. this.v0 = v0;
  17532. this.v1 = v1;
  17533. this.v2 = v2;
  17534. };
  17535. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17536. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17537. var tx, ty;
  17538. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17539. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17540. return new THREE.Vector2( tx, ty );
  17541. };
  17542. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17543. var tx, ty;
  17544. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17545. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17546. // returns unit vector
  17547. var tangent = new THREE.Vector2( tx, ty );
  17548. tangent.normalize();
  17549. return tangent;
  17550. };
  17551. /**************************************************************
  17552. * Cubic Bezier curve
  17553. **************************************************************/
  17554. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17555. this.v0 = v0;
  17556. this.v1 = v1;
  17557. this.v2 = v2;
  17558. this.v3 = v3;
  17559. };
  17560. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17561. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  17562. var tx, ty;
  17563. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17564. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17565. return new THREE.Vector2( tx, ty );
  17566. };
  17567. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  17568. var tx, ty;
  17569. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17570. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17571. var tangent = new THREE.Vector2( tx, ty );
  17572. tangent.normalize();
  17573. return tangent;
  17574. };
  17575. /**************************************************************
  17576. * Spline curve
  17577. **************************************************************/
  17578. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  17579. this.points = (points == undefined) ? [] : points;
  17580. };
  17581. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  17582. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  17583. var v = new THREE.Vector2();
  17584. var c = [];
  17585. var points = this.points, point, intPoint, weight;
  17586. point = ( points.length - 1 ) * t;
  17587. intPoint = Math.floor( point );
  17588. weight = point - intPoint;
  17589. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17590. c[ 1 ] = intPoint;
  17591. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  17592. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  17593. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17594. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17595. return v;
  17596. };
  17597. /**************************************************************
  17598. * Ellipse curve
  17599. **************************************************************/
  17600. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  17601. this.aX = aX;
  17602. this.aY = aY;
  17603. this.xRadius = xRadius;
  17604. this.yRadius = yRadius;
  17605. this.aStartAngle = aStartAngle;
  17606. this.aEndAngle = aEndAngle;
  17607. this.aClockwise = aClockwise;
  17608. };
  17609. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  17610. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  17611. var angle;
  17612. var deltaAngle = this.aEndAngle - this.aStartAngle;
  17613. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  17614. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  17615. if ( this.aClockwise === true ) {
  17616. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  17617. } else {
  17618. angle = this.aStartAngle + t * deltaAngle;
  17619. }
  17620. var tx = this.aX + this.xRadius * Math.cos( angle );
  17621. var ty = this.aY + this.yRadius * Math.sin( angle );
  17622. return new THREE.Vector2( tx, ty );
  17623. };
  17624. /**************************************************************
  17625. * Arc curve
  17626. **************************************************************/
  17627. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17628. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  17629. };
  17630. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  17631. /**************************************************************
  17632. * Line3D
  17633. **************************************************************/
  17634. THREE.LineCurve3 = THREE.Curve.create(
  17635. function ( v1, v2 ) {
  17636. this.v1 = v1;
  17637. this.v2 = v2;
  17638. },
  17639. function ( t ) {
  17640. var r = new THREE.Vector3();
  17641. r.subVectors( this.v2, this.v1 ); // diff
  17642. r.multiplyScalar( t );
  17643. r.add( this.v1 );
  17644. return r;
  17645. }
  17646. );
  17647. /**************************************************************
  17648. * Quadratic Bezier 3D curve
  17649. **************************************************************/
  17650. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  17651. function ( v0, v1, v2 ) {
  17652. this.v0 = v0;
  17653. this.v1 = v1;
  17654. this.v2 = v2;
  17655. },
  17656. function ( t ) {
  17657. var tx, ty, tz;
  17658. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17659. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17660. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  17661. return new THREE.Vector3( tx, ty, tz );
  17662. }
  17663. );
  17664. /**************************************************************
  17665. * Cubic Bezier 3D curve
  17666. **************************************************************/
  17667. THREE.CubicBezierCurve3 = THREE.Curve.create(
  17668. function ( v0, v1, v2, v3 ) {
  17669. this.v0 = v0;
  17670. this.v1 = v1;
  17671. this.v2 = v2;
  17672. this.v3 = v3;
  17673. },
  17674. function ( t ) {
  17675. var tx, ty, tz;
  17676. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17677. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17678. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  17679. return new THREE.Vector3( tx, ty, tz );
  17680. }
  17681. );
  17682. /**************************************************************
  17683. * Spline 3D curve
  17684. **************************************************************/
  17685. THREE.SplineCurve3 = THREE.Curve.create(
  17686. function ( points /* array of Vector3 */) {
  17687. this.points = (points == undefined) ? [] : points;
  17688. },
  17689. function ( t ) {
  17690. var v = new THREE.Vector3();
  17691. var c = [];
  17692. var points = this.points, point, intPoint, weight;
  17693. point = ( points.length - 1 ) * t;
  17694. intPoint = Math.floor( point );
  17695. weight = point - intPoint;
  17696. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17697. c[ 1 ] = intPoint;
  17698. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17699. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17700. var pt0 = points[ c[0] ],
  17701. pt1 = points[ c[1] ],
  17702. pt2 = points[ c[2] ],
  17703. pt3 = points[ c[3] ];
  17704. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  17705. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  17706. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  17707. return v;
  17708. }
  17709. );
  17710. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  17711. // var v = new THREE.Vector3();
  17712. // var c = [];
  17713. // var points = this.points, point, intPoint, weight;
  17714. // point = ( points.length - 1 ) * t;
  17715. // intPoint = Math.floor( point );
  17716. // weight = point - intPoint;
  17717. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17718. // c[ 1 ] = intPoint;
  17719. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17720. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17721. // var pt0 = points[ c[0] ],
  17722. // pt1 = points[ c[1] ],
  17723. // pt2 = points[ c[2] ],
  17724. // pt3 = points[ c[3] ];
  17725. // // t = weight;
  17726. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  17727. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  17728. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  17729. // return v;
  17730. // }
  17731. /**************************************************************
  17732. * Closed Spline 3D curve
  17733. **************************************************************/
  17734. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  17735. function ( points /* array of Vector3 */) {
  17736. this.points = (points == undefined) ? [] : points;
  17737. },
  17738. function ( t ) {
  17739. var v = new THREE.Vector3();
  17740. var c = [];
  17741. var points = this.points, point, intPoint, weight;
  17742. point = ( points.length - 0 ) * t;
  17743. // This needs to be from 0-length +1
  17744. intPoint = Math.floor( point );
  17745. weight = point - intPoint;
  17746. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  17747. c[ 0 ] = ( intPoint - 1 ) % points.length;
  17748. c[ 1 ] = ( intPoint ) % points.length;
  17749. c[ 2 ] = ( intPoint + 1 ) % points.length;
  17750. c[ 3 ] = ( intPoint + 2 ) % points.length;
  17751. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17752. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17753. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  17754. return v;
  17755. }
  17756. );
  17757. /**
  17758. * @author mikael emtinger / http://gomo.se/
  17759. */
  17760. THREE.AnimationHandler = (function() {
  17761. var playing = [];
  17762. var library = {};
  17763. var that = {};
  17764. //--- update ---
  17765. that.update = function( deltaTimeMS ) {
  17766. for( var i = 0; i < playing.length; i ++ )
  17767. playing[ i ].update( deltaTimeMS );
  17768. };
  17769. //--- add ---
  17770. that.addToUpdate = function( animation ) {
  17771. if ( playing.indexOf( animation ) === -1 )
  17772. playing.push( animation );
  17773. };
  17774. //--- remove ---
  17775. that.removeFromUpdate = function( animation ) {
  17776. var index = playing.indexOf( animation );
  17777. if( index !== -1 )
  17778. playing.splice( index, 1 );
  17779. };
  17780. //--- add ---
  17781. that.add = function( data ) {
  17782. if ( library[ data.name ] !== undefined )
  17783. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17784. library[ data.name ] = data;
  17785. initData( data );
  17786. };
  17787. //--- get ---
  17788. that.get = function( name ) {
  17789. if ( typeof name === "string" ) {
  17790. if ( library[ name ] ) {
  17791. return library[ name ];
  17792. } else {
  17793. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17794. return null;
  17795. }
  17796. } else {
  17797. // todo: add simple tween library
  17798. }
  17799. };
  17800. //--- parse ---
  17801. that.parse = function( root ) {
  17802. // setup hierarchy
  17803. var hierarchy = [];
  17804. if ( root instanceof THREE.SkinnedMesh ) {
  17805. for( var b = 0; b < root.bones.length; b++ ) {
  17806. hierarchy.push( root.bones[ b ] );
  17807. }
  17808. } else {
  17809. parseRecurseHierarchy( root, hierarchy );
  17810. }
  17811. return hierarchy;
  17812. };
  17813. var parseRecurseHierarchy = function( root, hierarchy ) {
  17814. hierarchy.push( root );
  17815. for( var c = 0; c < root.children.length; c++ )
  17816. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17817. }
  17818. //--- init data ---
  17819. var initData = function( data ) {
  17820. if( data.initialized === true )
  17821. return;
  17822. // loop through all keys
  17823. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17824. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17825. // remove minus times
  17826. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17827. data.hierarchy[ h ].keys[ k ].time = 0;
  17828. // create quaternions
  17829. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17830. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17831. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17832. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17833. }
  17834. }
  17835. // prepare morph target keys
  17836. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17837. // get all used
  17838. var usedMorphTargets = {};
  17839. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17840. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17841. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17842. usedMorphTargets[ morphTargetName ] = -1;
  17843. }
  17844. }
  17845. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17846. // set all used on all frames
  17847. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17848. var influences = {};
  17849. for ( var morphTargetName in usedMorphTargets ) {
  17850. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17851. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17852. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17853. break;
  17854. }
  17855. }
  17856. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17857. influences[ morphTargetName ] = 0;
  17858. }
  17859. }
  17860. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17861. }
  17862. }
  17863. // remove all keys that are on the same time
  17864. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17865. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17866. data.hierarchy[ h ].keys.splice( k, 1 );
  17867. k --;
  17868. }
  17869. }
  17870. // set index
  17871. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17872. data.hierarchy[ h ].keys[ k ].index = k;
  17873. }
  17874. }
  17875. // JIT
  17876. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17877. data.JIT = {};
  17878. data.JIT.hierarchy = [];
  17879. for( var h = 0; h < data.hierarchy.length; h ++ )
  17880. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17881. // done
  17882. data.initialized = true;
  17883. };
  17884. // interpolation types
  17885. that.LINEAR = 0;
  17886. that.CATMULLROM = 1;
  17887. that.CATMULLROM_FORWARD = 2;
  17888. return that;
  17889. }());
  17890. /**
  17891. * @author mikael emtinger / http://gomo.se/
  17892. * @author mrdoob / http://mrdoob.com/
  17893. * @author alteredq / http://alteredqualia.com/
  17894. */
  17895. THREE.Animation = function ( root, name, interpolationType ) {
  17896. this.root = root;
  17897. this.data = THREE.AnimationHandler.get( name );
  17898. this.hierarchy = THREE.AnimationHandler.parse( root );
  17899. this.currentTime = 0;
  17900. this.timeScale = 1;
  17901. this.isPlaying = false;
  17902. this.isPaused = true;
  17903. this.loop = true;
  17904. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17905. this.points = [];
  17906. this.target = new THREE.Vector3();
  17907. };
  17908. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17909. if ( this.isPlaying === false ) {
  17910. this.isPlaying = true;
  17911. this.loop = loop !== undefined ? loop : true;
  17912. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17913. // reset key cache
  17914. var h, hl = this.hierarchy.length,
  17915. object;
  17916. for ( h = 0; h < hl; h ++ ) {
  17917. object = this.hierarchy[ h ];
  17918. object.matrixAutoUpdate = true;
  17919. if ( object.animationCache === undefined ) {
  17920. object.animationCache = {};
  17921. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17922. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17923. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17924. }
  17925. var prevKey = object.animationCache.prevKey;
  17926. var nextKey = object.animationCache.nextKey;
  17927. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17928. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17929. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17930. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17931. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17932. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17933. }
  17934. this.update( 0 );
  17935. }
  17936. this.isPaused = false;
  17937. THREE.AnimationHandler.addToUpdate( this );
  17938. };
  17939. THREE.Animation.prototype.pause = function() {
  17940. if ( this.isPaused === true ) {
  17941. THREE.AnimationHandler.addToUpdate( this );
  17942. } else {
  17943. THREE.AnimationHandler.removeFromUpdate( this );
  17944. }
  17945. this.isPaused = !this.isPaused;
  17946. };
  17947. THREE.Animation.prototype.stop = function() {
  17948. this.isPlaying = false;
  17949. this.isPaused = false;
  17950. THREE.AnimationHandler.removeFromUpdate( this );
  17951. };
  17952. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17953. // early out
  17954. if ( this.isPlaying === false ) return;
  17955. // vars
  17956. var types = [ "pos", "rot", "scl" ];
  17957. var type;
  17958. var scale;
  17959. var vector;
  17960. var prevXYZ, nextXYZ;
  17961. var prevKey, nextKey;
  17962. var object;
  17963. var animationCache;
  17964. var frame;
  17965. var JIThierarchy = this.data.JIT.hierarchy;
  17966. var currentTime, unloopedCurrentTime;
  17967. var currentPoint, forwardPoint, angle;
  17968. this.currentTime += deltaTimeMS * this.timeScale;
  17969. unloopedCurrentTime = this.currentTime;
  17970. currentTime = this.currentTime = this.currentTime % this.data.length;
  17971. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17972. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17973. object = this.hierarchy[ h ];
  17974. animationCache = object.animationCache;
  17975. // loop through pos/rot/scl
  17976. for ( var t = 0; t < 3; t ++ ) {
  17977. // get keys
  17978. type = types[ t ];
  17979. prevKey = animationCache.prevKey[ type ];
  17980. nextKey = animationCache.nextKey[ type ];
  17981. // switch keys?
  17982. if ( nextKey.time <= unloopedCurrentTime ) {
  17983. // did we loop?
  17984. if ( currentTime < unloopedCurrentTime ) {
  17985. if ( this.loop ) {
  17986. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17987. nextKey = this.getNextKeyWith( type, h, 1 );
  17988. while( nextKey.time < currentTime ) {
  17989. prevKey = nextKey;
  17990. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17991. }
  17992. } else {
  17993. this.stop();
  17994. return;
  17995. }
  17996. } else {
  17997. do {
  17998. prevKey = nextKey;
  17999. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18000. } while( nextKey.time < currentTime )
  18001. }
  18002. animationCache.prevKey[ type ] = prevKey;
  18003. animationCache.nextKey[ type ] = nextKey;
  18004. }
  18005. object.matrixAutoUpdate = true;
  18006. object.matrixWorldNeedsUpdate = true;
  18007. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18008. prevXYZ = prevKey[ type ];
  18009. nextXYZ = nextKey[ type ];
  18010. // check scale error
  18011. if ( scale < 0 || scale > 1 ) {
  18012. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  18013. scale = scale < 0 ? 0 : 1;
  18014. }
  18015. // interpolate
  18016. if ( type === "pos" ) {
  18017. vector = object.position;
  18018. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18019. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18020. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18021. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18022. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18023. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18024. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18025. this.points[ 1 ] = prevXYZ;
  18026. this.points[ 2 ] = nextXYZ;
  18027. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18028. scale = scale * 0.33 + 0.33;
  18029. currentPoint = this.interpolateCatmullRom( this.points, scale );
  18030. vector.x = currentPoint[ 0 ];
  18031. vector.y = currentPoint[ 1 ];
  18032. vector.z = currentPoint[ 2 ];
  18033. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18034. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  18035. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18036. this.target.sub( vector );
  18037. this.target.y = 0;
  18038. this.target.normalize();
  18039. angle = Math.atan2( this.target.x, this.target.z );
  18040. object.rotation.set( 0, angle, 0 );
  18041. }
  18042. }
  18043. } else if ( type === "rot" ) {
  18044. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18045. } else if ( type === "scl" ) {
  18046. vector = object.scale;
  18047. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18048. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18049. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18050. }
  18051. }
  18052. }
  18053. };
  18054. // Catmull-Rom spline
  18055. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  18056. var c = [], v3 = [],
  18057. point, intPoint, weight, w2, w3,
  18058. pa, pb, pc, pd;
  18059. point = ( points.length - 1 ) * scale;
  18060. intPoint = Math.floor( point );
  18061. weight = point - intPoint;
  18062. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18063. c[ 1 ] = intPoint;
  18064. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18065. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18066. pa = points[ c[ 0 ] ];
  18067. pb = points[ c[ 1 ] ];
  18068. pc = points[ c[ 2 ] ];
  18069. pd = points[ c[ 3 ] ];
  18070. w2 = weight * weight;
  18071. w3 = weight * w2;
  18072. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18073. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18074. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18075. return v3;
  18076. };
  18077. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18078. var v0 = ( p2 - p0 ) * 0.5,
  18079. v1 = ( p3 - p1 ) * 0.5;
  18080. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18081. };
  18082. // Get next key with
  18083. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18084. var keys = this.data.hierarchy[ h ].keys;
  18085. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18086. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18087. key = key < keys.length - 1 ? key : keys.length - 1;
  18088. } else {
  18089. key = key % keys.length;
  18090. }
  18091. for ( ; key < keys.length; key++ ) {
  18092. if ( keys[ key ][ type ] !== undefined ) {
  18093. return keys[ key ];
  18094. }
  18095. }
  18096. return this.data.hierarchy[ h ].keys[ 0 ];
  18097. };
  18098. // Get previous key with
  18099. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18100. var keys = this.data.hierarchy[ h ].keys;
  18101. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18102. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18103. key = key > 0 ? key : 0;
  18104. } else {
  18105. key = key >= 0 ? key : key + keys.length;
  18106. }
  18107. for ( ; key >= 0; key -- ) {
  18108. if ( keys[ key ][ type ] !== undefined ) {
  18109. return keys[ key ];
  18110. }
  18111. }
  18112. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18113. };
  18114. /**
  18115. * @author mikael emtinger / http://gomo.se/
  18116. * @author mrdoob / http://mrdoob.com/
  18117. * @author alteredq / http://alteredqualia.com/
  18118. * @author khang duong
  18119. * @author erik kitson
  18120. */
  18121. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  18122. this.root = root;
  18123. this.data = THREE.AnimationHandler.get( data );
  18124. this.hierarchy = THREE.AnimationHandler.parse( root );
  18125. this.currentTime = 0;
  18126. this.timeScale = 0.001;
  18127. this.isPlaying = false;
  18128. this.isPaused = true;
  18129. this.loop = true;
  18130. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  18131. // initialize to first keyframes
  18132. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18133. var keys = this.data.hierarchy[h].keys,
  18134. sids = this.data.hierarchy[h].sids,
  18135. obj = this.hierarchy[h];
  18136. if ( keys.length && sids ) {
  18137. for ( var s = 0; s < sids.length; s++ ) {
  18138. var sid = sids[ s ],
  18139. next = this.getNextKeyWith( sid, h, 0 );
  18140. if ( next ) {
  18141. next.apply( sid );
  18142. }
  18143. }
  18144. obj.matrixAutoUpdate = false;
  18145. this.data.hierarchy[h].node.updateMatrix();
  18146. obj.matrixWorldNeedsUpdate = true;
  18147. }
  18148. }
  18149. };
  18150. // Play
  18151. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18152. if( !this.isPlaying ) {
  18153. this.isPlaying = true;
  18154. this.loop = loop !== undefined ? loop : true;
  18155. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18156. this.startTimeMs = startTimeMS;
  18157. this.startTime = 10000000;
  18158. this.endTime = -this.startTime;
  18159. // reset key cache
  18160. var h, hl = this.hierarchy.length,
  18161. object,
  18162. node;
  18163. for ( h = 0; h < hl; h++ ) {
  18164. object = this.hierarchy[ h ];
  18165. node = this.data.hierarchy[ h ];
  18166. if ( node.animationCache === undefined ) {
  18167. node.animationCache = {};
  18168. node.animationCache.prevKey = null;
  18169. node.animationCache.nextKey = null;
  18170. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18171. }
  18172. var keys = this.data.hierarchy[h].keys;
  18173. if (keys.length) {
  18174. node.animationCache.prevKey = keys[ 0 ];
  18175. node.animationCache.nextKey = keys[ 1 ];
  18176. this.startTime = Math.min( keys[0].time, this.startTime );
  18177. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18178. }
  18179. }
  18180. this.update( 0 );
  18181. }
  18182. this.isPaused = false;
  18183. THREE.AnimationHandler.addToUpdate( this );
  18184. };
  18185. // Pause
  18186. THREE.KeyFrameAnimation.prototype.pause = function() {
  18187. if( this.isPaused ) {
  18188. THREE.AnimationHandler.addToUpdate( this );
  18189. } else {
  18190. THREE.AnimationHandler.removeFromUpdate( this );
  18191. }
  18192. this.isPaused = !this.isPaused;
  18193. };
  18194. // Stop
  18195. THREE.KeyFrameAnimation.prototype.stop = function() {
  18196. this.isPlaying = false;
  18197. this.isPaused = false;
  18198. THREE.AnimationHandler.removeFromUpdate( this );
  18199. // reset JIT matrix and remove cache
  18200. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18201. var obj = this.hierarchy[ h ];
  18202. var node = this.data.hierarchy[ h ];
  18203. if ( node.animationCache !== undefined ) {
  18204. var original = node.animationCache.originalMatrix;
  18205. if( obj instanceof THREE.Bone ) {
  18206. original.copy( obj.skinMatrix );
  18207. obj.skinMatrix = original;
  18208. } else {
  18209. original.copy( obj.matrix );
  18210. obj.matrix = original;
  18211. }
  18212. delete node.animationCache;
  18213. }
  18214. }
  18215. };
  18216. // Update
  18217. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18218. // early out
  18219. if( !this.isPlaying ) return;
  18220. // vars
  18221. var prevKey, nextKey;
  18222. var object;
  18223. var node;
  18224. var frame;
  18225. var JIThierarchy = this.data.JIT.hierarchy;
  18226. var currentTime, unloopedCurrentTime;
  18227. var looped;
  18228. // update
  18229. this.currentTime += deltaTimeMS * this.timeScale;
  18230. unloopedCurrentTime = this.currentTime;
  18231. currentTime = this.currentTime = this.currentTime % this.data.length;
  18232. // if looped around, the current time should be based on the startTime
  18233. if ( currentTime < this.startTimeMs ) {
  18234. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18235. }
  18236. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18237. looped = currentTime < unloopedCurrentTime;
  18238. if ( looped && !this.loop ) {
  18239. // Set the animation to the last keyframes and stop
  18240. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18241. var keys = this.data.hierarchy[h].keys,
  18242. sids = this.data.hierarchy[h].sids,
  18243. end = keys.length-1,
  18244. obj = this.hierarchy[h];
  18245. if ( keys.length ) {
  18246. for ( var s = 0; s < sids.length; s++ ) {
  18247. var sid = sids[ s ],
  18248. prev = this.getPrevKeyWith( sid, h, end );
  18249. if ( prev ) {
  18250. prev.apply( sid );
  18251. }
  18252. }
  18253. this.data.hierarchy[h].node.updateMatrix();
  18254. obj.matrixWorldNeedsUpdate = true;
  18255. }
  18256. }
  18257. this.stop();
  18258. return;
  18259. }
  18260. // check pre-infinity
  18261. if ( currentTime < this.startTime ) {
  18262. return;
  18263. }
  18264. // update
  18265. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18266. object = this.hierarchy[ h ];
  18267. node = this.data.hierarchy[ h ];
  18268. var keys = node.keys,
  18269. animationCache = node.animationCache;
  18270. // use JIT?
  18271. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18272. if( object instanceof THREE.Bone ) {
  18273. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18274. object.matrixWorldNeedsUpdate = false;
  18275. } else {
  18276. object.matrix = JIThierarchy[ h ][ frame ];
  18277. object.matrixWorldNeedsUpdate = true;
  18278. }
  18279. // use interpolation
  18280. } else if ( keys.length ) {
  18281. // make sure so original matrix and not JIT matrix is set
  18282. if ( this.JITCompile && animationCache ) {
  18283. if( object instanceof THREE.Bone ) {
  18284. object.skinMatrix = animationCache.originalMatrix;
  18285. } else {
  18286. object.matrix = animationCache.originalMatrix;
  18287. }
  18288. }
  18289. prevKey = animationCache.prevKey;
  18290. nextKey = animationCache.nextKey;
  18291. if ( prevKey && nextKey ) {
  18292. // switch keys?
  18293. if ( nextKey.time <= unloopedCurrentTime ) {
  18294. // did we loop?
  18295. if ( looped && this.loop ) {
  18296. prevKey = keys[ 0 ];
  18297. nextKey = keys[ 1 ];
  18298. while ( nextKey.time < currentTime ) {
  18299. prevKey = nextKey;
  18300. nextKey = keys[ prevKey.index + 1 ];
  18301. }
  18302. } else if ( !looped ) {
  18303. var lastIndex = keys.length - 1;
  18304. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18305. prevKey = nextKey;
  18306. nextKey = keys[ prevKey.index + 1 ];
  18307. }
  18308. }
  18309. animationCache.prevKey = prevKey;
  18310. animationCache.nextKey = nextKey;
  18311. }
  18312. if(nextKey.time >= currentTime)
  18313. prevKey.interpolate( nextKey, currentTime );
  18314. else
  18315. prevKey.interpolate( nextKey, nextKey.time);
  18316. }
  18317. this.data.hierarchy[h].node.updateMatrix();
  18318. object.matrixWorldNeedsUpdate = true;
  18319. }
  18320. }
  18321. // update JIT?
  18322. if ( this.JITCompile ) {
  18323. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18324. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18325. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18326. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18327. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18328. } else {
  18329. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18330. }
  18331. }
  18332. }
  18333. }
  18334. };
  18335. // Get next key with
  18336. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18337. var keys = this.data.hierarchy[ h ].keys;
  18338. key = key % keys.length;
  18339. for ( ; key < keys.length; key++ ) {
  18340. if ( keys[ key ].hasTarget( sid ) ) {
  18341. return keys[ key ];
  18342. }
  18343. }
  18344. return keys[ 0 ];
  18345. };
  18346. // Get previous key with
  18347. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18348. var keys = this.data.hierarchy[ h ].keys;
  18349. key = key >= 0 ? key : key + keys.length;
  18350. for ( ; key >= 0; key-- ) {
  18351. if ( keys[ key ].hasTarget( sid ) ) {
  18352. return keys[ key ];
  18353. }
  18354. }
  18355. return keys[ keys.length - 1 ];
  18356. };
  18357. /**
  18358. * Camera for rendering cube maps
  18359. * - renders scene into axis-aligned cube
  18360. *
  18361. * @author alteredq / http://alteredqualia.com/
  18362. */
  18363. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18364. THREE.Object3D.call( this );
  18365. var fov = 90, aspect = 1;
  18366. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18367. cameraPX.up.set( 0, -1, 0 );
  18368. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18369. this.add( cameraPX );
  18370. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18371. cameraNX.up.set( 0, -1, 0 );
  18372. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18373. this.add( cameraNX );
  18374. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18375. cameraPY.up.set( 0, 0, 1 );
  18376. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18377. this.add( cameraPY );
  18378. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18379. cameraNY.up.set( 0, 0, -1 );
  18380. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18381. this.add( cameraNY );
  18382. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18383. cameraPZ.up.set( 0, -1, 0 );
  18384. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18385. this.add( cameraPZ );
  18386. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18387. cameraNZ.up.set( 0, -1, 0 );
  18388. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18389. this.add( cameraNZ );
  18390. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18391. this.updateCubeMap = function ( renderer, scene ) {
  18392. var renderTarget = this.renderTarget;
  18393. var generateMipmaps = renderTarget.generateMipmaps;
  18394. renderTarget.generateMipmaps = false;
  18395. renderTarget.activeCubeFace = 0;
  18396. renderer.render( scene, cameraPX, renderTarget );
  18397. renderTarget.activeCubeFace = 1;
  18398. renderer.render( scene, cameraNX, renderTarget );
  18399. renderTarget.activeCubeFace = 2;
  18400. renderer.render( scene, cameraPY, renderTarget );
  18401. renderTarget.activeCubeFace = 3;
  18402. renderer.render( scene, cameraNY, renderTarget );
  18403. renderTarget.activeCubeFace = 4;
  18404. renderer.render( scene, cameraPZ, renderTarget );
  18405. renderTarget.generateMipmaps = generateMipmaps;
  18406. renderTarget.activeCubeFace = 5;
  18407. renderer.render( scene, cameraNZ, renderTarget );
  18408. };
  18409. };
  18410. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18411. /*
  18412. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18413. *
  18414. * A general perpose camera, for setting FOV, Lens Focal Length,
  18415. * and switching between perspective and orthographic views easily.
  18416. * Use this only if you do not wish to manage
  18417. * both a Orthographic and Perspective Camera
  18418. *
  18419. */
  18420. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18421. THREE.Camera.call( this );
  18422. this.fov = fov;
  18423. this.left = -width / 2;
  18424. this.right = width / 2
  18425. this.top = height / 2;
  18426. this.bottom = -height / 2;
  18427. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18428. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18429. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18430. this.zoom = 1;
  18431. this.toPerspective();
  18432. var aspect = width/height;
  18433. };
  18434. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18435. THREE.CombinedCamera.prototype.toPerspective = function () {
  18436. // Switches to the Perspective Camera
  18437. this.near = this.cameraP.near;
  18438. this.far = this.cameraP.far;
  18439. this.cameraP.fov = this.fov / this.zoom ;
  18440. this.cameraP.updateProjectionMatrix();
  18441. this.projectionMatrix = this.cameraP.projectionMatrix;
  18442. this.inPerspectiveMode = true;
  18443. this.inOrthographicMode = false;
  18444. };
  18445. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18446. // Switches to the Orthographic camera estimating viewport from Perspective
  18447. var fov = this.fov;
  18448. var aspect = this.cameraP.aspect;
  18449. var near = this.cameraP.near;
  18450. var far = this.cameraP.far;
  18451. // The size that we set is the mid plane of the viewing frustum
  18452. var hyperfocus = ( near + far ) / 2;
  18453. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18454. var planeHeight = 2 * halfHeight;
  18455. var planeWidth = planeHeight * aspect;
  18456. var halfWidth = planeWidth / 2;
  18457. halfHeight /= this.zoom;
  18458. halfWidth /= this.zoom;
  18459. this.cameraO.left = -halfWidth;
  18460. this.cameraO.right = halfWidth;
  18461. this.cameraO.top = halfHeight;
  18462. this.cameraO.bottom = -halfHeight;
  18463. // this.cameraO.left = -farHalfWidth;
  18464. // this.cameraO.right = farHalfWidth;
  18465. // this.cameraO.top = farHalfHeight;
  18466. // this.cameraO.bottom = -farHalfHeight;
  18467. // this.cameraO.left = this.left / this.zoom;
  18468. // this.cameraO.right = this.right / this.zoom;
  18469. // this.cameraO.top = this.top / this.zoom;
  18470. // this.cameraO.bottom = this.bottom / this.zoom;
  18471. this.cameraO.updateProjectionMatrix();
  18472. this.near = this.cameraO.near;
  18473. this.far = this.cameraO.far;
  18474. this.projectionMatrix = this.cameraO.projectionMatrix;
  18475. this.inPerspectiveMode = false;
  18476. this.inOrthographicMode = true;
  18477. };
  18478. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18479. this.cameraP.aspect = width / height;
  18480. this.left = -width / 2;
  18481. this.right = width / 2
  18482. this.top = height / 2;
  18483. this.bottom = -height / 2;
  18484. };
  18485. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18486. this.fov = fov;
  18487. if ( this.inPerspectiveMode ) {
  18488. this.toPerspective();
  18489. } else {
  18490. this.toOrthographic();
  18491. }
  18492. };
  18493. // For mantaining similar API with PerspectiveCamera
  18494. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18495. if ( this.inPerspectiveMode ) {
  18496. this.toPerspective();
  18497. } else {
  18498. this.toPerspective();
  18499. this.toOrthographic();
  18500. }
  18501. };
  18502. /*
  18503. * Uses Focal Length (in mm) to estimate and set FOV
  18504. * 35mm (fullframe) camera is used if frame size is not specified;
  18505. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18506. */
  18507. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18508. if ( frameHeight === undefined ) frameHeight = 24;
  18509. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18510. this.setFov( fov );
  18511. return fov;
  18512. };
  18513. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18514. this.zoom = zoom;
  18515. if ( this.inPerspectiveMode ) {
  18516. this.toPerspective();
  18517. } else {
  18518. this.toOrthographic();
  18519. }
  18520. };
  18521. THREE.CombinedCamera.prototype.toFrontView = function() {
  18522. this.rotation.x = 0;
  18523. this.rotation.y = 0;
  18524. this.rotation.z = 0;
  18525. // should we be modifing the matrix instead?
  18526. this.rotationAutoUpdate = false;
  18527. };
  18528. THREE.CombinedCamera.prototype.toBackView = function() {
  18529. this.rotation.x = 0;
  18530. this.rotation.y = Math.PI;
  18531. this.rotation.z = 0;
  18532. this.rotationAutoUpdate = false;
  18533. };
  18534. THREE.CombinedCamera.prototype.toLeftView = function() {
  18535. this.rotation.x = 0;
  18536. this.rotation.y = - Math.PI / 2;
  18537. this.rotation.z = 0;
  18538. this.rotationAutoUpdate = false;
  18539. };
  18540. THREE.CombinedCamera.prototype.toRightView = function() {
  18541. this.rotation.x = 0;
  18542. this.rotation.y = Math.PI / 2;
  18543. this.rotation.z = 0;
  18544. this.rotationAutoUpdate = false;
  18545. };
  18546. THREE.CombinedCamera.prototype.toTopView = function() {
  18547. this.rotation.x = - Math.PI / 2;
  18548. this.rotation.y = 0;
  18549. this.rotation.z = 0;
  18550. this.rotationAutoUpdate = false;
  18551. };
  18552. THREE.CombinedCamera.prototype.toBottomView = function() {
  18553. this.rotation.x = Math.PI / 2;
  18554. this.rotation.y = 0;
  18555. this.rotation.z = 0;
  18556. this.rotationAutoUpdate = false;
  18557. };
  18558. /**
  18559. * @author hughes
  18560. */
  18561. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18562. THREE.Geometry.call( this );
  18563. this.radius = radius = radius || 50;
  18564. this.segments = segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18565. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18566. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18567. var i, uvs = [],
  18568. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18569. this.vertices.push(center);
  18570. uvs.push( centerUV );
  18571. for ( i = 0; i <= segments; i ++ ) {
  18572. var vertex = new THREE.Vector3();
  18573. var segment = thetaStart + i / segments * thetaLength;
  18574. vertex.x = radius * Math.cos( segment );
  18575. vertex.y = radius * Math.sin( segment );
  18576. this.vertices.push( vertex );
  18577. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  18578. }
  18579. var n = new THREE.Vector3( 0, 0, 1 );
  18580. for ( i = 1; i <= segments; i ++ ) {
  18581. var v1 = i;
  18582. var v2 = i + 1 ;
  18583. var v3 = 0;
  18584. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  18585. this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] );
  18586. }
  18587. this.computeCentroids();
  18588. this.computeFaceNormals();
  18589. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18590. };
  18591. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18592. /**
  18593. * @author mrdoob / http://mrdoob.com/
  18594. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18595. */
  18596. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18597. THREE.Geometry.call( this );
  18598. var scope = this;
  18599. this.width = width;
  18600. this.height = height;
  18601. this.depth = depth;
  18602. this.widthSegments = widthSegments || 1;
  18603. this.heightSegments = heightSegments || 1;
  18604. this.depthSegments = depthSegments || 1;
  18605. var width_half = this.width / 2;
  18606. var height_half = this.height / 2;
  18607. var depth_half = this.depth / 2;
  18608. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18609. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18610. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18611. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18612. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18613. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18614. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18615. var w, ix, iy,
  18616. gridX = scope.widthSegments,
  18617. gridY = scope.heightSegments,
  18618. width_half = width / 2,
  18619. height_half = height / 2,
  18620. offset = scope.vertices.length;
  18621. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18622. w = 'z';
  18623. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18624. w = 'y';
  18625. gridY = scope.depthSegments;
  18626. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18627. w = 'x';
  18628. gridX = scope.depthSegments;
  18629. }
  18630. var gridX1 = gridX + 1,
  18631. gridY1 = gridY + 1,
  18632. segment_width = width / gridX,
  18633. segment_height = height / gridY,
  18634. normal = new THREE.Vector3();
  18635. normal[ w ] = depth > 0 ? 1 : - 1;
  18636. for ( iy = 0; iy < gridY1; iy ++ ) {
  18637. for ( ix = 0; ix < gridX1; ix ++ ) {
  18638. var vector = new THREE.Vector3();
  18639. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18640. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18641. vector[ w ] = depth;
  18642. scope.vertices.push( vector );
  18643. }
  18644. }
  18645. for ( iy = 0; iy < gridY; iy++ ) {
  18646. for ( ix = 0; ix < gridX; ix++ ) {
  18647. var a = ix + gridX1 * iy;
  18648. var b = ix + gridX1 * ( iy + 1 );
  18649. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18650. var d = ( ix + 1 ) + gridX1 * iy;
  18651. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  18652. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  18653. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  18654. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  18655. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  18656. face.normal.copy( normal );
  18657. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18658. face.materialIndex = materialIndex;
  18659. scope.faces.push( face );
  18660. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  18661. face = new THREE.Face3( b + offset, c + offset, d + offset );
  18662. face.normal.copy( normal );
  18663. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18664. face.materialIndex = materialIndex;
  18665. scope.faces.push( face );
  18666. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  18667. }
  18668. }
  18669. }
  18670. this.computeCentroids();
  18671. this.mergeVertices();
  18672. };
  18673. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18674. /**
  18675. * @author mrdoob / http://mrdoob.com/
  18676. */
  18677. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  18678. THREE.Geometry.call( this );
  18679. this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18680. this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18681. this.height = height = height !== undefined ? height : 100;
  18682. this.radialSegments = radialSegments = radialSegments || 8;
  18683. this.heightSegments = heightSegments = heightSegments || 1;
  18684. this.openEnded = openEnded = openEnded !== undefined ? openEnded : false;
  18685. var heightHalf = height / 2;
  18686. var x, y, vertices = [], uvs = [];
  18687. for ( y = 0; y <= heightSegments; y ++ ) {
  18688. var verticesRow = [];
  18689. var uvsRow = [];
  18690. var v = y / heightSegments;
  18691. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18692. for ( x = 0; x <= radialSegments; x ++ ) {
  18693. var u = x / radialSegments;
  18694. var vertex = new THREE.Vector3();
  18695. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18696. vertex.y = - v * height + heightHalf;
  18697. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18698. this.vertices.push( vertex );
  18699. verticesRow.push( this.vertices.length - 1 );
  18700. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18701. }
  18702. vertices.push( verticesRow );
  18703. uvs.push( uvsRow );
  18704. }
  18705. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18706. var na, nb;
  18707. for ( x = 0; x < radialSegments; x ++ ) {
  18708. if ( radiusTop !== 0 ) {
  18709. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18710. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18711. } else {
  18712. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18713. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18714. }
  18715. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18716. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18717. for ( y = 0; y < heightSegments; y ++ ) {
  18718. var v1 = vertices[ y ][ x ];
  18719. var v2 = vertices[ y + 1 ][ x ];
  18720. var v3 = vertices[ y + 1 ][ x + 1 ];
  18721. var v4 = vertices[ y ][ x + 1 ];
  18722. var n1 = na.clone();
  18723. var n2 = na.clone();
  18724. var n3 = nb.clone();
  18725. var n4 = nb.clone();
  18726. var uv1 = uvs[ y ][ x ].clone();
  18727. var uv2 = uvs[ y + 1 ][ x ].clone();
  18728. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18729. var uv4 = uvs[ y ][ x + 1 ].clone();
  18730. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  18731. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  18732. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  18733. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  18734. }
  18735. }
  18736. // top cap
  18737. if ( openEnded === false && radiusTop > 0 ) {
  18738. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18739. for ( x = 0; x < radialSegments; x ++ ) {
  18740. var v1 = vertices[ 0 ][ x ];
  18741. var v2 = vertices[ 0 ][ x + 1 ];
  18742. var v3 = this.vertices.length - 1;
  18743. var n1 = new THREE.Vector3( 0, 1, 0 );
  18744. var n2 = new THREE.Vector3( 0, 1, 0 );
  18745. var n3 = new THREE.Vector3( 0, 1, 0 );
  18746. var uv1 = uvs[ 0 ][ x ].clone();
  18747. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18748. var uv3 = new THREE.Vector2( uv2.x, 0 );
  18749. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18750. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18751. }
  18752. }
  18753. // bottom cap
  18754. if ( openEnded === false && radiusBottom > 0 ) {
  18755. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18756. for ( x = 0; x < radialSegments; x ++ ) {
  18757. var v1 = vertices[ y ][ x + 1 ];
  18758. var v2 = vertices[ y ][ x ];
  18759. var v3 = this.vertices.length - 1;
  18760. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18761. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18762. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18763. var uv1 = uvs[ y ][ x + 1 ].clone();
  18764. var uv2 = uvs[ y ][ x ].clone();
  18765. var uv3 = new THREE.Vector2( uv2.x, 1 );
  18766. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18767. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18768. }
  18769. }
  18770. this.computeCentroids();
  18771. this.computeFaceNormals();
  18772. }
  18773. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18774. /**
  18775. * @author zz85 / http://www.lab4games.net/zz85/blog
  18776. *
  18777. * Creates extruded geometry from a path shape.
  18778. *
  18779. * parameters = {
  18780. *
  18781. * curveSegments: <int>, // number of points on the curves
  18782. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18783. * amount: <int>, // Depth to extrude the shape
  18784. *
  18785. * bevelEnabled: <bool>, // turn on bevel
  18786. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18787. * bevelSize: <float>, // how far from shape outline is bevel
  18788. * bevelSegments: <int>, // number of bevel layers
  18789. *
  18790. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18791. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18792. *
  18793. * material: <int> // material index for front and back faces
  18794. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18795. * uvGenerator: <Object> // object that provides UV generator functions
  18796. *
  18797. * }
  18798. **/
  18799. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18800. if ( typeof( shapes ) === "undefined" ) {
  18801. shapes = [];
  18802. return;
  18803. }
  18804. THREE.Geometry.call( this );
  18805. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18806. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18807. this.addShapeList( shapes, options );
  18808. this.computeCentroids();
  18809. this.computeFaceNormals();
  18810. // can't really use automatic vertex normals
  18811. // as then front and back sides get smoothed too
  18812. // should do separate smoothing just for sides
  18813. //this.computeVertexNormals();
  18814. //console.log( "took", ( Date.now() - startTime ) );
  18815. };
  18816. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18817. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18818. var sl = shapes.length;
  18819. for ( var s = 0; s < sl; s ++ ) {
  18820. var shape = shapes[ s ];
  18821. this.addShape( shape, options );
  18822. }
  18823. };
  18824. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18825. var amount = options.amount !== undefined ? options.amount : 100;
  18826. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18827. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18828. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18829. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18830. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18831. var steps = options.steps !== undefined ? options.steps : 1;
  18832. var extrudePath = options.extrudePath;
  18833. var extrudePts, extrudeByPath = false;
  18834. var material = options.material;
  18835. var extrudeMaterial = options.extrudeMaterial;
  18836. // Use default WorldUVGenerator if no UV generators are specified.
  18837. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18838. var shapebb = this.shapebb;
  18839. //shapebb = shape.getBoundingBox();
  18840. var splineTube, binormal, normal, position2;
  18841. if ( extrudePath ) {
  18842. extrudePts = extrudePath.getSpacedPoints( steps );
  18843. extrudeByPath = true;
  18844. bevelEnabled = false; // bevels not supported for path extrusion
  18845. // SETUP TNB variables
  18846. // Reuse TNB from TubeGeomtry for now.
  18847. // TODO1 - have a .isClosed in spline?
  18848. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18849. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18850. binormal = new THREE.Vector3();
  18851. normal = new THREE.Vector3();
  18852. position2 = new THREE.Vector3();
  18853. }
  18854. // Safeguards if bevels are not enabled
  18855. if ( ! bevelEnabled ) {
  18856. bevelSegments = 0;
  18857. bevelThickness = 0;
  18858. bevelSize = 0;
  18859. }
  18860. // Variables initalization
  18861. var ahole, h, hl; // looping of holes
  18862. var scope = this;
  18863. var bevelPoints = [];
  18864. var shapesOffset = this.vertices.length;
  18865. var shapePoints = shape.extractPoints( curveSegments );
  18866. var vertices = shapePoints.shape;
  18867. var holes = shapePoints.holes;
  18868. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18869. if ( reverse ) {
  18870. vertices = vertices.reverse();
  18871. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18872. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18873. ahole = holes[ h ];
  18874. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18875. holes[ h ] = ahole.reverse();
  18876. }
  18877. }
  18878. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18879. }
  18880. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18881. /* Vertices */
  18882. var contour = vertices; // vertices has all points but contour has only points of circumference
  18883. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18884. ahole = holes[ h ];
  18885. vertices = vertices.concat( ahole );
  18886. }
  18887. function scalePt2 ( pt, vec, size ) {
  18888. if ( !vec ) console.log( "die" );
  18889. return vec.clone().multiplyScalar( size ).add( pt );
  18890. }
  18891. var b, bs, t, z,
  18892. vert, vlen = vertices.length,
  18893. face, flen = faces.length,
  18894. cont, clen = contour.length;
  18895. // Find directions for point movement
  18896. var RAD_TO_DEGREES = 180 / Math.PI;
  18897. function getBevelVec( pt_i, pt_j, pt_k ) {
  18898. // Algorithm 2
  18899. return getBevelVec2( pt_i, pt_j, pt_k );
  18900. }
  18901. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18902. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18903. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18904. if ( anglea > angleb ) {
  18905. angleb += Math.PI * 2;
  18906. }
  18907. var anglec = ( anglea + angleb ) / 2;
  18908. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18909. var x = - Math.cos( anglec );
  18910. var y = - Math.sin( anglec );
  18911. var vec = new THREE.Vector2( x, y ); //.normalize();
  18912. return vec;
  18913. }
  18914. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18915. var a = THREE.ExtrudeGeometry.__v1,
  18916. b = THREE.ExtrudeGeometry.__v2,
  18917. v_hat = THREE.ExtrudeGeometry.__v3,
  18918. w_hat = THREE.ExtrudeGeometry.__v4,
  18919. p = THREE.ExtrudeGeometry.__v5,
  18920. q = THREE.ExtrudeGeometry.__v6,
  18921. v, w,
  18922. v_dot_w_hat, q_sub_p_dot_w_hat,
  18923. s, intersection;
  18924. // good reading for line-line intersection
  18925. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18926. // define a as vector j->i
  18927. // define b as vectot k->i
  18928. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18929. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18930. // get unit vectors
  18931. v = a.normalize();
  18932. w = b.normalize();
  18933. // normals from pt i
  18934. v_hat.set( -v.y, v.x );
  18935. w_hat.set( w.y, -w.x );
  18936. // pts from i
  18937. p.copy( pt_i ).add( v_hat );
  18938. q.copy( pt_i ).add( w_hat );
  18939. if ( p.equals( q ) ) {
  18940. //console.log("Warning: lines are straight");
  18941. return w_hat.clone();
  18942. }
  18943. // Points from j, k. helps prevents points cross overover most of the time
  18944. p.copy( pt_j ).add( v_hat );
  18945. q.copy( pt_k ).add( w_hat );
  18946. v_dot_w_hat = v.dot( w_hat );
  18947. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  18948. // We should not reach these conditions
  18949. if ( v_dot_w_hat === 0 ) {
  18950. console.log( "Either infinite or no solutions!" );
  18951. if ( q_sub_p_dot_w_hat === 0 ) {
  18952. console.log( "Its finite solutions." );
  18953. } else {
  18954. console.log( "Too bad, no solutions." );
  18955. }
  18956. }
  18957. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18958. if ( s < 0 ) {
  18959. // in case of emergecy, revert to algorithm 1.
  18960. return getBevelVec1( pt_i, pt_j, pt_k );
  18961. }
  18962. intersection = v.multiplyScalar( s ).add( p );
  18963. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18964. }
  18965. var contourMovements = [];
  18966. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18967. if ( j === il ) j = 0;
  18968. if ( k === il ) k = 0;
  18969. // (j)---(i)---(k)
  18970. // console.log('i,j,k', i, j , k)
  18971. var pt_i = contour[ i ];
  18972. var pt_j = contour[ j ];
  18973. var pt_k = contour[ k ];
  18974. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18975. }
  18976. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18977. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18978. ahole = holes[ h ];
  18979. oneHoleMovements = [];
  18980. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18981. if ( j === il ) j = 0;
  18982. if ( k === il ) k = 0;
  18983. // (j)---(i)---(k)
  18984. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18985. }
  18986. holesMovements.push( oneHoleMovements );
  18987. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18988. }
  18989. // Loop bevelSegments, 1 for the front, 1 for the back
  18990. for ( b = 0; b < bevelSegments; b ++ ) {
  18991. //for ( b = bevelSegments; b > 0; b -- ) {
  18992. t = b / bevelSegments;
  18993. z = bevelThickness * ( 1 - t );
  18994. //z = bevelThickness * t;
  18995. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18996. //bs = bevelSize * t ; // linear
  18997. // contract shape
  18998. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18999. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19000. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  19001. v( vert.x, vert.y, - z );
  19002. }
  19003. // expand holes
  19004. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19005. ahole = holes[ h ];
  19006. oneHoleMovements = holesMovements[ h ];
  19007. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19008. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19009. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  19010. v( vert.x, vert.y, -z );
  19011. }
  19012. }
  19013. }
  19014. bs = bevelSize;
  19015. // Back facing vertices
  19016. for ( i = 0; i < vlen; i ++ ) {
  19017. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19018. if ( !extrudeByPath ) {
  19019. v( vert.x, vert.y, 0 );
  19020. } else {
  19021. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19022. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19023. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19024. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  19025. v( position2.x, position2.y, position2.z );
  19026. }
  19027. }
  19028. // Add stepped vertices...
  19029. // Including front facing vertices
  19030. var s;
  19031. for ( s = 1; s <= steps; s ++ ) {
  19032. for ( i = 0; i < vlen; i ++ ) {
  19033. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19034. if ( !extrudeByPath ) {
  19035. v( vert.x, vert.y, amount / steps * s );
  19036. } else {
  19037. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19038. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19039. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19040. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19041. v( position2.x, position2.y, position2.z );
  19042. }
  19043. }
  19044. }
  19045. // Add bevel segments planes
  19046. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19047. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19048. t = b / bevelSegments;
  19049. z = bevelThickness * ( 1 - t );
  19050. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19051. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19052. // contract shape
  19053. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19054. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19055. v( vert.x, vert.y, amount + z );
  19056. }
  19057. // expand holes
  19058. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19059. ahole = holes[ h ];
  19060. oneHoleMovements = holesMovements[ h ];
  19061. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19062. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19063. if ( !extrudeByPath ) {
  19064. v( vert.x, vert.y, amount + z );
  19065. } else {
  19066. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19067. }
  19068. }
  19069. }
  19070. }
  19071. /* Faces */
  19072. // Top and bottom faces
  19073. buildLidFaces();
  19074. // Sides faces
  19075. buildSideFaces();
  19076. ///// Internal functions
  19077. function buildLidFaces() {
  19078. if ( bevelEnabled ) {
  19079. var layer = 0 ; // steps + 1
  19080. var offset = vlen * layer;
  19081. // Bottom faces
  19082. for ( i = 0; i < flen; i ++ ) {
  19083. face = faces[ i ];
  19084. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19085. }
  19086. layer = steps + bevelSegments * 2;
  19087. offset = vlen * layer;
  19088. // Top faces
  19089. for ( i = 0; i < flen; i ++ ) {
  19090. face = faces[ i ];
  19091. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19092. }
  19093. } else {
  19094. // Bottom faces
  19095. for ( i = 0; i < flen; i++ ) {
  19096. face = faces[ i ];
  19097. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19098. }
  19099. // Top faces
  19100. for ( i = 0; i < flen; i ++ ) {
  19101. face = faces[ i ];
  19102. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19103. }
  19104. }
  19105. }
  19106. // Create faces for the z-sides of the shape
  19107. function buildSideFaces() {
  19108. var layeroffset = 0;
  19109. sidewalls( contour, layeroffset );
  19110. layeroffset += contour.length;
  19111. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19112. ahole = holes[ h ];
  19113. sidewalls( ahole, layeroffset );
  19114. //, true
  19115. layeroffset += ahole.length;
  19116. }
  19117. }
  19118. function sidewalls( contour, layeroffset ) {
  19119. var j, k;
  19120. i = contour.length;
  19121. while ( --i >= 0 ) {
  19122. j = i;
  19123. k = i - 1;
  19124. if ( k < 0 ) k = contour.length - 1;
  19125. //console.log('b', i,j, i-1, k,vertices.length);
  19126. var s = 0, sl = steps + bevelSegments * 2;
  19127. for ( s = 0; s < sl; s ++ ) {
  19128. var slen1 = vlen * s;
  19129. var slen2 = vlen * ( s + 1 );
  19130. var a = layeroffset + j + slen1,
  19131. b = layeroffset + k + slen1,
  19132. c = layeroffset + k + slen2,
  19133. d = layeroffset + j + slen2;
  19134. f4( a, b, c, d, contour, s, sl, j, k );
  19135. }
  19136. }
  19137. }
  19138. function v( x, y, z ) {
  19139. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19140. }
  19141. function f3( a, b, c, isBottom ) {
  19142. a += shapesOffset;
  19143. b += shapesOffset;
  19144. c += shapesOffset;
  19145. // normal, color, material
  19146. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19147. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19148. scope.faceVertexUvs[ 0 ].push( uvs );
  19149. }
  19150. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19151. a += shapesOffset;
  19152. b += shapesOffset;
  19153. c += shapesOffset;
  19154. d += shapesOffset;
  19155. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  19156. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  19157. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19158. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19159. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  19160. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  19161. }
  19162. };
  19163. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19164. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19165. var ax = geometry.vertices[ indexA ].x,
  19166. ay = geometry.vertices[ indexA ].y,
  19167. bx = geometry.vertices[ indexB ].x,
  19168. by = geometry.vertices[ indexB ].y,
  19169. cx = geometry.vertices[ indexC ].x,
  19170. cy = geometry.vertices[ indexC ].y;
  19171. return [
  19172. new THREE.Vector2( ax, ay ),
  19173. new THREE.Vector2( bx, by ),
  19174. new THREE.Vector2( cx, cy )
  19175. ];
  19176. },
  19177. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19178. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19179. },
  19180. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19181. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19182. contourIndex1, contourIndex2 ) {
  19183. var ax = geometry.vertices[ indexA ].x,
  19184. ay = geometry.vertices[ indexA ].y,
  19185. az = geometry.vertices[ indexA ].z,
  19186. bx = geometry.vertices[ indexB ].x,
  19187. by = geometry.vertices[ indexB ].y,
  19188. bz = geometry.vertices[ indexB ].z,
  19189. cx = geometry.vertices[ indexC ].x,
  19190. cy = geometry.vertices[ indexC ].y,
  19191. cz = geometry.vertices[ indexC ].z,
  19192. dx = geometry.vertices[ indexD ].x,
  19193. dy = geometry.vertices[ indexD ].y,
  19194. dz = geometry.vertices[ indexD ].z;
  19195. if ( Math.abs( ay - by ) < 0.01 ) {
  19196. return [
  19197. new THREE.Vector2( ax, 1 - az ),
  19198. new THREE.Vector2( bx, 1 - bz ),
  19199. new THREE.Vector2( cx, 1 - cz ),
  19200. new THREE.Vector2( dx, 1 - dz )
  19201. ];
  19202. } else {
  19203. return [
  19204. new THREE.Vector2( ay, 1 - az ),
  19205. new THREE.Vector2( by, 1 - bz ),
  19206. new THREE.Vector2( cy, 1 - cz ),
  19207. new THREE.Vector2( dy, 1 - dz )
  19208. ];
  19209. }
  19210. }
  19211. };
  19212. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19213. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19214. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19215. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19216. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19217. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19218. /**
  19219. * @author jonobr1 / http://jonobr1.com
  19220. *
  19221. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19222. * ExtrudeGeometry.
  19223. *
  19224. * parameters = {
  19225. *
  19226. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19227. *
  19228. * material: <int> // material index for front and back faces
  19229. * uvGenerator: <Object> // object that provides UV generator functions
  19230. *
  19231. * }
  19232. **/
  19233. THREE.ShapeGeometry = function ( shapes, options ) {
  19234. THREE.Geometry.call( this );
  19235. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19236. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19237. this.addShapeList( shapes, options );
  19238. this.computeCentroids();
  19239. this.computeFaceNormals();
  19240. };
  19241. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19242. /**
  19243. * Add an array of shapes to THREE.ShapeGeometry.
  19244. */
  19245. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19246. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19247. this.addShape( shapes[ i ], options );
  19248. }
  19249. return this;
  19250. };
  19251. /**
  19252. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19253. */
  19254. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19255. if ( options === undefined ) options = {};
  19256. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19257. var material = options.material;
  19258. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19259. var shapebb = this.shapebb;
  19260. //
  19261. var i, l, hole, s;
  19262. var shapesOffset = this.vertices.length;
  19263. var shapePoints = shape.extractPoints( curveSegments );
  19264. var vertices = shapePoints.shape;
  19265. var holes = shapePoints.holes;
  19266. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19267. if ( reverse ) {
  19268. vertices = vertices.reverse();
  19269. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19270. for ( i = 0, l = holes.length; i < l; i++ ) {
  19271. hole = holes[ i ];
  19272. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19273. holes[ i ] = hole.reverse();
  19274. }
  19275. }
  19276. reverse = false;
  19277. }
  19278. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19279. // Vertices
  19280. var contour = vertices;
  19281. for ( i = 0, l = holes.length; i < l; i++ ) {
  19282. hole = holes[ i ];
  19283. vertices = vertices.concat( hole );
  19284. }
  19285. //
  19286. var vert, vlen = vertices.length;
  19287. var face, flen = faces.length;
  19288. var cont, clen = contour.length;
  19289. for ( i = 0; i < vlen; i++ ) {
  19290. vert = vertices[ i ];
  19291. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19292. }
  19293. for ( i = 0; i < flen; i++ ) {
  19294. face = faces[ i ];
  19295. var a = face[ 0 ] + shapesOffset;
  19296. var b = face[ 1 ] + shapesOffset;
  19297. var c = face[ 2 ] + shapesOffset;
  19298. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19299. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19300. }
  19301. };
  19302. /**
  19303. * @author astrodud / http://astrodud.isgreat.org/
  19304. * @author zz85 / https://github.com/zz85
  19305. * @author bhouston / http://exocortex.com
  19306. */
  19307. // points - to create a closed torus, one must use a set of points
  19308. // like so: [ a, b, c, d, a ], see first is the same as last.
  19309. // segments - the number of circumference segments to create
  19310. // phiStart - the starting radian
  19311. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19312. // 2*pi is a closed lathe, less than 2PI is a portion.
  19313. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19314. THREE.Geometry.call( this );
  19315. segments = segments || 12;
  19316. phiStart = phiStart || 0;
  19317. phiLength = phiLength || 2 * Math.PI;
  19318. var inversePointLength = 1.0 / ( points.length - 1 );
  19319. var inverseSegments = 1.0 / segments;
  19320. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19321. var phi = phiStart + i * inverseSegments * phiLength;
  19322. var c = Math.cos( phi ),
  19323. s = Math.sin( phi );
  19324. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19325. var pt = points[ j ];
  19326. var vertex = new THREE.Vector3();
  19327. vertex.x = c * pt.x - s * pt.y;
  19328. vertex.y = s * pt.x + c * pt.y;
  19329. vertex.z = pt.z;
  19330. this.vertices.push( vertex );
  19331. }
  19332. }
  19333. var np = points.length;
  19334. for ( var i = 0, il = segments; i < il; i ++ ) {
  19335. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19336. var base = j + np * i;
  19337. var a = base;
  19338. var b = base + np;
  19339. var c = base + 1 + np;
  19340. var d = base + 1;
  19341. var u0 = i * inverseSegments;
  19342. var v0 = j * inversePointLength;
  19343. var u1 = u0 + inverseSegments;
  19344. var v1 = v0 + inversePointLength;
  19345. this.faces.push( new THREE.Face3( a, b, d ) );
  19346. this.faceVertexUvs[ 0 ].push( [
  19347. new THREE.Vector2( u0, v0 ),
  19348. new THREE.Vector2( u1, v0 ),
  19349. new THREE.Vector2( u0, v1 )
  19350. ] );
  19351. this.faces.push( new THREE.Face3( b, c, d ) );
  19352. this.faceVertexUvs[ 0 ].push( [
  19353. new THREE.Vector2( u1, v0 ),
  19354. new THREE.Vector2( u1, v1 ),
  19355. new THREE.Vector2( u0, v1 )
  19356. ] );
  19357. }
  19358. }
  19359. this.mergeVertices();
  19360. this.computeCentroids();
  19361. this.computeFaceNormals();
  19362. this.computeVertexNormals();
  19363. };
  19364. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19365. /**
  19366. * @author mrdoob / http://mrdoob.com/
  19367. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19368. */
  19369. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19370. THREE.Geometry.call( this );
  19371. this.width = width;
  19372. this.height = height;
  19373. this.widthSegments = widthSegments || 1;
  19374. this.heightSegments = heightSegments || 1;
  19375. var ix, iz;
  19376. var width_half = width / 2;
  19377. var height_half = height / 2;
  19378. var gridX = this.widthSegments;
  19379. var gridZ = this.heightSegments;
  19380. var gridX1 = gridX + 1;
  19381. var gridZ1 = gridZ + 1;
  19382. var segment_width = this.width / gridX;
  19383. var segment_height = this.height / gridZ;
  19384. var normal = new THREE.Vector3( 0, 0, 1 );
  19385. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19386. for ( ix = 0; ix < gridX1; ix ++ ) {
  19387. var x = ix * segment_width - width_half;
  19388. var y = iz * segment_height - height_half;
  19389. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19390. }
  19391. }
  19392. for ( iz = 0; iz < gridZ; iz ++ ) {
  19393. for ( ix = 0; ix < gridX; ix ++ ) {
  19394. var a = ix + gridX1 * iz;
  19395. var b = ix + gridX1 * ( iz + 1 );
  19396. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19397. var d = ( ix + 1 ) + gridX1 * iz;
  19398. var uva = new THREE.Vector2( ix / gridX, 1 - iz / gridZ );
  19399. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ );
  19400. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ );
  19401. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ );
  19402. var face = new THREE.Face3( a, b, d );
  19403. face.normal.copy( normal );
  19404. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19405. this.faces.push( face );
  19406. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19407. face = new THREE.Face3( b, c, d );
  19408. face.normal.copy( normal );
  19409. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19410. this.faces.push( face );
  19411. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19412. }
  19413. }
  19414. this.computeCentroids();
  19415. };
  19416. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19417. /**
  19418. * @author Kaleb Murphy
  19419. */
  19420. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19421. THREE.Geometry.call( this );
  19422. innerRadius = innerRadius || 0;
  19423. outerRadius = outerRadius || 50;
  19424. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19425. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19426. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19427. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19428. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19429. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19430. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19431. var vertex = new THREE.Vector3();
  19432. var segment = thetaStart + o / thetaSegments * thetaLength;
  19433. vertex.x = radius * Math.cos( segment );
  19434. vertex.y = radius * Math.sin( segment );
  19435. this.vertices.push( vertex );
  19436. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  19437. }
  19438. radius += radiusStep;
  19439. }
  19440. var n = new THREE.Vector3( 0, 0, 1 );
  19441. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19442. var thetaSegment = i * thetaSegments;
  19443. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19444. var segment = o + thetaSegment;
  19445. var v1 = segment + i;
  19446. var v2 = segment + thetaSegments + i;
  19447. var v3 = segment + thetaSegments + 1 + i;
  19448. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19449. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19450. v1 = segment + i;
  19451. v2 = segment + thetaSegments + 1 + i;
  19452. v3 = segment + 1 + i;
  19453. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19454. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19455. }
  19456. }
  19457. this.computeCentroids();
  19458. this.computeFaceNormals();
  19459. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19460. };
  19461. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19462. /**
  19463. * @author mrdoob / http://mrdoob.com/
  19464. */
  19465. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19466. THREE.Geometry.call( this );
  19467. this.radius = radius = radius || 50;
  19468. this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19469. this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19470. this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0;
  19471. this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19472. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19473. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19474. var x, y, vertices = [], uvs = [];
  19475. for ( y = 0; y <= heightSegments; y ++ ) {
  19476. var verticesRow = [];
  19477. var uvsRow = [];
  19478. for ( x = 0; x <= widthSegments; x ++ ) {
  19479. var u = x / widthSegments;
  19480. var v = y / heightSegments;
  19481. var vertex = new THREE.Vector3();
  19482. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19483. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19484. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19485. this.vertices.push( vertex );
  19486. verticesRow.push( this.vertices.length - 1 );
  19487. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19488. }
  19489. vertices.push( verticesRow );
  19490. uvs.push( uvsRow );
  19491. }
  19492. for ( y = 0; y < this.heightSegments; y ++ ) {
  19493. for ( x = 0; x < this.widthSegments; x ++ ) {
  19494. var v1 = vertices[ y ][ x + 1 ];
  19495. var v2 = vertices[ y ][ x ];
  19496. var v3 = vertices[ y + 1 ][ x ];
  19497. var v4 = vertices[ y + 1 ][ x + 1 ];
  19498. var n1 = this.vertices[ v1 ].clone().normalize();
  19499. var n2 = this.vertices[ v2 ].clone().normalize();
  19500. var n3 = this.vertices[ v3 ].clone().normalize();
  19501. var n4 = this.vertices[ v4 ].clone().normalize();
  19502. var uv1 = uvs[ y ][ x + 1 ].clone();
  19503. var uv2 = uvs[ y ][ x ].clone();
  19504. var uv3 = uvs[ y + 1 ][ x ].clone();
  19505. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19506. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19507. uv1.x = ( uv1.x + uv2.x ) / 2;
  19508. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19509. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19510. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19511. uv3.x = ( uv3.x + uv4.x ) / 2;
  19512. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19513. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19514. } else {
  19515. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19516. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19517. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19518. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19519. }
  19520. }
  19521. }
  19522. this.computeCentroids();
  19523. this.computeFaceNormals();
  19524. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19525. };
  19526. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19527. /**
  19528. * @author zz85 / http://www.lab4games.net/zz85/blog
  19529. * @author alteredq / http://alteredqualia.com/
  19530. *
  19531. * For creating 3D text geometry in three.js
  19532. *
  19533. * Text = 3D Text
  19534. *
  19535. * parameters = {
  19536. * size: <float>, // size of the text
  19537. * height: <float>, // thickness to extrude text
  19538. * curveSegments: <int>, // number of points on the curves
  19539. *
  19540. * font: <string>, // font name
  19541. * weight: <string>, // font weight (normal, bold)
  19542. * style: <string>, // font style (normal, italics)
  19543. *
  19544. * bevelEnabled: <bool>, // turn on bevel
  19545. * bevelThickness: <float>, // how deep into text bevel goes
  19546. * bevelSize: <float>, // how far from text outline is bevel
  19547. * }
  19548. *
  19549. */
  19550. /* Usage Examples
  19551. // TextGeometry wrapper
  19552. var text3d = new TextGeometry( text, options );
  19553. // Complete manner
  19554. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19555. var text3d = new ExtrudeGeometry( textShapes, options );
  19556. */
  19557. THREE.TextGeometry = function ( text, parameters ) {
  19558. parameters = parameters || {};
  19559. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19560. // translate parameters to ExtrudeGeometry API
  19561. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19562. // defaults
  19563. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19564. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19565. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19566. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19567. };
  19568. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19569. /**
  19570. * @author oosmoxiecode
  19571. * @author mrdoob / http://mrdoob.com/
  19572. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19573. */
  19574. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19575. THREE.Geometry.call( this );
  19576. var scope = this;
  19577. this.radius = radius || 100;
  19578. this.tube = tube || 40;
  19579. this.radialSegments = radialSegments || 8;
  19580. this.tubularSegments = tubularSegments || 6;
  19581. this.arc = arc || Math.PI * 2;
  19582. var center = new THREE.Vector3(), uvs = [], normals = [];
  19583. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19584. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19585. var u = i / this.tubularSegments * this.arc;
  19586. var v = j / this.radialSegments * Math.PI * 2;
  19587. center.x = this.radius * Math.cos( u );
  19588. center.y = this.radius * Math.sin( u );
  19589. var vertex = new THREE.Vector3();
  19590. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19591. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19592. vertex.z = this.tube * Math.sin( v );
  19593. this.vertices.push( vertex );
  19594. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19595. normals.push( vertex.clone().sub( center ).normalize() );
  19596. }
  19597. }
  19598. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19599. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19600. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19601. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19602. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19603. var d = ( this.tubularSegments + 1 ) * j + i;
  19604. var face = new THREE.Face3( a, b, d, [ normals[ a ], normals[ b ], normals[ d ] ] );
  19605. face.normal.add( normals[ a ] );
  19606. face.normal.add( normals[ b ] );
  19607. face.normal.add( normals[ d ] );
  19608. face.normal.normalize();
  19609. this.faces.push( face );
  19610. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  19611. face = new THREE.Face3( b, c, d, [ normals[ b ], normals[ c ], normals[ d ] ] );
  19612. face.normal.add( normals[ b ] );
  19613. face.normal.add( normals[ c ] );
  19614. face.normal.add( normals[ d ] );
  19615. face.normal.normalize();
  19616. this.faces.push( face );
  19617. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19618. }
  19619. }
  19620. this.computeCentroids();
  19621. };
  19622. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19623. /**
  19624. * @author oosmoxiecode
  19625. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19626. */
  19627. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19628. THREE.Geometry.call( this );
  19629. var scope = this;
  19630. this.radius = radius || 100;
  19631. this.tube = tube || 40;
  19632. this.radialSegments = radialSegments || 64;
  19633. this.tubularSegments = tubularSegments || 8;
  19634. this.p = p || 2;
  19635. this.q = q || 3;
  19636. this.heightScale = heightScale || 1;
  19637. this.grid = new Array( this.radialSegments );
  19638. var tang = new THREE.Vector3();
  19639. var n = new THREE.Vector3();
  19640. var bitan = new THREE.Vector3();
  19641. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19642. this.grid[ i ] = new Array( this.tubularSegments );
  19643. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19644. var p1 = getPos( u, this.q, this.p, this.radius, this.heightScale );
  19645. var p2 = getPos( u + 0.01, this.q, this.p, this.radius, this.heightScale );
  19646. tang.subVectors( p2, p1 );
  19647. n.addVectors( p2, p1 );
  19648. bitan.crossVectors( tang, n );
  19649. n.crossVectors( bitan, tang );
  19650. bitan.normalize();
  19651. n.normalize();
  19652. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19653. var v = j / this.tubularSegments * 2 * Math.PI;
  19654. var cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19655. var cy = this.tube * Math.sin( v );
  19656. var pos = new THREE.Vector3();
  19657. pos.x = p1.x + cx * n.x + cy * bitan.x;
  19658. pos.y = p1.y + cx * n.y + cy * bitan.y;
  19659. pos.z = p1.z + cx * n.z + cy * bitan.z;
  19660. this.grid[ i ][ j ] = scope.vertices.push( pos ) - 1;
  19661. }
  19662. }
  19663. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19664. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19665. var ip = ( i + 1 ) % this.radialSegments;
  19666. var jp = ( j + 1 ) % this.tubularSegments;
  19667. var a = this.grid[ i ][ j ];
  19668. var b = this.grid[ ip ][ j ];
  19669. var c = this.grid[ ip ][ jp ];
  19670. var d = this.grid[ i ][ jp ];
  19671. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19672. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19673. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19674. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19675. this.faces.push( new THREE.Face3( a, b, d ) );
  19676. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19677. this.faces.push( new THREE.Face3( b, c, d ) );
  19678. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19679. }
  19680. }
  19681. this.computeCentroids();
  19682. this.computeFaceNormals();
  19683. this.computeVertexNormals();
  19684. function getPos( u, in_q, in_p, radius, heightScale ) {
  19685. var cu = Math.cos( u );
  19686. var su = Math.sin( u );
  19687. var quOverP = in_q / in_p * u;
  19688. var cs = Math.cos( quOverP );
  19689. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19690. var ty = radius * ( 2 + cs ) * su * 0.5;
  19691. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19692. return new THREE.Vector3( tx, ty, tz );
  19693. }
  19694. };
  19695. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19696. /**
  19697. * @author WestLangley / https://github.com/WestLangley
  19698. * @author zz85 / https://github.com/zz85
  19699. * @author miningold / https://github.com/miningold
  19700. *
  19701. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19702. *
  19703. * Creates a tube which extrudes along a 3d spline
  19704. *
  19705. * Uses parallel transport frames as described in
  19706. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19707. */
  19708. THREE.TubeGeometry = function( path, segments, radius, radialSegments, closed ) {
  19709. THREE.Geometry.call( this );
  19710. this.path = path;
  19711. this.segments = segments || 64;
  19712. this.radius = radius || 1;
  19713. this.radialSegments = radialSegments || 8;
  19714. this.closed = closed || false;
  19715. this.grid = [];
  19716. var scope = this,
  19717. tangent,
  19718. normal,
  19719. binormal,
  19720. numpoints = this.segments + 1,
  19721. x, y, z,
  19722. tx, ty, tz,
  19723. u, v,
  19724. cx, cy,
  19725. pos, pos2 = new THREE.Vector3(),
  19726. i, j,
  19727. ip, jp,
  19728. a, b, c, d,
  19729. uva, uvb, uvc, uvd;
  19730. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19731. tangents = frames.tangents,
  19732. normals = frames.normals,
  19733. binormals = frames.binormals;
  19734. // proxy internals
  19735. this.tangents = tangents;
  19736. this.normals = normals;
  19737. this.binormals = binormals;
  19738. function vert( x, y, z ) {
  19739. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19740. }
  19741. // consruct the grid
  19742. for ( i = 0; i < numpoints; i++ ) {
  19743. this.grid[ i ] = [];
  19744. u = i / ( numpoints - 1 );
  19745. pos = path.getPointAt( u );
  19746. tangent = tangents[ i ];
  19747. normal = normals[ i ];
  19748. binormal = binormals[ i ];
  19749. for ( j = 0; j < this.radialSegments; j++ ) {
  19750. v = j / this.radialSegments * 2 * Math.PI;
  19751. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19752. cy = this.radius * Math.sin( v );
  19753. pos2.copy( pos );
  19754. pos2.x += cx * normal.x + cy * binormal.x;
  19755. pos2.y += cx * normal.y + cy * binormal.y;
  19756. pos2.z += cx * normal.z + cy * binormal.z;
  19757. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19758. }
  19759. }
  19760. // construct the mesh
  19761. for ( i = 0; i < this.segments; i++ ) {
  19762. for ( j = 0; j < this.radialSegments; j++ ) {
  19763. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  19764. jp = (j + 1) % this.radialSegments;
  19765. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19766. b = this.grid[ ip ][ j ];
  19767. c = this.grid[ ip ][ jp ];
  19768. d = this.grid[ i ][ jp ];
  19769. uva = new THREE.Vector2( i / this.segments, j / this.radialSegments );
  19770. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radialSegments );
  19771. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radialSegments );
  19772. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radialSegments );
  19773. this.faces.push( new THREE.Face3( a, b, d ) );
  19774. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19775. this.faces.push( new THREE.Face3( b, c, d ) );
  19776. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19777. }
  19778. }
  19779. this.computeCentroids();
  19780. this.computeFaceNormals();
  19781. this.computeVertexNormals();
  19782. };
  19783. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19784. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19785. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19786. var tangent = new THREE.Vector3(),
  19787. normal = new THREE.Vector3(),
  19788. binormal = new THREE.Vector3(),
  19789. tangents = [],
  19790. normals = [],
  19791. binormals = [],
  19792. vec = new THREE.Vector3(),
  19793. mat = new THREE.Matrix4(),
  19794. numpoints = segments + 1,
  19795. theta,
  19796. epsilon = 0.0001,
  19797. smallest,
  19798. tx, ty, tz,
  19799. i, u, v;
  19800. // expose internals
  19801. this.tangents = tangents;
  19802. this.normals = normals;
  19803. this.binormals = binormals;
  19804. // compute the tangent vectors for each segment on the path
  19805. for ( i = 0; i < numpoints; i++ ) {
  19806. u = i / ( numpoints - 1 );
  19807. tangents[ i ] = path.getTangentAt( u );
  19808. tangents[ i ].normalize();
  19809. }
  19810. initialNormal3();
  19811. function initialNormal1(lastBinormal) {
  19812. // fixed start binormal. Has dangers of 0 vectors
  19813. normals[ 0 ] = new THREE.Vector3();
  19814. binormals[ 0 ] = new THREE.Vector3();
  19815. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19816. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19817. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19818. }
  19819. function initialNormal2() {
  19820. // This uses the Frenet-Serret formula for deriving binormal
  19821. var t2 = path.getTangentAt( epsilon );
  19822. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19823. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19824. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19825. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19826. }
  19827. function initialNormal3() {
  19828. // select an initial normal vector perpenicular to the first tangent vector,
  19829. // and in the direction of the smallest tangent xyz component
  19830. normals[ 0 ] = new THREE.Vector3();
  19831. binormals[ 0 ] = new THREE.Vector3();
  19832. smallest = Number.MAX_VALUE;
  19833. tx = Math.abs( tangents[ 0 ].x );
  19834. ty = Math.abs( tangents[ 0 ].y );
  19835. tz = Math.abs( tangents[ 0 ].z );
  19836. if ( tx <= smallest ) {
  19837. smallest = tx;
  19838. normal.set( 1, 0, 0 );
  19839. }
  19840. if ( ty <= smallest ) {
  19841. smallest = ty;
  19842. normal.set( 0, 1, 0 );
  19843. }
  19844. if ( tz <= smallest ) {
  19845. normal.set( 0, 0, 1 );
  19846. }
  19847. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19848. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19849. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19850. }
  19851. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19852. for ( i = 1; i < numpoints; i++ ) {
  19853. normals[ i ] = normals[ i-1 ].clone();
  19854. binormals[ i ] = binormals[ i-1 ].clone();
  19855. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  19856. if ( vec.length() > epsilon ) {
  19857. vec.normalize();
  19858. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  19859. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19860. }
  19861. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19862. }
  19863. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19864. if ( closed ) {
  19865. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  19866. theta /= ( numpoints - 1 );
  19867. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19868. theta = -theta;
  19869. }
  19870. for ( i = 1; i < numpoints; i++ ) {
  19871. // twist a little...
  19872. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19873. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19874. }
  19875. }
  19876. };
  19877. /**
  19878. * @author clockworkgeek / https://github.com/clockworkgeek
  19879. * @author timothypratley / https://github.com/timothypratley
  19880. * @author WestLangley / http://github.com/WestLangley
  19881. */
  19882. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19883. THREE.Geometry.call( this );
  19884. radius = radius || 1;
  19885. detail = detail || 0;
  19886. var that = this;
  19887. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19888. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19889. }
  19890. var midpoints = [], p = this.vertices;
  19891. var f = [];
  19892. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19893. var v1 = p[ faces[ i ][ 0 ] ];
  19894. var v2 = p[ faces[ i ][ 1 ] ];
  19895. var v3 = p[ faces[ i ][ 2 ] ];
  19896. f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19897. }
  19898. for ( var i = 0, l = f.length; i < l; i ++ ) {
  19899. subdivide(f[ i ], detail);
  19900. }
  19901. // Handle case when face straddles the seam
  19902. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  19903. var uvs = this.faceVertexUvs[ 0 ][ i ];
  19904. var x0 = uvs[ 0 ].x;
  19905. var x1 = uvs[ 1 ].x;
  19906. var x2 = uvs[ 2 ].x;
  19907. var max = Math.max( x0, Math.max( x1, x2 ) );
  19908. var min = Math.min( x0, Math.min( x1, x2 ) );
  19909. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  19910. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  19911. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  19912. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  19913. }
  19914. }
  19915. // Apply radius
  19916. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19917. this.vertices[ i ].multiplyScalar( radius );
  19918. }
  19919. // Merge vertices
  19920. this.mergeVertices();
  19921. this.computeCentroids();
  19922. this.computeFaceNormals();
  19923. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19924. // Project vector onto sphere's surface
  19925. function prepare( vector ) {
  19926. var vertex = vector.normalize().clone();
  19927. vertex.index = that.vertices.push( vertex ) - 1;
  19928. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19929. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19930. var v = inclination( vector ) / Math.PI + 0.5;
  19931. vertex.uv = new THREE.Vector2( u, 1 - v );
  19932. return vertex;
  19933. }
  19934. // Approximate a curved face with recursively sub-divided triangles.
  19935. function make( v1, v2, v3 ) {
  19936. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19937. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19938. that.faces.push( face );
  19939. var azi = azimuth( face.centroid );
  19940. that.faceVertexUvs[ 0 ].push( [
  19941. correctUV( v1.uv, v1, azi ),
  19942. correctUV( v2.uv, v2, azi ),
  19943. correctUV( v3.uv, v3, azi )
  19944. ] );
  19945. }
  19946. // Analytically subdivide a face to the required detail level.
  19947. function subdivide(face, detail ) {
  19948. var cols = Math.pow(2, detail);
  19949. var cells = Math.pow(4, detail);
  19950. var a = prepare( that.vertices[ face.a ] );
  19951. var b = prepare( that.vertices[ face.b ] );
  19952. var c = prepare( that.vertices[ face.c ] );
  19953. var v = [];
  19954. // Construct all of the vertices for this subdivision.
  19955. for ( var i = 0 ; i <= cols; i ++ ) {
  19956. v[ i ] = [];
  19957. var aj = prepare( a.clone().lerp( c, i / cols ) );
  19958. var bj = prepare( b.clone().lerp( c, i / cols ) );
  19959. var rows = cols - i;
  19960. for ( var j = 0; j <= rows; j ++) {
  19961. if ( j == 0 && i == cols ) {
  19962. v[ i ][ j ] = aj;
  19963. } else {
  19964. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  19965. }
  19966. }
  19967. }
  19968. // Construct all of the faces.
  19969. for ( var i = 0; i < cols ; i ++ ) {
  19970. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  19971. var k = Math.floor( j / 2 );
  19972. if ( j % 2 == 0 ) {
  19973. make(
  19974. v[ i ][ k + 1],
  19975. v[ i + 1 ][ k ],
  19976. v[ i ][ k ]
  19977. );
  19978. } else {
  19979. make(
  19980. v[ i ][ k + 1 ],
  19981. v[ i + 1][ k + 1],
  19982. v[ i + 1 ][ k ]
  19983. );
  19984. }
  19985. }
  19986. }
  19987. }
  19988. // Angle around the Y axis, counter-clockwise when looking from above.
  19989. function azimuth( vector ) {
  19990. return Math.atan2( vector.z, -vector.x );
  19991. }
  19992. // Angle above the XZ plane.
  19993. function inclination( vector ) {
  19994. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19995. }
  19996. // Texture fixing helper. Spheres have some odd behaviours.
  19997. function correctUV( uv, vector, azimuth ) {
  19998. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19999. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  20000. return uv.clone();
  20001. }
  20002. };
  20003. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20004. /**
  20005. * @author timothypratley / https://github.com/timothypratley
  20006. */
  20007. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20008. this.radius = radius;
  20009. this.detail = detail;
  20010. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20011. var vertices = [
  20012. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  20013. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  20014. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  20015. ];
  20016. var faces = [
  20017. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  20018. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  20019. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  20020. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  20021. ];
  20022. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20023. };
  20024. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20025. /**
  20026. * @author timothypratley / https://github.com/timothypratley
  20027. */
  20028. THREE.OctahedronGeometry = function ( radius, detail ) {
  20029. var vertices = [
  20030. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  20031. ];
  20032. var faces = [
  20033. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  20034. ];
  20035. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20036. };
  20037. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20038. /**
  20039. * @author timothypratley / https://github.com/timothypratley
  20040. */
  20041. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20042. var vertices = [
  20043. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  20044. ];
  20045. var faces = [
  20046. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  20047. ];
  20048. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20049. };
  20050. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20051. /**
  20052. * @author zz85 / https://github.com/zz85
  20053. * Parametric Surfaces Geometry
  20054. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20055. *
  20056. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  20057. *
  20058. */
  20059. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  20060. THREE.Geometry.call( this );
  20061. var verts = this.vertices;
  20062. var faces = this.faces;
  20063. var uvs = this.faceVertexUvs[ 0 ];
  20064. var i, il, j, p;
  20065. var u, v;
  20066. var stackCount = stacks + 1;
  20067. var sliceCount = slices + 1;
  20068. for ( i = 0; i <= stacks; i ++ ) {
  20069. v = i / stacks;
  20070. for ( j = 0; j <= slices; j ++ ) {
  20071. u = j / slices;
  20072. p = func( u, v );
  20073. verts.push( p );
  20074. }
  20075. }
  20076. var a, b, c, d;
  20077. var uva, uvb, uvc, uvd;
  20078. for ( i = 0; i < stacks; i ++ ) {
  20079. for ( j = 0; j < slices; j ++ ) {
  20080. a = i * sliceCount + j;
  20081. b = i * sliceCount + j + 1;
  20082. c = (i + 1) * sliceCount + j + 1;
  20083. d = (i + 1) * sliceCount + j;
  20084. uva = new THREE.Vector2( j / slices, i / stacks );
  20085. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20086. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20087. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20088. faces.push( new THREE.Face3( a, b, d ) );
  20089. uvs.push( [ uva, uvb, uvd ] );
  20090. faces.push( new THREE.Face3( b, c, d ) );
  20091. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  20092. }
  20093. }
  20094. // console.log(this);
  20095. // magic bullet
  20096. // var diff = this.mergeVertices();
  20097. // console.log('removed ', diff, ' vertices by merging');
  20098. this.computeCentroids();
  20099. this.computeFaceNormals();
  20100. this.computeVertexNormals();
  20101. };
  20102. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20103. /**
  20104. * @author sroucheray / http://sroucheray.org/
  20105. * @author mrdoob / http://mrdoob.com/
  20106. */
  20107. THREE.AxisHelper = function ( size ) {
  20108. size = size || 1;
  20109. var geometry = new THREE.Geometry();
  20110. geometry.vertices.push(
  20111. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  20112. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  20113. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  20114. );
  20115. geometry.colors.push(
  20116. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20117. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20118. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20119. );
  20120. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20121. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20122. };
  20123. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20124. /**
  20125. * @author WestLangley / http://github.com/WestLangley
  20126. * @author zz85 / http://github.com/zz85
  20127. * @author bhouston / http://exocortex.com
  20128. *
  20129. * Creates an arrow for visualizing directions
  20130. *
  20131. * Parameters:
  20132. * dir - Vector3
  20133. * origin - Vector3
  20134. * length - Number
  20135. * hex - color in hex value
  20136. */
  20137. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  20138. // dir is assumed to be normalized
  20139. THREE.Object3D.call( this );
  20140. if ( hex === undefined ) hex = 0xffff00;
  20141. if ( length === undefined ) length = 1;
  20142. this.position = origin;
  20143. var lineGeometry = new THREE.Geometry();
  20144. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20145. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20146. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20147. this.line.matrixAutoUpdate = false;
  20148. this.add( this.line );
  20149. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  20150. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, 0.875, 0 ) );
  20151. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20152. this.cone.matrixAutoUpdate = false;
  20153. this.add( this.cone );
  20154. this.setDirection( dir );
  20155. this.setLength( length );
  20156. };
  20157. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20158. THREE.ArrowHelper.prototype.setDirection = function () {
  20159. var axis = new THREE.Vector3();
  20160. var radians;
  20161. return function ( dir ) {
  20162. // dir is assumed to be normalized
  20163. if ( dir.y > 0.99999 ) {
  20164. this.quaternion.set( 0, 0, 0, 1 );
  20165. } else if ( dir.y < - 0.99999 ) {
  20166. this.quaternion.set( 1, 0, 0, 0 );
  20167. } else {
  20168. axis.set( dir.z, 0, - dir.x ).normalize();
  20169. radians = Math.acos( dir.y );
  20170. this.quaternion.setFromAxisAngle( axis, radians );
  20171. }
  20172. };
  20173. }();
  20174. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20175. this.scale.set( length, length, length );
  20176. };
  20177. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20178. this.line.material.color.setHex( hex );
  20179. this.cone.material.color.setHex( hex );
  20180. };
  20181. /**
  20182. * @author mrdoob / http://mrdoob.com/
  20183. */
  20184. THREE.BoxHelper = function ( object ) {
  20185. // 5____4
  20186. // 1/___0/|
  20187. // | 6__|_7
  20188. // 2/___3/
  20189. var vertices = [
  20190. new THREE.Vector3( 1, 1, 1 ),
  20191. new THREE.Vector3( - 1, 1, 1 ),
  20192. new THREE.Vector3( - 1, - 1, 1 ),
  20193. new THREE.Vector3( 1, - 1, 1 ),
  20194. new THREE.Vector3( 1, 1, - 1 ),
  20195. new THREE.Vector3( - 1, 1, - 1 ),
  20196. new THREE.Vector3( - 1, - 1, - 1 ),
  20197. new THREE.Vector3( 1, - 1, - 1 )
  20198. ];
  20199. this.vertices = vertices;
  20200. // TODO: Wouldn't be nice if Line had .segments?
  20201. var geometry = new THREE.Geometry();
  20202. geometry.vertices.push(
  20203. vertices[ 0 ], vertices[ 1 ],
  20204. vertices[ 1 ], vertices[ 2 ],
  20205. vertices[ 2 ], vertices[ 3 ],
  20206. vertices[ 3 ], vertices[ 0 ],
  20207. vertices[ 4 ], vertices[ 5 ],
  20208. vertices[ 5 ], vertices[ 6 ],
  20209. vertices[ 6 ], vertices[ 7 ],
  20210. vertices[ 7 ], vertices[ 4 ],
  20211. vertices[ 0 ], vertices[ 4 ],
  20212. vertices[ 1 ], vertices[ 5 ],
  20213. vertices[ 2 ], vertices[ 6 ],
  20214. vertices[ 3 ], vertices[ 7 ]
  20215. );
  20216. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20217. if ( object !== undefined ) {
  20218. this.update( object );
  20219. }
  20220. };
  20221. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20222. THREE.BoxHelper.prototype.update = function ( object ) {
  20223. var geometry = object.geometry;
  20224. if ( geometry.boundingBox === null ) {
  20225. geometry.computeBoundingBox();
  20226. }
  20227. var min = geometry.boundingBox.min;
  20228. var max = geometry.boundingBox.max;
  20229. var vertices = this.vertices;
  20230. vertices[ 0 ].set( max.x, max.y, max.z );
  20231. vertices[ 1 ].set( min.x, max.y, max.z );
  20232. vertices[ 2 ].set( min.x, min.y, max.z );
  20233. vertices[ 3 ].set( max.x, min.y, max.z );
  20234. vertices[ 4 ].set( max.x, max.y, min.z );
  20235. vertices[ 5 ].set( min.x, max.y, min.z );
  20236. vertices[ 6 ].set( min.x, min.y, min.z );
  20237. vertices[ 7 ].set( max.x, min.y, min.z );
  20238. this.geometry.computeBoundingSphere();
  20239. this.geometry.verticesNeedUpdate = true;
  20240. this.matrixAutoUpdate = false;
  20241. this.matrixWorld = object.matrixWorld;
  20242. };
  20243. /**
  20244. * @author WestLangley / http://github.com/WestLangley
  20245. */
  20246. // a helper to show the world-axis-aligned bounding box for an object
  20247. THREE.BoundingBoxHelper = function ( object, hex ) {
  20248. var color = hex || 0x888888;
  20249. this.object = object;
  20250. this.box = new THREE.Box3();
  20251. THREE.Mesh.call( this, new THREE.CubeGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20252. };
  20253. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20254. THREE.BoundingBoxHelper.prototype.update = function () {
  20255. this.box.setFromObject( this.object );
  20256. this.box.size( this.scale );
  20257. this.box.center( this.position );
  20258. };
  20259. /**
  20260. * @author alteredq / http://alteredqualia.com/
  20261. *
  20262. * - shows frustum, line of sight and up of the camera
  20263. * - suitable for fast updates
  20264. * - based on frustum visualization in lightgl.js shadowmap example
  20265. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20266. */
  20267. THREE.CameraHelper = function ( camera ) {
  20268. var geometry = new THREE.Geometry();
  20269. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20270. var pointMap = {};
  20271. // colors
  20272. var hexFrustum = 0xffaa00;
  20273. var hexCone = 0xff0000;
  20274. var hexUp = 0x00aaff;
  20275. var hexTarget = 0xffffff;
  20276. var hexCross = 0x333333;
  20277. // near
  20278. addLine( "n1", "n2", hexFrustum );
  20279. addLine( "n2", "n4", hexFrustum );
  20280. addLine( "n4", "n3", hexFrustum );
  20281. addLine( "n3", "n1", hexFrustum );
  20282. // far
  20283. addLine( "f1", "f2", hexFrustum );
  20284. addLine( "f2", "f4", hexFrustum );
  20285. addLine( "f4", "f3", hexFrustum );
  20286. addLine( "f3", "f1", hexFrustum );
  20287. // sides
  20288. addLine( "n1", "f1", hexFrustum );
  20289. addLine( "n2", "f2", hexFrustum );
  20290. addLine( "n3", "f3", hexFrustum );
  20291. addLine( "n4", "f4", hexFrustum );
  20292. // cone
  20293. addLine( "p", "n1", hexCone );
  20294. addLine( "p", "n2", hexCone );
  20295. addLine( "p", "n3", hexCone );
  20296. addLine( "p", "n4", hexCone );
  20297. // up
  20298. addLine( "u1", "u2", hexUp );
  20299. addLine( "u2", "u3", hexUp );
  20300. addLine( "u3", "u1", hexUp );
  20301. // target
  20302. addLine( "c", "t", hexTarget );
  20303. addLine( "p", "c", hexCross );
  20304. // cross
  20305. addLine( "cn1", "cn2", hexCross );
  20306. addLine( "cn3", "cn4", hexCross );
  20307. addLine( "cf1", "cf2", hexCross );
  20308. addLine( "cf3", "cf4", hexCross );
  20309. function addLine( a, b, hex ) {
  20310. addPoint( a, hex );
  20311. addPoint( b, hex );
  20312. }
  20313. function addPoint( id, hex ) {
  20314. geometry.vertices.push( new THREE.Vector3() );
  20315. geometry.colors.push( new THREE.Color( hex ) );
  20316. if ( pointMap[ id ] === undefined ) {
  20317. pointMap[ id ] = [];
  20318. }
  20319. pointMap[ id ].push( geometry.vertices.length - 1 );
  20320. }
  20321. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20322. this.camera = camera;
  20323. this.matrixWorld = camera.matrixWorld;
  20324. this.matrixAutoUpdate = false;
  20325. this.pointMap = pointMap;
  20326. this.update();
  20327. };
  20328. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20329. THREE.CameraHelper.prototype.update = function () {
  20330. var vector = new THREE.Vector3();
  20331. var camera = new THREE.Camera();
  20332. var projector = new THREE.Projector();
  20333. return function () {
  20334. var scope = this;
  20335. var w = 1, h = 1;
  20336. // we need just camera projection matrix
  20337. // world matrix must be identity
  20338. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20339. // center / target
  20340. setPoint( "c", 0, 0, -1 );
  20341. setPoint( "t", 0, 0, 1 );
  20342. // near
  20343. setPoint( "n1", -w, -h, -1 );
  20344. setPoint( "n2", w, -h, -1 );
  20345. setPoint( "n3", -w, h, -1 );
  20346. setPoint( "n4", w, h, -1 );
  20347. // far
  20348. setPoint( "f1", -w, -h, 1 );
  20349. setPoint( "f2", w, -h, 1 );
  20350. setPoint( "f3", -w, h, 1 );
  20351. setPoint( "f4", w, h, 1 );
  20352. // up
  20353. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20354. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20355. setPoint( "u3", 0, h * 2, -1 );
  20356. // cross
  20357. setPoint( "cf1", -w, 0, 1 );
  20358. setPoint( "cf2", w, 0, 1 );
  20359. setPoint( "cf3", 0, -h, 1 );
  20360. setPoint( "cf4", 0, h, 1 );
  20361. setPoint( "cn1", -w, 0, -1 );
  20362. setPoint( "cn2", w, 0, -1 );
  20363. setPoint( "cn3", 0, -h, -1 );
  20364. setPoint( "cn4", 0, h, -1 );
  20365. function setPoint( point, x, y, z ) {
  20366. vector.set( x, y, z );
  20367. projector.unprojectVector( vector, camera );
  20368. var points = scope.pointMap[ point ];
  20369. if ( points !== undefined ) {
  20370. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20371. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20372. }
  20373. }
  20374. }
  20375. this.geometry.verticesNeedUpdate = true;
  20376. };
  20377. }();
  20378. /**
  20379. * @author alteredq / http://alteredqualia.com/
  20380. * @author mrdoob / http://mrdoob.com/
  20381. * @author WestLangley / http://github.com/WestLangley
  20382. */
  20383. THREE.DirectionalLightHelper = function ( light, size ) {
  20384. THREE.Object3D.call( this );
  20385. this.light = light;
  20386. this.light.updateMatrixWorld();
  20387. this.matrixWorld = light.matrixWorld;
  20388. this.matrixAutoUpdate = false;
  20389. size = size || 1;
  20390. var geometry = new THREE.PlaneGeometry( size, size );
  20391. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20392. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20393. this.lightPlane = new THREE.Mesh( geometry, material );
  20394. this.add( this.lightPlane );
  20395. geometry = new THREE.Geometry();
  20396. geometry.vertices.push( new THREE.Vector3() );
  20397. geometry.vertices.push( new THREE.Vector3() );
  20398. material = new THREE.LineBasicMaterial( { fog: false } );
  20399. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20400. this.targetLine = new THREE.Line( geometry, material );
  20401. this.add( this.targetLine );
  20402. this.update();
  20403. };
  20404. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20405. THREE.DirectionalLightHelper.prototype.dispose = function () {
  20406. this.lightPlane.geometry.dispose();
  20407. this.lightPlane.material.dispose();
  20408. this.targetLine.geometry.dispose();
  20409. this.targetLine.material.dispose();
  20410. };
  20411. THREE.DirectionalLightHelper.prototype.update = function () {
  20412. var v1 = new THREE.Vector3();
  20413. var v2 = new THREE.Vector3();
  20414. var v3 = new THREE.Vector3();
  20415. return function () {
  20416. v1.getPositionFromMatrix( this.light.matrixWorld );
  20417. v2.getPositionFromMatrix( this.light.target.matrixWorld );
  20418. v3.subVectors( v2, v1 );
  20419. this.lightPlane.lookAt( v3 );
  20420. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20421. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  20422. this.targetLine.geometry.verticesNeedUpdate = true;
  20423. this.targetLine.material.color.copy( this.lightPlane.material.color );
  20424. }
  20425. }();
  20426. /**
  20427. * @author mrdoob / http://mrdoob.com/
  20428. * @author WestLangley / http://github.com/WestLangley
  20429. */
  20430. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20431. this.object = object;
  20432. this.size = size || 1;
  20433. var color = hex || 0xffff00;
  20434. var width = linewidth || 1;
  20435. var geometry = new THREE.Geometry();
  20436. var faces = this.object.geometry.faces;
  20437. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20438. geometry.vertices.push( new THREE.Vector3() );
  20439. geometry.vertices.push( new THREE.Vector3() );
  20440. }
  20441. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20442. this.matrixAutoUpdate = false;
  20443. this.normalMatrix = new THREE.Matrix3();
  20444. this.update();
  20445. };
  20446. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20447. THREE.FaceNormalsHelper.prototype.update = ( function ( object ) {
  20448. var v1 = new THREE.Vector3();
  20449. return function ( object ) {
  20450. this.object.updateMatrixWorld( true );
  20451. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20452. var vertices = this.geometry.vertices;
  20453. var faces = this.object.geometry.faces;
  20454. var worldMatrix = this.object.matrixWorld;
  20455. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20456. var face = faces[ i ];
  20457. v1.copy( face.normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20458. var idx = 2 * i;
  20459. vertices[ idx ].copy( face.centroid ).applyMatrix4( worldMatrix );
  20460. vertices[ idx + 1 ].addVectors( vertices[ idx ], v1 );
  20461. }
  20462. this.geometry.verticesNeedUpdate = true;
  20463. return this;
  20464. }
  20465. }());
  20466. /**
  20467. * @author mrdoob / http://mrdoob.com/
  20468. */
  20469. THREE.GridHelper = function ( size, step ) {
  20470. var geometry = new THREE.Geometry();
  20471. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20472. this.color1 = new THREE.Color( 0x444444 );
  20473. this.color2 = new THREE.Color( 0x888888 );
  20474. for ( var i = - size; i <= size; i += step ) {
  20475. geometry.vertices.push(
  20476. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  20477. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  20478. );
  20479. var color = i === 0 ? this.color1 : this.color2;
  20480. geometry.colors.push( color, color, color, color );
  20481. }
  20482. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20483. };
  20484. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  20485. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  20486. this.color1.set( colorCenterLine );
  20487. this.color2.set( colorGrid );
  20488. this.geometry.colorsNeedUpdate = true;
  20489. }
  20490. /**
  20491. * @author alteredq / http://alteredqualia.com/
  20492. * @author mrdoob / http://mrdoob.com/
  20493. */
  20494. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20495. THREE.Object3D.call( this );
  20496. this.light = light;
  20497. this.light.updateMatrixWorld();
  20498. this.matrixWorld = light.matrixWorld;
  20499. this.matrixAutoUpdate = false;
  20500. this.colors = [ new THREE.Color(), new THREE.Color() ];
  20501. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20502. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20503. for ( var i = 0, il = 8; i < il; i ++ ) {
  20504. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  20505. }
  20506. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  20507. this.lightSphere = new THREE.Mesh( geometry, material );
  20508. this.add( this.lightSphere );
  20509. this.update();
  20510. };
  20511. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20512. THREE.HemisphereLightHelper.prototype.dispose = function () {
  20513. this.lightSphere.geometry.dispose();
  20514. this.lightSphere.material.dispose();
  20515. };
  20516. THREE.HemisphereLightHelper.prototype.update = function () {
  20517. var vector = new THREE.Vector3();
  20518. return function () {
  20519. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  20520. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  20521. this.lightSphere.lookAt( vector.getPositionFromMatrix( this.light.matrixWorld ).negate() );
  20522. this.lightSphere.geometry.colorsNeedUpdate = true;
  20523. }
  20524. }();
  20525. /**
  20526. * @author alteredq / http://alteredqualia.com/
  20527. * @author mrdoob / http://mrdoob.com/
  20528. */
  20529. THREE.PointLightHelper = function ( light, sphereSize ) {
  20530. this.light = light;
  20531. this.light.updateMatrixWorld();
  20532. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20533. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20534. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20535. THREE.Mesh.call( this, geometry, material );
  20536. this.matrixWorld = this.light.matrixWorld;
  20537. this.matrixAutoUpdate = false;
  20538. /*
  20539. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20540. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20541. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20542. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20543. var d = light.distance;
  20544. if ( d === 0.0 ) {
  20545. this.lightDistance.visible = false;
  20546. } else {
  20547. this.lightDistance.scale.set( d, d, d );
  20548. }
  20549. this.add( this.lightDistance );
  20550. */
  20551. };
  20552. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  20553. THREE.PointLightHelper.prototype.dispose = function () {
  20554. this.geometry.dispose();
  20555. this.material.dispose();
  20556. };
  20557. THREE.PointLightHelper.prototype.update = function () {
  20558. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20559. /*
  20560. var d = this.light.distance;
  20561. if ( d === 0.0 ) {
  20562. this.lightDistance.visible = false;
  20563. } else {
  20564. this.lightDistance.visible = true;
  20565. this.lightDistance.scale.set( d, d, d );
  20566. }
  20567. */
  20568. };
  20569. /**
  20570. * @author alteredq / http://alteredqualia.com/
  20571. * @author mrdoob / http://mrdoob.com/
  20572. * @author WestLangley / http://github.com/WestLangley
  20573. */
  20574. THREE.SpotLightHelper = function ( light ) {
  20575. THREE.Object3D.call( this );
  20576. this.light = light;
  20577. this.light.updateMatrixWorld();
  20578. this.matrixWorld = light.matrixWorld;
  20579. this.matrixAutoUpdate = false;
  20580. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  20581. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  20582. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20583. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20584. this.cone = new THREE.Mesh( geometry, material );
  20585. this.add( this.cone );
  20586. this.update();
  20587. };
  20588. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20589. THREE.SpotLightHelper.prototype.dispose = function () {
  20590. this.cone.geometry.dispose();
  20591. this.cone.material.dispose();
  20592. };
  20593. THREE.SpotLightHelper.prototype.update = function () {
  20594. var vector = new THREE.Vector3();
  20595. var vector2 = new THREE.Vector3();
  20596. return function () {
  20597. var coneLength = this.light.distance ? this.light.distance : 10000;
  20598. var coneWidth = coneLength * Math.tan( this.light.angle );
  20599. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20600. vector.getPositionFromMatrix( this.light.matrixWorld );
  20601. vector2.getPositionFromMatrix( this.light.target.matrixWorld );
  20602. this.cone.lookAt( vector2.sub( vector ) );
  20603. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20604. };
  20605. }();
  20606. /**
  20607. * @author mrdoob / http://mrdoob.com/
  20608. * @author WestLangley / http://github.com/WestLangley
  20609. */
  20610. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  20611. this.object = object;
  20612. this.size = size || 1;
  20613. var color = hex || 0xff0000;
  20614. var width = linewidth || 1;
  20615. var geometry = new THREE.Geometry();
  20616. var vertices = object.geometry.vertices;
  20617. var faces = object.geometry.faces;
  20618. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20619. var face = faces[ i ];
  20620. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20621. geometry.vertices.push( new THREE.Vector3() );
  20622. geometry.vertices.push( new THREE.Vector3() );
  20623. }
  20624. }
  20625. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20626. this.matrixAutoUpdate = false;
  20627. this.normalMatrix = new THREE.Matrix3();
  20628. this.update();
  20629. };
  20630. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20631. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  20632. var v1 = new THREE.Vector3();
  20633. return function( object ) {
  20634. var keys = [ 'a', 'b', 'c', 'd' ];
  20635. this.object.updateMatrixWorld( true );
  20636. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20637. var vertices = this.geometry.vertices;
  20638. var verts = this.object.geometry.vertices;
  20639. var faces = this.object.geometry.faces;
  20640. var worldMatrix = this.object.matrixWorld;
  20641. var idx = 0;
  20642. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20643. var face = faces[ i ];
  20644. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20645. var vertexId = face[ keys[ j ] ];
  20646. var vertex = verts[ vertexId ];
  20647. var normal = face.vertexNormals[ j ];
  20648. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20649. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20650. v1.add( vertices[ idx ] );
  20651. idx = idx + 1;
  20652. vertices[ idx ].copy( v1 );
  20653. idx = idx + 1;
  20654. }
  20655. }
  20656. this.geometry.verticesNeedUpdate = true;
  20657. return this;
  20658. }
  20659. }());
  20660. /**
  20661. * @author mrdoob / http://mrdoob.com/
  20662. * @author WestLangley / http://github.com/WestLangley
  20663. */
  20664. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  20665. this.object = object;
  20666. this.size = size || 1;
  20667. var color = hex || 0x0000ff;
  20668. var width = linewidth || 1;
  20669. var geometry = new THREE.Geometry();
  20670. var vertices = object.geometry.vertices;
  20671. var faces = object.geometry.faces;
  20672. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20673. var face = faces[ i ];
  20674. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20675. geometry.vertices.push( new THREE.Vector3() );
  20676. geometry.vertices.push( new THREE.Vector3() );
  20677. }
  20678. }
  20679. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20680. this.matrixAutoUpdate = false;
  20681. this.update();
  20682. };
  20683. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  20684. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  20685. var v1 = new THREE.Vector3();
  20686. return function( object ) {
  20687. var keys = [ 'a', 'b', 'c', 'd' ];
  20688. this.object.updateMatrixWorld( true );
  20689. var vertices = this.geometry.vertices;
  20690. var verts = this.object.geometry.vertices;
  20691. var faces = this.object.geometry.faces;
  20692. var worldMatrix = this.object.matrixWorld;
  20693. var idx = 0;
  20694. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20695. var face = faces[ i ];
  20696. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20697. var vertexId = face[ keys[ j ] ];
  20698. var vertex = verts[ vertexId ];
  20699. var tangent = face.vertexTangents[ j ];
  20700. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20701. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  20702. v1.add( vertices[ idx ] );
  20703. idx = idx + 1;
  20704. vertices[ idx ].copy( v1 );
  20705. idx = idx + 1;
  20706. }
  20707. }
  20708. this.geometry.verticesNeedUpdate = true;
  20709. return this;
  20710. }
  20711. }());
  20712. /**
  20713. * @author mrdoob / http://mrdoob.com/
  20714. */
  20715. THREE.WireframeHelper = function ( object ) {
  20716. var edge = [ 0, 0 ], hash = {};
  20717. var sortFunction = function ( a, b ) { return a - b };
  20718. var keys = [ 'a', 'b', 'c', 'd' ];
  20719. var geometry = new THREE.Geometry();
  20720. var vertices = object.geometry.vertices;
  20721. var faces = object.geometry.faces;
  20722. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20723. var face = faces[ i ];
  20724. for ( var j = 0; j < 3; j ++ ) {
  20725. edge[ 0 ] = face[ keys[ j ] ];
  20726. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20727. edge.sort( sortFunction );
  20728. var key = edge.toString();
  20729. if ( hash[ key ] === undefined ) {
  20730. geometry.vertices.push( vertices[ edge[ 0 ] ] );
  20731. geometry.vertices.push( vertices[ edge[ 1 ] ] );
  20732. hash[ key ] = true;
  20733. }
  20734. }
  20735. }
  20736. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffffff } ), THREE.LinePieces );
  20737. this.matrixAutoUpdate = false;
  20738. this.matrixWorld = object.matrixWorld;
  20739. };
  20740. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  20741. /**
  20742. * @author alteredq / http://alteredqualia.com/
  20743. */
  20744. THREE.ImmediateRenderObject = function () {
  20745. THREE.Object3D.call( this );
  20746. this.render = function ( renderCallback ) { };
  20747. };
  20748. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20749. /**
  20750. * @author mikael emtinger / http://gomo.se/
  20751. * @author alteredq / http://alteredqualia.com/
  20752. */
  20753. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20754. THREE.Object3D.call( this );
  20755. this.lensFlares = [];
  20756. this.positionScreen = new THREE.Vector3();
  20757. this.customUpdateCallback = undefined;
  20758. if( texture !== undefined ) {
  20759. this.add( texture, size, distance, blending, color );
  20760. }
  20761. };
  20762. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20763. /*
  20764. * Add: adds another flare
  20765. */
  20766. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20767. if( size === undefined ) size = -1;
  20768. if( distance === undefined ) distance = 0;
  20769. if( opacity === undefined ) opacity = 1;
  20770. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20771. if( blending === undefined ) blending = THREE.NormalBlending;
  20772. distance = Math.min( distance, Math.max( 0, distance ) );
  20773. this.lensFlares.push( { texture: texture, // THREE.Texture
  20774. size: size, // size in pixels (-1 = use texture.width)
  20775. distance: distance, // distance (0-1) from light source (0=at light source)
  20776. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20777. scale: 1, // scale
  20778. rotation: 1, // rotation
  20779. opacity: opacity, // opacity
  20780. color: color, // color
  20781. blending: blending } ); // blending
  20782. };
  20783. /*
  20784. * Update lens flares update positions on all flares based on the screen position
  20785. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20786. */
  20787. THREE.LensFlare.prototype.updateLensFlares = function () {
  20788. var f, fl = this.lensFlares.length;
  20789. var flare;
  20790. var vecX = -this.positionScreen.x * 2;
  20791. var vecY = -this.positionScreen.y * 2;
  20792. for( f = 0; f < fl; f ++ ) {
  20793. flare = this.lensFlares[ f ];
  20794. flare.x = this.positionScreen.x + vecX * flare.distance;
  20795. flare.y = this.positionScreen.y + vecY * flare.distance;
  20796. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20797. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20798. }
  20799. };
  20800. /**
  20801. * @author alteredq / http://alteredqualia.com/
  20802. */
  20803. THREE.MorphBlendMesh = function( geometry, material ) {
  20804. THREE.Mesh.call( this, geometry, material );
  20805. this.animationsMap = {};
  20806. this.animationsList = [];
  20807. // prepare default animation
  20808. // (all frames played together in 1 second)
  20809. var numFrames = this.geometry.morphTargets.length;
  20810. var name = "__default";
  20811. var startFrame = 0;
  20812. var endFrame = numFrames - 1;
  20813. var fps = numFrames / 1;
  20814. this.createAnimation( name, startFrame, endFrame, fps );
  20815. this.setAnimationWeight( name, 1 );
  20816. };
  20817. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20818. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20819. var animation = {
  20820. startFrame: start,
  20821. endFrame: end,
  20822. length: end - start + 1,
  20823. fps: fps,
  20824. duration: ( end - start ) / fps,
  20825. lastFrame: 0,
  20826. currentFrame: 0,
  20827. active: false,
  20828. time: 0,
  20829. direction: 1,
  20830. weight: 1,
  20831. directionBackwards: false,
  20832. mirroredLoop: false
  20833. };
  20834. this.animationsMap[ name ] = animation;
  20835. this.animationsList.push( animation );
  20836. };
  20837. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20838. var pattern = /([a-z]+)(\d+)/;
  20839. var firstAnimation, frameRanges = {};
  20840. var geometry = this.geometry;
  20841. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20842. var morph = geometry.morphTargets[ i ];
  20843. var chunks = morph.name.match( pattern );
  20844. if ( chunks && chunks.length > 1 ) {
  20845. var name = chunks[ 1 ];
  20846. var num = chunks[ 2 ];
  20847. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20848. var range = frameRanges[ name ];
  20849. if ( i < range.start ) range.start = i;
  20850. if ( i > range.end ) range.end = i;
  20851. if ( ! firstAnimation ) firstAnimation = name;
  20852. }
  20853. }
  20854. for ( var name in frameRanges ) {
  20855. var range = frameRanges[ name ];
  20856. this.createAnimation( name, range.start, range.end, fps );
  20857. }
  20858. this.firstAnimation = firstAnimation;
  20859. };
  20860. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20861. var animation = this.animationsMap[ name ];
  20862. if ( animation ) {
  20863. animation.direction = 1;
  20864. animation.directionBackwards = false;
  20865. }
  20866. };
  20867. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20868. var animation = this.animationsMap[ name ];
  20869. if ( animation ) {
  20870. animation.direction = -1;
  20871. animation.directionBackwards = true;
  20872. }
  20873. };
  20874. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20875. var animation = this.animationsMap[ name ];
  20876. if ( animation ) {
  20877. animation.fps = fps;
  20878. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20879. }
  20880. };
  20881. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20882. var animation = this.animationsMap[ name ];
  20883. if ( animation ) {
  20884. animation.duration = duration;
  20885. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20886. }
  20887. };
  20888. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20889. var animation = this.animationsMap[ name ];
  20890. if ( animation ) {
  20891. animation.weight = weight;
  20892. }
  20893. };
  20894. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20895. var animation = this.animationsMap[ name ];
  20896. if ( animation ) {
  20897. animation.time = time;
  20898. }
  20899. };
  20900. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20901. var time = 0;
  20902. var animation = this.animationsMap[ name ];
  20903. if ( animation ) {
  20904. time = animation.time;
  20905. }
  20906. return time;
  20907. };
  20908. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20909. var duration = -1;
  20910. var animation = this.animationsMap[ name ];
  20911. if ( animation ) {
  20912. duration = animation.duration;
  20913. }
  20914. return duration;
  20915. };
  20916. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20917. var animation = this.animationsMap[ name ];
  20918. if ( animation ) {
  20919. animation.time = 0;
  20920. animation.active = true;
  20921. } else {
  20922. console.warn( "animation[" + name + "] undefined" );
  20923. }
  20924. };
  20925. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20926. var animation = this.animationsMap[ name ];
  20927. if ( animation ) {
  20928. animation.active = false;
  20929. }
  20930. };
  20931. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20932. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20933. var animation = this.animationsList[ i ];
  20934. if ( ! animation.active ) continue;
  20935. var frameTime = animation.duration / animation.length;
  20936. animation.time += animation.direction * delta;
  20937. if ( animation.mirroredLoop ) {
  20938. if ( animation.time > animation.duration || animation.time < 0 ) {
  20939. animation.direction *= -1;
  20940. if ( animation.time > animation.duration ) {
  20941. animation.time = animation.duration;
  20942. animation.directionBackwards = true;
  20943. }
  20944. if ( animation.time < 0 ) {
  20945. animation.time = 0;
  20946. animation.directionBackwards = false;
  20947. }
  20948. }
  20949. } else {
  20950. animation.time = animation.time % animation.duration;
  20951. if ( animation.time < 0 ) animation.time += animation.duration;
  20952. }
  20953. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20954. var weight = animation.weight;
  20955. if ( keyframe !== animation.currentFrame ) {
  20956. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20957. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20958. this.morphTargetInfluences[ keyframe ] = 0;
  20959. animation.lastFrame = animation.currentFrame;
  20960. animation.currentFrame = keyframe;
  20961. }
  20962. var mix = ( animation.time % frameTime ) / frameTime;
  20963. if ( animation.directionBackwards ) mix = 1 - mix;
  20964. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20965. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20966. }
  20967. };
  20968. /**
  20969. * @author mikael emtinger / http://gomo.se/
  20970. * @author alteredq / http://alteredqualia.com/
  20971. */
  20972. THREE.LensFlarePlugin = function () {
  20973. var _gl, _renderer, _precision, _lensFlare = {};
  20974. this.init = function ( renderer ) {
  20975. _gl = renderer.context;
  20976. _renderer = renderer;
  20977. _precision = renderer.getPrecision();
  20978. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20979. _lensFlare.faces = new Uint16Array( 6 );
  20980. var i = 0;
  20981. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20982. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20983. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20984. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20985. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20986. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20987. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20988. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20989. i = 0;
  20990. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20991. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20992. // buffers
  20993. _lensFlare.vertexBuffer = _gl.createBuffer();
  20994. _lensFlare.elementBuffer = _gl.createBuffer();
  20995. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20996. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20997. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20998. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20999. // textures
  21000. _lensFlare.tempTexture = _gl.createTexture();
  21001. _lensFlare.occlusionTexture = _gl.createTexture();
  21002. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21003. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21004. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21005. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21006. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21007. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21008. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21009. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21010. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21011. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21012. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21013. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21014. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21015. _lensFlare.hasVertexTexture = false;
  21016. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21017. } else {
  21018. _lensFlare.hasVertexTexture = true;
  21019. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21020. }
  21021. _lensFlare.attributes = {};
  21022. _lensFlare.uniforms = {};
  21023. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21024. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21025. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21026. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21027. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21028. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21029. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21030. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21031. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21032. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21033. };
  21034. /*
  21035. * Render lens flares
  21036. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21037. * reads these back and calculates occlusion.
  21038. * Then _lensFlare.update_lensFlares() is called to re-position and
  21039. * update transparency of flares. Then they are rendered.
  21040. *
  21041. */
  21042. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21043. var flares = scene.__webglFlares,
  21044. nFlares = flares.length;
  21045. if ( ! nFlares ) return;
  21046. var tempPosition = new THREE.Vector3();
  21047. var invAspect = viewportHeight / viewportWidth,
  21048. halfViewportWidth = viewportWidth * 0.5,
  21049. halfViewportHeight = viewportHeight * 0.5;
  21050. var size = 16 / viewportHeight,
  21051. scale = new THREE.Vector2( size * invAspect, size );
  21052. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21053. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21054. var uniforms = _lensFlare.uniforms,
  21055. attributes = _lensFlare.attributes;
  21056. // set _lensFlare program and reset blending
  21057. _gl.useProgram( _lensFlare.program );
  21058. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21059. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21060. // loop through all lens flares to update their occlusion and positions
  21061. // setup gl and common used attribs/unforms
  21062. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21063. _gl.uniform1i( uniforms.map, 1 );
  21064. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21065. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21066. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21067. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21068. _gl.disable( _gl.CULL_FACE );
  21069. _gl.depthMask( false );
  21070. var i, j, jl, flare, sprite;
  21071. for ( i = 0; i < nFlares; i ++ ) {
  21072. size = 16 / viewportHeight;
  21073. scale.set( size * invAspect, size );
  21074. // calc object screen position
  21075. flare = flares[ i ];
  21076. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21077. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21078. tempPosition.applyProjection( camera.projectionMatrix );
  21079. // setup arrays for gl programs
  21080. screenPosition.copy( tempPosition )
  21081. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21082. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21083. // screen cull
  21084. if ( _lensFlare.hasVertexTexture || (
  21085. screenPositionPixels.x > 0 &&
  21086. screenPositionPixels.x < viewportWidth &&
  21087. screenPositionPixels.y > 0 &&
  21088. screenPositionPixels.y < viewportHeight ) ) {
  21089. // save current RGB to temp texture
  21090. _gl.activeTexture( _gl.TEXTURE1 );
  21091. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21092. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21093. // render pink quad
  21094. _gl.uniform1i( uniforms.renderType, 0 );
  21095. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21096. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21097. _gl.disable( _gl.BLEND );
  21098. _gl.enable( _gl.DEPTH_TEST );
  21099. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21100. // copy result to occlusionMap
  21101. _gl.activeTexture( _gl.TEXTURE0 );
  21102. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21103. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21104. // restore graphics
  21105. _gl.uniform1i( uniforms.renderType, 1 );
  21106. _gl.disable( _gl.DEPTH_TEST );
  21107. _gl.activeTexture( _gl.TEXTURE1 );
  21108. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21109. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21110. // update object positions
  21111. flare.positionScreen.copy( screenPosition )
  21112. if ( flare.customUpdateCallback ) {
  21113. flare.customUpdateCallback( flare );
  21114. } else {
  21115. flare.updateLensFlares();
  21116. }
  21117. // render flares
  21118. _gl.uniform1i( uniforms.renderType, 2 );
  21119. _gl.enable( _gl.BLEND );
  21120. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21121. sprite = flare.lensFlares[ j ];
  21122. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21123. screenPosition.x = sprite.x;
  21124. screenPosition.y = sprite.y;
  21125. screenPosition.z = sprite.z;
  21126. size = sprite.size * sprite.scale / viewportHeight;
  21127. scale.x = size * invAspect;
  21128. scale.y = size;
  21129. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21130. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21131. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21132. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21133. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21134. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21135. _renderer.setTexture( sprite.texture, 1 );
  21136. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21137. }
  21138. }
  21139. }
  21140. }
  21141. // restore gl
  21142. _gl.enable( _gl.CULL_FACE );
  21143. _gl.enable( _gl.DEPTH_TEST );
  21144. _gl.depthMask( true );
  21145. };
  21146. function createProgram ( shader, precision ) {
  21147. var program = _gl.createProgram();
  21148. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21149. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21150. var prefix = "precision " + precision + " float;\n";
  21151. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21152. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21153. _gl.compileShader( fragmentShader );
  21154. _gl.compileShader( vertexShader );
  21155. _gl.attachShader( program, fragmentShader );
  21156. _gl.attachShader( program, vertexShader );
  21157. _gl.linkProgram( program );
  21158. return program;
  21159. };
  21160. };
  21161. /**
  21162. * @author alteredq / http://alteredqualia.com/
  21163. */
  21164. THREE.ShadowMapPlugin = function () {
  21165. var _gl,
  21166. _renderer,
  21167. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21168. _frustum = new THREE.Frustum(),
  21169. _projScreenMatrix = new THREE.Matrix4(),
  21170. _min = new THREE.Vector3(),
  21171. _max = new THREE.Vector3(),
  21172. _matrixPosition = new THREE.Vector3();
  21173. this.init = function ( renderer ) {
  21174. _gl = renderer.context;
  21175. _renderer = renderer;
  21176. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21177. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21178. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21179. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21180. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21181. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21182. _depthMaterial._shadowPass = true;
  21183. _depthMaterialMorph._shadowPass = true;
  21184. _depthMaterialSkin._shadowPass = true;
  21185. _depthMaterialMorphSkin._shadowPass = true;
  21186. };
  21187. this.render = function ( scene, camera ) {
  21188. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21189. this.update( scene, camera );
  21190. };
  21191. this.update = function ( scene, camera ) {
  21192. var i, il, j, jl, n,
  21193. shadowMap, shadowMatrix, shadowCamera,
  21194. program, buffer, material,
  21195. webglObject, object, light,
  21196. renderList,
  21197. lights = [],
  21198. k = 0,
  21199. fog = null;
  21200. // set GL state for depth map
  21201. _gl.clearColor( 1, 1, 1, 1 );
  21202. _gl.disable( _gl.BLEND );
  21203. _gl.enable( _gl.CULL_FACE );
  21204. _gl.frontFace( _gl.CCW );
  21205. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21206. _gl.cullFace( _gl.FRONT );
  21207. } else {
  21208. _gl.cullFace( _gl.BACK );
  21209. }
  21210. _renderer.setDepthTest( true );
  21211. // preprocess lights
  21212. // - skip lights that are not casting shadows
  21213. // - create virtual lights for cascaded shadow maps
  21214. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21215. light = scene.__lights[ i ];
  21216. if ( ! light.castShadow ) continue;
  21217. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21218. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21219. var virtualLight;
  21220. if ( ! light.shadowCascadeArray[ n ] ) {
  21221. virtualLight = createVirtualLight( light, n );
  21222. virtualLight.originalCamera = camera;
  21223. var gyro = new THREE.Gyroscope();
  21224. gyro.position = light.shadowCascadeOffset;
  21225. gyro.add( virtualLight );
  21226. gyro.add( virtualLight.target );
  21227. camera.add( gyro );
  21228. light.shadowCascadeArray[ n ] = virtualLight;
  21229. console.log( "Created virtualLight", virtualLight );
  21230. } else {
  21231. virtualLight = light.shadowCascadeArray[ n ];
  21232. }
  21233. updateVirtualLight( light, n );
  21234. lights[ k ] = virtualLight;
  21235. k ++;
  21236. }
  21237. } else {
  21238. lights[ k ] = light;
  21239. k ++;
  21240. }
  21241. }
  21242. // render depth map
  21243. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21244. light = lights[ i ];
  21245. if ( ! light.shadowMap ) {
  21246. var shadowFilter = THREE.LinearFilter;
  21247. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21248. shadowFilter = THREE.NearestFilter;
  21249. }
  21250. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21251. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21252. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21253. light.shadowMatrix = new THREE.Matrix4();
  21254. }
  21255. if ( ! light.shadowCamera ) {
  21256. if ( light instanceof THREE.SpotLight ) {
  21257. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21258. } else if ( light instanceof THREE.DirectionalLight ) {
  21259. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21260. } else {
  21261. console.error( "Unsupported light type for shadow" );
  21262. continue;
  21263. }
  21264. scene.add( light.shadowCamera );
  21265. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21266. }
  21267. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21268. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21269. light.shadowCamera.add( light.cameraHelper );
  21270. }
  21271. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21272. updateShadowCamera( camera, light );
  21273. }
  21274. shadowMap = light.shadowMap;
  21275. shadowMatrix = light.shadowMatrix;
  21276. shadowCamera = light.shadowCamera;
  21277. shadowCamera.position.getPositionFromMatrix( light.matrixWorld );
  21278. _matrixPosition.getPositionFromMatrix( light.target.matrixWorld );
  21279. shadowCamera.lookAt( _matrixPosition );
  21280. shadowCamera.updateMatrixWorld();
  21281. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21282. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21283. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21284. // compute shadow matrix
  21285. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21286. 0.0, 0.5, 0.0, 0.5,
  21287. 0.0, 0.0, 0.5, 0.5,
  21288. 0.0, 0.0, 0.0, 1.0 );
  21289. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21290. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21291. // update camera matrices and frustum
  21292. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21293. _frustum.setFromMatrix( _projScreenMatrix );
  21294. // render shadow map
  21295. _renderer.setRenderTarget( shadowMap );
  21296. _renderer.clear();
  21297. // set object matrices & frustum culling
  21298. renderList = scene.__webglObjects;
  21299. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21300. webglObject = renderList[ j ];
  21301. object = webglObject.object;
  21302. webglObject.render = false;
  21303. if ( object.visible && object.castShadow ) {
  21304. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21305. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21306. webglObject.render = true;
  21307. }
  21308. }
  21309. }
  21310. // render regular objects
  21311. var objectMaterial, useMorphing, useSkinning;
  21312. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21313. webglObject = renderList[ j ];
  21314. if ( webglObject.render ) {
  21315. object = webglObject.object;
  21316. buffer = webglObject.buffer;
  21317. // culling is overriden globally for all objects
  21318. // while rendering depth map
  21319. // need to deal with MeshFaceMaterial somehow
  21320. // in that case just use the first of material.materials for now
  21321. // (proper solution would require to break objects by materials
  21322. // similarly to regular rendering and then set corresponding
  21323. // depth materials per each chunk instead of just once per object)
  21324. objectMaterial = getObjectMaterial( object );
  21325. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21326. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21327. if ( object.customDepthMaterial ) {
  21328. material = object.customDepthMaterial;
  21329. } else if ( useSkinning ) {
  21330. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21331. } else if ( useMorphing ) {
  21332. material = _depthMaterialMorph;
  21333. } else {
  21334. material = _depthMaterial;
  21335. }
  21336. if ( buffer instanceof THREE.BufferGeometry ) {
  21337. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21338. } else {
  21339. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21340. }
  21341. }
  21342. }
  21343. // set matrices and render immediate objects
  21344. renderList = scene.__webglObjectsImmediate;
  21345. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21346. webglObject = renderList[ j ];
  21347. object = webglObject.object;
  21348. if ( object.visible && object.castShadow ) {
  21349. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21350. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21351. }
  21352. }
  21353. }
  21354. // restore GL state
  21355. var clearColor = _renderer.getClearColor(),
  21356. clearAlpha = _renderer.getClearAlpha();
  21357. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21358. _gl.enable( _gl.BLEND );
  21359. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21360. _gl.cullFace( _gl.BACK );
  21361. }
  21362. };
  21363. function createVirtualLight( light, cascade ) {
  21364. var virtualLight = new THREE.DirectionalLight();
  21365. virtualLight.isVirtual = true;
  21366. virtualLight.onlyShadow = true;
  21367. virtualLight.castShadow = true;
  21368. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21369. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21370. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21371. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21372. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21373. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21374. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21375. virtualLight.shadowDarkness = light.shadowDarkness;
  21376. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21377. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21378. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21379. virtualLight.pointsWorld = [];
  21380. virtualLight.pointsFrustum = [];
  21381. var pointsWorld = virtualLight.pointsWorld,
  21382. pointsFrustum = virtualLight.pointsFrustum;
  21383. for ( var i = 0; i < 8; i ++ ) {
  21384. pointsWorld[ i ] = new THREE.Vector3();
  21385. pointsFrustum[ i ] = new THREE.Vector3();
  21386. }
  21387. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21388. var farZ = light.shadowCascadeFarZ[ cascade ];
  21389. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21390. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21391. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21392. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21393. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21394. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21395. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21396. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21397. return virtualLight;
  21398. }
  21399. // Synchronize virtual light with the original light
  21400. function updateVirtualLight( light, cascade ) {
  21401. var virtualLight = light.shadowCascadeArray[ cascade ];
  21402. virtualLight.position.copy( light.position );
  21403. virtualLight.target.position.copy( light.target.position );
  21404. virtualLight.lookAt( virtualLight.target );
  21405. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21406. virtualLight.shadowDarkness = light.shadowDarkness;
  21407. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21408. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21409. var farZ = light.shadowCascadeFarZ[ cascade ];
  21410. var pointsFrustum = virtualLight.pointsFrustum;
  21411. pointsFrustum[ 0 ].z = nearZ;
  21412. pointsFrustum[ 1 ].z = nearZ;
  21413. pointsFrustum[ 2 ].z = nearZ;
  21414. pointsFrustum[ 3 ].z = nearZ;
  21415. pointsFrustum[ 4 ].z = farZ;
  21416. pointsFrustum[ 5 ].z = farZ;
  21417. pointsFrustum[ 6 ].z = farZ;
  21418. pointsFrustum[ 7 ].z = farZ;
  21419. }
  21420. // Fit shadow camera's ortho frustum to camera frustum
  21421. function updateShadowCamera( camera, light ) {
  21422. var shadowCamera = light.shadowCamera,
  21423. pointsFrustum = light.pointsFrustum,
  21424. pointsWorld = light.pointsWorld;
  21425. _min.set( Infinity, Infinity, Infinity );
  21426. _max.set( -Infinity, -Infinity, -Infinity );
  21427. for ( var i = 0; i < 8; i ++ ) {
  21428. var p = pointsWorld[ i ];
  21429. p.copy( pointsFrustum[ i ] );
  21430. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21431. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21432. if ( p.x < _min.x ) _min.x = p.x;
  21433. if ( p.x > _max.x ) _max.x = p.x;
  21434. if ( p.y < _min.y ) _min.y = p.y;
  21435. if ( p.y > _max.y ) _max.y = p.y;
  21436. if ( p.z < _min.z ) _min.z = p.z;
  21437. if ( p.z > _max.z ) _max.z = p.z;
  21438. }
  21439. shadowCamera.left = _min.x;
  21440. shadowCamera.right = _max.x;
  21441. shadowCamera.top = _max.y;
  21442. shadowCamera.bottom = _min.y;
  21443. // can't really fit near/far
  21444. //shadowCamera.near = _min.z;
  21445. //shadowCamera.far = _max.z;
  21446. shadowCamera.updateProjectionMatrix();
  21447. }
  21448. // For the moment just ignore objects that have multiple materials with different animation methods
  21449. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21450. function getObjectMaterial( object ) {
  21451. return object.material instanceof THREE.MeshFaceMaterial
  21452. ? object.material.materials[ 0 ]
  21453. : object.material;
  21454. };
  21455. };
  21456. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21457. /**
  21458. * @author mikael emtinger / http://gomo.se/
  21459. * @author alteredq / http://alteredqualia.com/
  21460. */
  21461. THREE.SpritePlugin = function () {
  21462. var _gl, _renderer, _texture;
  21463. var vertices, faces, vertexBuffer, elementBuffer;
  21464. var program, attributes, uniforms;
  21465. this.init = function ( renderer ) {
  21466. _gl = renderer.context;
  21467. _renderer = renderer;
  21468. vertices = new Float32Array( [
  21469. - 0.5, - 0.5, 0, 0,
  21470. 0.5, - 0.5, 1, 0,
  21471. 0.5, 0.5, 1, 1,
  21472. - 0.5, 0.5, 0, 1
  21473. ] );
  21474. faces = new Uint16Array( [
  21475. 0, 1, 2,
  21476. 0, 2, 3
  21477. ] );
  21478. vertexBuffer = _gl.createBuffer();
  21479. elementBuffer = _gl.createBuffer();
  21480. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  21481. _gl.bufferData( _gl.ARRAY_BUFFER, vertices, _gl.STATIC_DRAW );
  21482. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  21483. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faces, _gl.STATIC_DRAW );
  21484. program = createProgram();
  21485. attributes = {
  21486. position: _gl.getAttribLocation ( program, 'position' ),
  21487. uv: _gl.getAttribLocation ( program, 'uv' )
  21488. };
  21489. uniforms = {
  21490. uvOffset: _gl.getUniformLocation( program, 'uvOffset' ),
  21491. uvScale: _gl.getUniformLocation( program, 'uvScale' ),
  21492. rotation: _gl.getUniformLocation( program, 'rotation' ),
  21493. scale: _gl.getUniformLocation( program, 'scale' ),
  21494. color: _gl.getUniformLocation( program, 'color' ),
  21495. map: _gl.getUniformLocation( program, 'map' ),
  21496. opacity: _gl.getUniformLocation( program, 'opacity' ),
  21497. modelViewMatrix: _gl.getUniformLocation( program, 'modelViewMatrix' ),
  21498. projectionMatrix: _gl.getUniformLocation( program, 'projectionMatrix' ),
  21499. fogType: _gl.getUniformLocation( program, 'fogType' ),
  21500. fogDensity: _gl.getUniformLocation( program, 'fogDensity' ),
  21501. fogNear: _gl.getUniformLocation( program, 'fogNear' ),
  21502. fogFar: _gl.getUniformLocation( program, 'fogFar' ),
  21503. fogColor: _gl.getUniformLocation( program, 'fogColor' ),
  21504. alphaTest: _gl.getUniformLocation( program, 'alphaTest' )
  21505. };
  21506. var canvas = document.createElement( 'canvas' );
  21507. canvas.width = 8;
  21508. canvas.height = 8;
  21509. var context = canvas.getContext( '2d' );
  21510. context.fillStyle = '#ffffff';
  21511. context.fillRect( 0, 0, canvas.width, canvas.height );
  21512. _texture = new THREE.Texture( canvas );
  21513. _texture.needsUpdate = true;
  21514. };
  21515. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21516. var sprites = scene.__webglSprites,
  21517. nSprites = sprites.length;
  21518. if ( ! nSprites ) return;
  21519. // setup gl
  21520. _gl.useProgram( program );
  21521. _gl.enableVertexAttribArray( attributes.position );
  21522. _gl.enableVertexAttribArray( attributes.uv );
  21523. _gl.disable( _gl.CULL_FACE );
  21524. _gl.enable( _gl.BLEND );
  21525. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  21526. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21527. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21528. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  21529. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21530. _gl.activeTexture( _gl.TEXTURE0 );
  21531. _gl.uniform1i( uniforms.map, 0 );
  21532. var oldFogType = 0;
  21533. var sceneFogType = 0;
  21534. var fog = scene.fog;
  21535. if ( fog ) {
  21536. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21537. if ( fog instanceof THREE.Fog ) {
  21538. _gl.uniform1f( uniforms.fogNear, fog.near );
  21539. _gl.uniform1f( uniforms.fogFar, fog.far );
  21540. _gl.uniform1i( uniforms.fogType, 1 );
  21541. oldFogType = 1;
  21542. sceneFogType = 1;
  21543. } else if ( fog instanceof THREE.FogExp2 ) {
  21544. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21545. _gl.uniform1i( uniforms.fogType, 2 );
  21546. oldFogType = 2;
  21547. sceneFogType = 2;
  21548. }
  21549. } else {
  21550. _gl.uniform1i( uniforms.fogType, 0 );
  21551. oldFogType = 0;
  21552. sceneFogType = 0;
  21553. }
  21554. // update positions and sort
  21555. var i, sprite, material, fogType, scale = [];
  21556. for( i = 0; i < nSprites; i ++ ) {
  21557. sprite = sprites[ i ];
  21558. material = sprite.material;
  21559. if ( sprite.visible === false ) continue;
  21560. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21561. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21562. }
  21563. sprites.sort( painterSortStable );
  21564. // render all sprites
  21565. for( i = 0; i < nSprites; i ++ ) {
  21566. sprite = sprites[ i ];
  21567. if ( sprite.visible === false ) continue;
  21568. material = sprite.material;
  21569. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21570. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21571. scale[ 0 ] = sprite.scale.x;
  21572. scale[ 1 ] = sprite.scale.y;
  21573. if ( scene.fog && material.fog ) {
  21574. fogType = sceneFogType;
  21575. } else {
  21576. fogType = 0;
  21577. }
  21578. if ( oldFogType !== fogType ) {
  21579. _gl.uniform1i( uniforms.fogType, fogType );
  21580. oldFogType = fogType;
  21581. }
  21582. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21583. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21584. _gl.uniform1f( uniforms.opacity, material.opacity );
  21585. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21586. _gl.uniform1f( uniforms.rotation, material.rotation );
  21587. _gl.uniform2fv( uniforms.scale, scale );
  21588. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21589. _renderer.setDepthTest( material.depthTest );
  21590. _renderer.setDepthWrite( material.depthWrite );
  21591. if ( material.map && material.map.image && material.map.image.width ) {
  21592. _renderer.setTexture( material.map, 0 );
  21593. } else {
  21594. _renderer.setTexture( _texture, 0 );
  21595. }
  21596. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21597. }
  21598. // restore gl
  21599. _gl.enable( _gl.CULL_FACE );
  21600. };
  21601. function createProgram () {
  21602. var program = _gl.createProgram();
  21603. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21604. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21605. _gl.shaderSource( vertexShader, [
  21606. 'precision ' + _renderer.getPrecision() + ' float;',
  21607. 'uniform mat4 modelViewMatrix;',
  21608. 'uniform mat4 projectionMatrix;',
  21609. 'uniform float rotation;',
  21610. 'uniform vec2 scale;',
  21611. 'uniform vec2 uvOffset;',
  21612. 'uniform vec2 uvScale;',
  21613. 'attribute vec2 position;',
  21614. 'attribute vec2 uv;',
  21615. 'varying vec2 vUV;',
  21616. 'void main() {',
  21617. 'vUV = uvOffset + uv * uvScale;',
  21618. 'vec2 alignedPosition = position * scale;',
  21619. 'vec2 rotatedPosition;',
  21620. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  21621. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  21622. 'vec4 finalPosition;',
  21623. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  21624. 'finalPosition.xy += rotatedPosition;',
  21625. 'finalPosition = projectionMatrix * finalPosition;',
  21626. 'gl_Position = finalPosition;',
  21627. '}'
  21628. ].join( '\n' ) );
  21629. _gl.shaderSource( fragmentShader, [
  21630. 'precision ' + _renderer.getPrecision() + ' float;',
  21631. 'uniform vec3 color;',
  21632. 'uniform sampler2D map;',
  21633. 'uniform float opacity;',
  21634. 'uniform int fogType;',
  21635. 'uniform vec3 fogColor;',
  21636. 'uniform float fogDensity;',
  21637. 'uniform float fogNear;',
  21638. 'uniform float fogFar;',
  21639. 'uniform float alphaTest;',
  21640. 'varying vec2 vUV;',
  21641. 'void main() {',
  21642. 'vec4 texture = texture2D( map, vUV );',
  21643. 'if ( texture.a < alphaTest ) discard;',
  21644. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  21645. 'if ( fogType > 0 ) {',
  21646. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  21647. 'float fogFactor = 0.0;',
  21648. 'if ( fogType == 1 ) {',
  21649. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  21650. '} else {',
  21651. 'const float LOG2 = 1.442695;',
  21652. 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  21653. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  21654. '}',
  21655. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  21656. '}',
  21657. '}'
  21658. ].join( '\n' ) );
  21659. _gl.compileShader( vertexShader );
  21660. _gl.compileShader( fragmentShader );
  21661. _gl.attachShader( program, vertexShader );
  21662. _gl.attachShader( program, fragmentShader );
  21663. _gl.linkProgram( program );
  21664. return program;
  21665. };
  21666. function painterSortStable ( a, b ) {
  21667. if ( a.z !== b.z ) {
  21668. return b.z - a.z;
  21669. } else {
  21670. return b.id - a.id;
  21671. }
  21672. };
  21673. };
  21674. /**
  21675. * @author alteredq / http://alteredqualia.com/
  21676. */
  21677. THREE.DepthPassPlugin = function () {
  21678. this.enabled = false;
  21679. this.renderTarget = null;
  21680. var _gl,
  21681. _renderer,
  21682. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21683. _frustum = new THREE.Frustum(),
  21684. _projScreenMatrix = new THREE.Matrix4();
  21685. this.init = function ( renderer ) {
  21686. _gl = renderer.context;
  21687. _renderer = renderer;
  21688. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21689. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21690. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21691. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21692. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21693. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21694. _depthMaterial._shadowPass = true;
  21695. _depthMaterialMorph._shadowPass = true;
  21696. _depthMaterialSkin._shadowPass = true;
  21697. _depthMaterialMorphSkin._shadowPass = true;
  21698. };
  21699. this.render = function ( scene, camera ) {
  21700. if ( ! this.enabled ) return;
  21701. this.update( scene, camera );
  21702. };
  21703. this.update = function ( scene, camera ) {
  21704. var i, il, j, jl, n,
  21705. program, buffer, material,
  21706. webglObject, object, light,
  21707. renderList,
  21708. fog = null;
  21709. // set GL state for depth map
  21710. _gl.clearColor( 1, 1, 1, 1 );
  21711. _gl.disable( _gl.BLEND );
  21712. _renderer.setDepthTest( true );
  21713. // update scene
  21714. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21715. // update camera matrices and frustum
  21716. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21717. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21718. _frustum.setFromMatrix( _projScreenMatrix );
  21719. // render depth map
  21720. _renderer.setRenderTarget( this.renderTarget );
  21721. _renderer.clear();
  21722. // set object matrices & frustum culling
  21723. renderList = scene.__webglObjects;
  21724. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21725. webglObject = renderList[ j ];
  21726. object = webglObject.object;
  21727. webglObject.render = false;
  21728. if ( object.visible ) {
  21729. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21730. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21731. webglObject.render = true;
  21732. }
  21733. }
  21734. }
  21735. // render regular objects
  21736. var objectMaterial, useMorphing, useSkinning;
  21737. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21738. webglObject = renderList[ j ];
  21739. if ( webglObject.render ) {
  21740. object = webglObject.object;
  21741. buffer = webglObject.buffer;
  21742. // todo: create proper depth material for particles
  21743. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21744. objectMaterial = getObjectMaterial( object );
  21745. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21746. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21747. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21748. if ( object.customDepthMaterial ) {
  21749. material = object.customDepthMaterial;
  21750. } else if ( useSkinning ) {
  21751. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21752. } else if ( useMorphing ) {
  21753. material = _depthMaterialMorph;
  21754. } else {
  21755. material = _depthMaterial;
  21756. }
  21757. if ( buffer instanceof THREE.BufferGeometry ) {
  21758. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21759. } else {
  21760. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21761. }
  21762. }
  21763. }
  21764. // set matrices and render immediate objects
  21765. renderList = scene.__webglObjectsImmediate;
  21766. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21767. webglObject = renderList[ j ];
  21768. object = webglObject.object;
  21769. if ( object.visible ) {
  21770. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21771. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21772. }
  21773. }
  21774. // restore GL state
  21775. var clearColor = _renderer.getClearColor(),
  21776. clearAlpha = _renderer.getClearAlpha();
  21777. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21778. _gl.enable( _gl.BLEND );
  21779. };
  21780. // For the moment just ignore objects that have multiple materials with different animation methods
  21781. // Only the first material will be taken into account for deciding which depth material to use
  21782. function getObjectMaterial( object ) {
  21783. return object.material instanceof THREE.MeshFaceMaterial
  21784. ? object.material.materials[ 0 ]
  21785. : object.material;
  21786. };
  21787. };
  21788. /**
  21789. * @author mikael emtinger / http://gomo.se/
  21790. */
  21791. THREE.ShaderFlares = {
  21792. 'lensFlareVertexTexture': {
  21793. vertexShader: [
  21794. "uniform lowp int renderType;",
  21795. "uniform vec3 screenPosition;",
  21796. "uniform vec2 scale;",
  21797. "uniform float rotation;",
  21798. "uniform sampler2D occlusionMap;",
  21799. "attribute vec2 position;",
  21800. "attribute vec2 uv;",
  21801. "varying vec2 vUV;",
  21802. "varying float vVisibility;",
  21803. "void main() {",
  21804. "vUV = uv;",
  21805. "vec2 pos = position;",
  21806. "if( renderType == 2 ) {",
  21807. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  21808. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  21809. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  21810. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  21811. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  21812. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  21813. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  21814. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  21815. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21816. "vVisibility = visibility.r / 9.0;",
  21817. "vVisibility *= 1.0 - visibility.g / 9.0;",
  21818. "vVisibility *= visibility.b / 9.0;",
  21819. "vVisibility *= 1.0 - visibility.a / 9.0;",
  21820. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21821. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21822. "}",
  21823. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21824. "}"
  21825. ].join( "\n" ),
  21826. fragmentShader: [
  21827. "uniform lowp int renderType;",
  21828. "uniform sampler2D map;",
  21829. "uniform float opacity;",
  21830. "uniform vec3 color;",
  21831. "varying vec2 vUV;",
  21832. "varying float vVisibility;",
  21833. "void main() {",
  21834. // pink square
  21835. "if( renderType == 0 ) {",
  21836. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21837. // restore
  21838. "} else if( renderType == 1 ) {",
  21839. "gl_FragColor = texture2D( map, vUV );",
  21840. // flare
  21841. "} else {",
  21842. "vec4 texture = texture2D( map, vUV );",
  21843. "texture.a *= opacity * vVisibility;",
  21844. "gl_FragColor = texture;",
  21845. "gl_FragColor.rgb *= color;",
  21846. "}",
  21847. "}"
  21848. ].join( "\n" )
  21849. },
  21850. 'lensFlare': {
  21851. vertexShader: [
  21852. "uniform lowp int renderType;",
  21853. "uniform vec3 screenPosition;",
  21854. "uniform vec2 scale;",
  21855. "uniform float rotation;",
  21856. "attribute vec2 position;",
  21857. "attribute vec2 uv;",
  21858. "varying vec2 vUV;",
  21859. "void main() {",
  21860. "vUV = uv;",
  21861. "vec2 pos = position;",
  21862. "if( renderType == 2 ) {",
  21863. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21864. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21865. "}",
  21866. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21867. "}"
  21868. ].join( "\n" ),
  21869. fragmentShader: [
  21870. "precision mediump float;",
  21871. "uniform lowp int renderType;",
  21872. "uniform sampler2D map;",
  21873. "uniform sampler2D occlusionMap;",
  21874. "uniform float opacity;",
  21875. "uniform vec3 color;",
  21876. "varying vec2 vUV;",
  21877. "void main() {",
  21878. // pink square
  21879. "if( renderType == 0 ) {",
  21880. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21881. // restore
  21882. "} else if( renderType == 1 ) {",
  21883. "gl_FragColor = texture2D( map, vUV );",
  21884. // flare
  21885. "} else {",
  21886. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  21887. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  21888. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  21889. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21890. "visibility = ( 1.0 - visibility / 4.0 );",
  21891. "vec4 texture = texture2D( map, vUV );",
  21892. "texture.a *= opacity * visibility;",
  21893. "gl_FragColor = texture;",
  21894. "gl_FragColor.rgb *= color;",
  21895. "}",
  21896. "}"
  21897. ].join( "\n" )
  21898. }
  21899. };