three.js 795 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981
  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: '62' };
  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 eulerOrder () {
  4273. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4274. return this.rotation.order;
  4275. },
  4276. set eulerOrder ( value ) {
  4277. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4278. this.rotation.order = value;
  4279. },
  4280. get useQuaternion () {
  4281. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4282. },
  4283. set useQuaternion ( value ) {
  4284. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4285. },
  4286. applyMatrix: function () {
  4287. var m1 = new THREE.Matrix4();
  4288. return function ( matrix ) {
  4289. this.matrix.multiplyMatrices( matrix, this.matrix );
  4290. this.position.getPositionFromMatrix( this.matrix );
  4291. this.scale.getScaleFromMatrix( this.matrix );
  4292. m1.extractRotation( this.matrix );
  4293. this.quaternion.setFromRotationMatrix( m1 );
  4294. }
  4295. }(),
  4296. setRotationFromAxisAngle: function ( axis, angle ) {
  4297. // assumes axis is normalized
  4298. this.quaternion.setFromAxisAngle( axis, angle );
  4299. },
  4300. setRotationFromEuler: function ( euler ) {
  4301. this.quaternion.setFromEuler( euler, true );
  4302. },
  4303. setRotationFromMatrix: function ( m ) {
  4304. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4305. this.quaternion.setFromRotationMatrix( m );
  4306. },
  4307. setRotationFromQuaternion: function ( q ) {
  4308. // assumes q is normalized
  4309. this.quaternion.copy( q );
  4310. },
  4311. rotateOnAxis: function() {
  4312. // rotate object on axis in object space
  4313. // axis is assumed to be normalized
  4314. var q1 = new THREE.Quaternion();
  4315. return function ( axis, angle ) {
  4316. q1.setFromAxisAngle( axis, angle );
  4317. this.quaternion.multiply( q1 );
  4318. return this;
  4319. }
  4320. }(),
  4321. rotateX: function () {
  4322. var v1 = new THREE.Vector3( 1, 0, 0 );
  4323. return function ( angle ) {
  4324. return this.rotateOnAxis( v1, angle );
  4325. };
  4326. }(),
  4327. rotateY: function () {
  4328. var v1 = new THREE.Vector3( 0, 1, 0 );
  4329. return function ( angle ) {
  4330. return this.rotateOnAxis( v1, angle );
  4331. };
  4332. }(),
  4333. rotateZ: function () {
  4334. var v1 = new THREE.Vector3( 0, 0, 1 );
  4335. return function ( angle ) {
  4336. return this.rotateOnAxis( v1, angle );
  4337. };
  4338. }(),
  4339. translateOnAxis: function () {
  4340. // translate object by distance along axis in object space
  4341. // axis is assumed to be normalized
  4342. var v1 = new THREE.Vector3();
  4343. return function ( axis, distance ) {
  4344. v1.copy( axis );
  4345. v1.applyQuaternion( this.quaternion );
  4346. this.position.add( v1.multiplyScalar( distance ) );
  4347. return this;
  4348. }
  4349. }(),
  4350. translate: function ( distance, axis ) {
  4351. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  4352. return this.translateOnAxis( axis, distance );
  4353. },
  4354. translateX: function () {
  4355. var v1 = new THREE.Vector3( 1, 0, 0 );
  4356. return function ( distance ) {
  4357. return this.translateOnAxis( v1, distance );
  4358. };
  4359. }(),
  4360. translateY: function () {
  4361. var v1 = new THREE.Vector3( 0, 1, 0 );
  4362. return function ( distance ) {
  4363. return this.translateOnAxis( v1, distance );
  4364. };
  4365. }(),
  4366. translateZ: function () {
  4367. var v1 = new THREE.Vector3( 0, 0, 1 );
  4368. return function ( distance ) {
  4369. return this.translateOnAxis( v1, distance );
  4370. };
  4371. }(),
  4372. localToWorld: function ( vector ) {
  4373. return vector.applyMatrix4( this.matrixWorld );
  4374. },
  4375. worldToLocal: function () {
  4376. var m1 = new THREE.Matrix4();
  4377. return function ( vector ) {
  4378. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4379. };
  4380. }(),
  4381. lookAt: function () {
  4382. // This routine does not support objects with rotated and/or translated parent(s)
  4383. var m1 = new THREE.Matrix4();
  4384. return function ( vector ) {
  4385. m1.lookAt( vector, this.position, this.up );
  4386. this.quaternion.setFromRotationMatrix( m1 );
  4387. };
  4388. }(),
  4389. add: function ( object ) {
  4390. if ( object === this ) {
  4391. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  4392. return;
  4393. }
  4394. if ( object instanceof THREE.Object3D ) {
  4395. if ( object.parent !== undefined ) {
  4396. object.parent.remove( object );
  4397. }
  4398. object.parent = this;
  4399. object.dispatchEvent( { type: 'added' } );
  4400. this.children.push( object );
  4401. // add to scene
  4402. var scene = this;
  4403. while ( scene.parent !== undefined ) {
  4404. scene = scene.parent;
  4405. }
  4406. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4407. scene.__addObject( object );
  4408. }
  4409. }
  4410. },
  4411. remove: function ( object ) {
  4412. var index = this.children.indexOf( object );
  4413. if ( index !== - 1 ) {
  4414. object.parent = undefined;
  4415. object.dispatchEvent( { type: 'removed' } );
  4416. this.children.splice( index, 1 );
  4417. // remove from scene
  4418. var scene = this;
  4419. while ( scene.parent !== undefined ) {
  4420. scene = scene.parent;
  4421. }
  4422. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4423. scene.__removeObject( object );
  4424. }
  4425. }
  4426. },
  4427. traverse: function ( callback ) {
  4428. callback( this );
  4429. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4430. this.children[ i ].traverse( callback );
  4431. }
  4432. },
  4433. getObjectById: function ( id, recursive ) {
  4434. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4435. var child = this.children[ i ];
  4436. if ( child.id === id ) {
  4437. return child;
  4438. }
  4439. if ( recursive === true ) {
  4440. child = child.getObjectById( id, recursive );
  4441. if ( child !== undefined ) {
  4442. return child;
  4443. }
  4444. }
  4445. }
  4446. return undefined;
  4447. },
  4448. getObjectByName: function ( name, recursive ) {
  4449. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4450. var child = this.children[ i ];
  4451. if ( child.name === name ) {
  4452. return child;
  4453. }
  4454. if ( recursive === true ) {
  4455. child = child.getObjectByName( name, recursive );
  4456. if ( child !== undefined ) {
  4457. return child;
  4458. }
  4459. }
  4460. }
  4461. return undefined;
  4462. },
  4463. getChildByName: function ( name, recursive ) {
  4464. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  4465. return this.getObjectByName( name, recursive );
  4466. },
  4467. getDescendants: function ( array ) {
  4468. if ( array === undefined ) array = [];
  4469. Array.prototype.push.apply( array, this.children );
  4470. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4471. this.children[ i ].getDescendants( array );
  4472. }
  4473. return array;
  4474. },
  4475. updateMatrix: function () {
  4476. this.matrix.compose( this.position, this.quaternion, this.scale );
  4477. this.matrixWorldNeedsUpdate = true;
  4478. },
  4479. updateMatrixWorld: function ( force ) {
  4480. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4481. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4482. if ( this.parent === undefined ) {
  4483. this.matrixWorld.copy( this.matrix );
  4484. } else {
  4485. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4486. }
  4487. this.matrixWorldNeedsUpdate = false;
  4488. force = true;
  4489. }
  4490. // update children
  4491. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4492. this.children[ i ].updateMatrixWorld( force );
  4493. }
  4494. },
  4495. clone: function ( object, recursive ) {
  4496. if ( object === undefined ) object = new THREE.Object3D();
  4497. if ( recursive === undefined ) recursive = true;
  4498. object.name = this.name;
  4499. object.up.copy( this.up );
  4500. object.position.copy( this.position );
  4501. object.quaternion.copy( this.quaternion );
  4502. object.scale.copy( this.scale );
  4503. object.renderDepth = this.renderDepth;
  4504. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4505. object.matrix.copy( this.matrix );
  4506. object.matrixWorld.copy( this.matrixWorld );
  4507. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4508. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4509. object.visible = this.visible;
  4510. object.castShadow = this.castShadow;
  4511. object.receiveShadow = this.receiveShadow;
  4512. object.frustumCulled = this.frustumCulled;
  4513. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4514. if ( recursive === true ) {
  4515. for ( var i = 0; i < this.children.length; i ++ ) {
  4516. var child = this.children[ i ];
  4517. object.add( child.clone() );
  4518. }
  4519. }
  4520. return object;
  4521. }
  4522. };
  4523. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4524. THREE.Object3DIdCount = 0;
  4525. /**
  4526. * @author mrdoob / http://mrdoob.com/
  4527. * @author supereggbert / http://www.paulbrunt.co.uk/
  4528. * @author julianwa / https://github.com/julianwa
  4529. */
  4530. THREE.Projector = function () {
  4531. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4532. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4533. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  4534. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4535. _sprite, _spriteCount, _spritePool = [], _spritePoolLength = 0,
  4536. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  4537. _vector3 = new THREE.Vector3(),
  4538. _vector4 = new THREE.Vector4(),
  4539. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4540. _boundingBox = new THREE.Box3(),
  4541. _points3 = new Array( 3 ),
  4542. _points4 = new Array( 4 ),
  4543. _viewMatrix = new THREE.Matrix4(),
  4544. _viewProjectionMatrix = new THREE.Matrix4(),
  4545. _modelMatrix,
  4546. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4547. _normalMatrix = new THREE.Matrix3(),
  4548. _normalViewMatrix = new THREE.Matrix3(),
  4549. _centroid = new THREE.Vector3(),
  4550. _frustum = new THREE.Frustum(),
  4551. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4552. _clippedVertex2PositionScreen = new THREE.Vector4();
  4553. this.projectVector = function ( vector, camera ) {
  4554. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4555. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4556. return vector.applyProjection( _viewProjectionMatrix );
  4557. };
  4558. this.unprojectVector = function ( vector, camera ) {
  4559. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4560. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  4561. return vector.applyProjection( _viewProjectionMatrix );
  4562. };
  4563. this.pickingRay = function ( vector, camera ) {
  4564. // set two vectors with opposing z values
  4565. vector.z = -1.0;
  4566. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4567. this.unprojectVector( vector, camera );
  4568. this.unprojectVector( end, camera );
  4569. // find direction from vector to end
  4570. end.sub( vector ).normalize();
  4571. return new THREE.Raycaster( vector, end );
  4572. };
  4573. var getObject = function ( object ) {
  4574. _object = getNextObjectInPool();
  4575. _object.id = object.id;
  4576. _object.object = object;
  4577. if ( object.renderDepth !== null ) {
  4578. _object.z = object.renderDepth;
  4579. } else {
  4580. _vector3.getPositionFromMatrix( object.matrixWorld );
  4581. _vector3.applyProjection( _viewProjectionMatrix );
  4582. _object.z = _vector3.z;
  4583. }
  4584. return _object;
  4585. };
  4586. var projectObject = function ( object ) {
  4587. if ( object.visible === false ) return;
  4588. if ( object instanceof THREE.Light ) {
  4589. _renderData.lights.push( object );
  4590. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  4591. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4592. _renderData.objects.push( getObject( object ) );
  4593. }
  4594. } else if ( object instanceof THREE.Sprite ) {
  4595. _renderData.sprites.push( getObject( object ) );
  4596. }
  4597. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4598. projectObject( object.children[ i ] );
  4599. }
  4600. };
  4601. var projectGraph = function ( root, sortObjects ) {
  4602. _objectCount = 0;
  4603. _renderData.objects.length = 0;
  4604. _renderData.sprites.length = 0;
  4605. _renderData.lights.length = 0;
  4606. projectObject( root );
  4607. if ( sortObjects === true ) {
  4608. _renderData.objects.sort( painterSort );
  4609. }
  4610. };
  4611. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4612. var visible = false,
  4613. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  4614. geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  4615. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  4616. _face3Count = 0;
  4617. _lineCount = 0;
  4618. _spriteCount = 0;
  4619. _renderData.elements.length = 0;
  4620. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4621. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4622. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4623. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4624. _normalViewMatrix.getNormalMatrix( _viewMatrix );
  4625. _frustum.setFromMatrix( _viewProjectionMatrix );
  4626. projectGraph( scene, sortObjects );
  4627. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4628. object = _renderData.objects[ o ].object;
  4629. _modelMatrix = object.matrixWorld;
  4630. _vertexCount = 0;
  4631. if ( object instanceof THREE.Mesh ) {
  4632. geometry = object.geometry;
  4633. vertices = geometry.vertices;
  4634. faces = geometry.faces;
  4635. faceVertexUvs = geometry.faceVertexUvs;
  4636. _normalMatrix.getNormalMatrix( _modelMatrix );
  4637. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4638. objectMaterials = isFaceMaterial === true ? object.material : null;
  4639. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  4640. _vertex = getNextVertexInPool();
  4641. _vertex.positionWorld.copy( vertices[ v ] ).applyMatrix4( _modelMatrix );
  4642. _vertex.positionScreen.copy( _vertex.positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4643. var invW = 1 / _vertex.positionScreen.w;
  4644. _vertex.positionScreen.x *= invW;
  4645. _vertex.positionScreen.y *= invW;
  4646. _vertex.positionScreen.z *= invW;
  4647. _vertex.visible = ! ( _vertex.positionScreen.x < -1 || _vertex.positionScreen.x > 1 ||
  4648. _vertex.positionScreen.y < -1 || _vertex.positionScreen.y > 1 ||
  4649. _vertex.positionScreen.z < -1 || _vertex.positionScreen.z > 1 );
  4650. }
  4651. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  4652. face = faces[ f ];
  4653. var material = isFaceMaterial === true
  4654. ? objectMaterials.materials[ face.materialIndex ]
  4655. : object.material;
  4656. if ( material === undefined ) continue;
  4657. var side = material.side;
  4658. v1 = _vertexPool[ face.a ];
  4659. v2 = _vertexPool[ face.b ];
  4660. v3 = _vertexPool[ face.c ];
  4661. _points3[ 0 ] = v1.positionScreen;
  4662. _points3[ 1 ] = v2.positionScreen;
  4663. _points3[ 2 ] = v3.positionScreen;
  4664. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4665. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4666. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) *
  4667. ( v2.positionScreen.y - v1.positionScreen.y ) -
  4668. ( v3.positionScreen.y - v1.positionScreen.y ) *
  4669. ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4670. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4671. _face = getNextFace3InPool();
  4672. _face.id = object.id;
  4673. _face.v1.copy( v1 );
  4674. _face.v2.copy( v2 );
  4675. _face.v3.copy( v3 );
  4676. } else {
  4677. continue;
  4678. }
  4679. } else {
  4680. continue;
  4681. }
  4682. _face.normalModel.copy( face.normal );
  4683. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4684. _face.normalModel.negate();
  4685. }
  4686. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4687. _face.normalModelView.copy( _face.normalModel ).applyMatrix3( _normalViewMatrix );
  4688. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4689. faceVertexNormals = face.vertexNormals;
  4690. for ( n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) {
  4691. var normalModel = _face.vertexNormalsModel[ n ];
  4692. normalModel.copy( faceVertexNormals[ n ] );
  4693. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4694. normalModel.negate();
  4695. }
  4696. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4697. var normalModelView = _face.vertexNormalsModelView[ n ];
  4698. normalModelView.copy( normalModel ).applyMatrix3( _normalViewMatrix );
  4699. }
  4700. _face.vertexNormalsLength = faceVertexNormals.length;
  4701. for ( c = 0, cl = Math.min( faceVertexUvs.length, 3 ); c < cl; c ++ ) {
  4702. uvs = faceVertexUvs[ c ][ f ];
  4703. if ( uvs === undefined ) continue;
  4704. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  4705. _face.uvs[ c ][ u ] = uvs[ u ];
  4706. }
  4707. }
  4708. _face.color = face.color;
  4709. _face.material = material;
  4710. _centroid.copy( _face.centroidModel ).applyProjection( _viewProjectionMatrix );
  4711. _face.z = _centroid.z;
  4712. _renderData.elements.push( _face );
  4713. }
  4714. } else if ( object instanceof THREE.Line ) {
  4715. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4716. vertices = object.geometry.vertices;
  4717. v1 = getNextVertexInPool();
  4718. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4719. // Handle LineStrip and LinePieces
  4720. var step = object.type === THREE.LinePieces ? 2 : 1;
  4721. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  4722. v1 = getNextVertexInPool();
  4723. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4724. if ( ( v + 1 ) % step > 0 ) continue;
  4725. v2 = _vertexPool[ _vertexCount - 2 ];
  4726. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4727. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4728. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4729. // Perform the perspective divide
  4730. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4731. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4732. _line = getNextLineInPool();
  4733. _line.id = object.id;
  4734. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4735. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4736. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4737. _line.material = object.material;
  4738. if ( object.material.vertexColors === THREE.VertexColors ) {
  4739. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  4740. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  4741. }
  4742. _renderData.elements.push( _line );
  4743. }
  4744. }
  4745. }
  4746. }
  4747. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  4748. object = _renderData.sprites[ o ].object;
  4749. _modelMatrix = object.matrixWorld;
  4750. if ( object instanceof THREE.Sprite ) {
  4751. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4752. _vector4.applyMatrix4( _viewProjectionMatrix );
  4753. var invW = 1 / _vector4.w;
  4754. _vector4.z *= invW;
  4755. if ( _vector4.z > -1 && _vector4.z < 1 ) {
  4756. _sprite = getNextSpriteInPool();
  4757. _sprite.id = object.id;
  4758. _sprite.x = _vector4.x * invW;
  4759. _sprite.y = _vector4.y * invW;
  4760. _sprite.z = _vector4.z;
  4761. _sprite.object = object;
  4762. _sprite.rotation = object.rotation;
  4763. _sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4764. _sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4765. _sprite.material = object.material;
  4766. _renderData.elements.push( _sprite );
  4767. }
  4768. }
  4769. }
  4770. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4771. return _renderData;
  4772. };
  4773. // Pools
  4774. function getNextObjectInPool() {
  4775. if ( _objectCount === _objectPoolLength ) {
  4776. var object = new THREE.RenderableObject();
  4777. _objectPool.push( object );
  4778. _objectPoolLength ++;
  4779. _objectCount ++;
  4780. return object;
  4781. }
  4782. return _objectPool[ _objectCount ++ ];
  4783. }
  4784. function getNextVertexInPool() {
  4785. if ( _vertexCount === _vertexPoolLength ) {
  4786. var vertex = new THREE.RenderableVertex();
  4787. _vertexPool.push( vertex );
  4788. _vertexPoolLength ++;
  4789. _vertexCount ++;
  4790. return vertex;
  4791. }
  4792. return _vertexPool[ _vertexCount ++ ];
  4793. }
  4794. function getNextFace3InPool() {
  4795. if ( _face3Count === _face3PoolLength ) {
  4796. var face = new THREE.RenderableFace3();
  4797. _face3Pool.push( face );
  4798. _face3PoolLength ++;
  4799. _face3Count ++;
  4800. return face;
  4801. }
  4802. return _face3Pool[ _face3Count ++ ];
  4803. }
  4804. function getNextLineInPool() {
  4805. if ( _lineCount === _linePoolLength ) {
  4806. var line = new THREE.RenderableLine();
  4807. _linePool.push( line );
  4808. _linePoolLength ++;
  4809. _lineCount ++
  4810. return line;
  4811. }
  4812. return _linePool[ _lineCount ++ ];
  4813. }
  4814. function getNextSpriteInPool() {
  4815. if ( _spriteCount === _spritePoolLength ) {
  4816. var sprite = new THREE.RenderableSprite();
  4817. _spritePool.push( sprite );
  4818. _spritePoolLength ++;
  4819. _spriteCount ++
  4820. return sprite;
  4821. }
  4822. return _spritePool[ _spriteCount ++ ];
  4823. }
  4824. //
  4825. function painterSort( a, b ) {
  4826. if ( a.z !== b.z ) {
  4827. return b.z - a.z;
  4828. } else if ( a.id !== b.id ) {
  4829. return a.id - b.id;
  4830. } else {
  4831. return 0;
  4832. }
  4833. }
  4834. function clipLine( s1, s2 ) {
  4835. var alpha1 = 0, alpha2 = 1,
  4836. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4837. // Z = -1 and Z = +1, respectively.
  4838. bc1near = s1.z + s1.w,
  4839. bc2near = s2.z + s2.w,
  4840. bc1far = - s1.z + s1.w,
  4841. bc2far = - s2.z + s2.w;
  4842. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4843. // Both vertices lie entirely within all clip planes.
  4844. return true;
  4845. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4846. // Both vertices lie entirely outside one of the clip planes.
  4847. return false;
  4848. } else {
  4849. // The line segment spans at least one clip plane.
  4850. if ( bc1near < 0 ) {
  4851. // v1 lies outside the near plane, v2 inside
  4852. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4853. } else if ( bc2near < 0 ) {
  4854. // v2 lies outside the near plane, v1 inside
  4855. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4856. }
  4857. if ( bc1far < 0 ) {
  4858. // v1 lies outside the far plane, v2 inside
  4859. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4860. } else if ( bc2far < 0 ) {
  4861. // v2 lies outside the far plane, v2 inside
  4862. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4863. }
  4864. if ( alpha2 < alpha1 ) {
  4865. // The line segment spans two boundaries, but is outside both of them.
  4866. // (This can't happen when we're only clipping against just near/far but good
  4867. // to leave the check here for future usage if other clip planes are added.)
  4868. return false;
  4869. } else {
  4870. // Update the s1 and s2 vertices to match the clipped line segment.
  4871. s1.lerp( s2, alpha1 );
  4872. s2.lerp( s1, 1 - alpha2 );
  4873. return true;
  4874. }
  4875. }
  4876. }
  4877. };
  4878. /**
  4879. * @author mrdoob / http://mrdoob.com/
  4880. * @author alteredq / http://alteredqualia.com/
  4881. */
  4882. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4883. this.a = a;
  4884. this.b = b;
  4885. this.c = c;
  4886. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4887. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4888. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4889. this.vertexColors = color instanceof Array ? color : [];
  4890. this.vertexTangents = [];
  4891. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4892. this.centroid = new THREE.Vector3();
  4893. };
  4894. THREE.Face3.prototype = {
  4895. constructor: THREE.Face3,
  4896. clone: function () {
  4897. var face = new THREE.Face3( this.a, this.b, this.c );
  4898. face.normal.copy( this.normal );
  4899. face.color.copy( this.color );
  4900. face.centroid.copy( this.centroid );
  4901. face.materialIndex = this.materialIndex;
  4902. var i, il;
  4903. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4904. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4905. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4906. return face;
  4907. }
  4908. };
  4909. /**
  4910. * @author mrdoob / http://mrdoob.com/
  4911. */
  4912. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4913. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.')
  4914. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  4915. };
  4916. /**
  4917. * @author mrdoob / http://mrdoob.com/
  4918. * @author kile / http://kile.stravaganza.org/
  4919. * @author alteredq / http://alteredqualia.com/
  4920. * @author mikael emtinger / http://gomo.se/
  4921. * @author zz85 / http://www.lab4games.net/zz85/blog
  4922. * @author bhouston / http://exocortex.com
  4923. */
  4924. THREE.Geometry = function () {
  4925. this.id = THREE.GeometryIdCount ++;
  4926. this.uuid = THREE.Math.generateUUID();
  4927. this.name = '';
  4928. this.vertices = [];
  4929. this.colors = []; // one-to-one vertex colors, used in ParticleSystem and Line
  4930. this.faces = [];
  4931. this.faceVertexUvs = [[]];
  4932. this.morphTargets = [];
  4933. this.morphColors = [];
  4934. this.morphNormals = [];
  4935. this.skinWeights = [];
  4936. this.skinIndices = [];
  4937. this.lineDistances = [];
  4938. this.boundingBox = null;
  4939. this.boundingSphere = null;
  4940. this.hasTangents = false;
  4941. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4942. // update flags
  4943. this.verticesNeedUpdate = false;
  4944. this.elementsNeedUpdate = false;
  4945. this.uvsNeedUpdate = false;
  4946. this.normalsNeedUpdate = false;
  4947. this.tangentsNeedUpdate = false;
  4948. this.colorsNeedUpdate = false;
  4949. this.lineDistancesNeedUpdate = false;
  4950. this.buffersNeedUpdate = false;
  4951. };
  4952. THREE.Geometry.prototype = {
  4953. constructor: THREE.Geometry,
  4954. applyMatrix: function ( matrix ) {
  4955. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  4956. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4957. var vertex = this.vertices[ i ];
  4958. vertex.applyMatrix4( matrix );
  4959. }
  4960. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4961. var face = this.faces[ i ];
  4962. face.normal.applyMatrix3( normalMatrix ).normalize();
  4963. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4964. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4965. }
  4966. face.centroid.applyMatrix4( matrix );
  4967. }
  4968. if ( this.boundingBox instanceof THREE.Box3 ) {
  4969. this.computeBoundingBox();
  4970. }
  4971. if ( this.boundingSphere instanceof THREE.Sphere ) {
  4972. this.computeBoundingSphere();
  4973. }
  4974. },
  4975. computeCentroids: function () {
  4976. var f, fl, face;
  4977. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4978. face = this.faces[ f ];
  4979. face.centroid.set( 0, 0, 0 );
  4980. face.centroid.add( this.vertices[ face.a ] );
  4981. face.centroid.add( this.vertices[ face.b ] );
  4982. face.centroid.add( this.vertices[ face.c ] );
  4983. face.centroid.divideScalar( 3 );
  4984. }
  4985. },
  4986. computeFaceNormals: function () {
  4987. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  4988. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4989. var face = this.faces[ f ];
  4990. var vA = this.vertices[ face.a ];
  4991. var vB = this.vertices[ face.b ];
  4992. var vC = this.vertices[ face.c ];
  4993. cb.subVectors( vC, vB );
  4994. ab.subVectors( vA, vB );
  4995. cb.cross( ab );
  4996. cb.normalize();
  4997. face.normal.copy( cb );
  4998. }
  4999. },
  5000. computeVertexNormals: function ( areaWeighted ) {
  5001. var v, vl, f, fl, face, vertices;
  5002. // create internal buffers for reuse when calling this method repeatedly
  5003. // (otherwise memory allocation / deallocation every frame is big resource hog)
  5004. if ( this.__tmpVertices === undefined ) {
  5005. this.__tmpVertices = new Array( this.vertices.length );
  5006. vertices = this.__tmpVertices;
  5007. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5008. vertices[ v ] = new THREE.Vector3();
  5009. }
  5010. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5011. face = this.faces[ f ];
  5012. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  5013. }
  5014. } else {
  5015. vertices = this.__tmpVertices;
  5016. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5017. vertices[ v ].set( 0, 0, 0 );
  5018. }
  5019. }
  5020. if ( areaWeighted ) {
  5021. // vertex normals weighted by triangle areas
  5022. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5023. var vA, vB, vC, vD;
  5024. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  5025. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  5026. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5027. face = this.faces[ f ];
  5028. vA = this.vertices[ face.a ];
  5029. vB = this.vertices[ face.b ];
  5030. vC = this.vertices[ face.c ];
  5031. cb.subVectors( vC, vB );
  5032. ab.subVectors( vA, vB );
  5033. cb.cross( ab );
  5034. vertices[ face.a ].add( cb );
  5035. vertices[ face.b ].add( cb );
  5036. vertices[ face.c ].add( cb );
  5037. }
  5038. } else {
  5039. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5040. face = this.faces[ f ];
  5041. vertices[ face.a ].add( face.normal );
  5042. vertices[ face.b ].add( face.normal );
  5043. vertices[ face.c ].add( face.normal );
  5044. }
  5045. }
  5046. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5047. vertices[ v ].normalize();
  5048. }
  5049. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5050. face = this.faces[ f ];
  5051. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  5052. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  5053. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  5054. }
  5055. },
  5056. computeMorphNormals: function () {
  5057. var i, il, f, fl, face;
  5058. // save original normals
  5059. // - create temp variables on first access
  5060. // otherwise just copy (for faster repeated calls)
  5061. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5062. face = this.faces[ f ];
  5063. if ( ! face.__originalFaceNormal ) {
  5064. face.__originalFaceNormal = face.normal.clone();
  5065. } else {
  5066. face.__originalFaceNormal.copy( face.normal );
  5067. }
  5068. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5069. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5070. if ( ! face.__originalVertexNormals[ i ] ) {
  5071. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5072. } else {
  5073. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  5074. }
  5075. }
  5076. }
  5077. // use temp geometry to compute face and vertex normals for each morph
  5078. var tmpGeo = new THREE.Geometry();
  5079. tmpGeo.faces = this.faces;
  5080. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  5081. // create on first access
  5082. if ( ! this.morphNormals[ i ] ) {
  5083. this.morphNormals[ i ] = {};
  5084. this.morphNormals[ i ].faceNormals = [];
  5085. this.morphNormals[ i ].vertexNormals = [];
  5086. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  5087. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  5088. var faceNormal, vertexNormals;
  5089. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5090. face = this.faces[ f ];
  5091. faceNormal = new THREE.Vector3();
  5092. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5093. dstNormalsFace.push( faceNormal );
  5094. dstNormalsVertex.push( vertexNormals );
  5095. }
  5096. }
  5097. var morphNormals = this.morphNormals[ i ];
  5098. // set vertices to morph target
  5099. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5100. // compute morph normals
  5101. tmpGeo.computeFaceNormals();
  5102. tmpGeo.computeVertexNormals();
  5103. // store morph normals
  5104. var faceNormal, vertexNormals;
  5105. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5106. face = this.faces[ f ];
  5107. faceNormal = morphNormals.faceNormals[ f ];
  5108. vertexNormals = morphNormals.vertexNormals[ f ];
  5109. faceNormal.copy( face.normal );
  5110. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5111. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5112. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5113. }
  5114. }
  5115. // restore original normals
  5116. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5117. face = this.faces[ f ];
  5118. face.normal = face.__originalFaceNormal;
  5119. face.vertexNormals = face.__originalVertexNormals;
  5120. }
  5121. },
  5122. computeTangents: function () {
  5123. // based on http://www.terathon.com/code/tangent.html
  5124. // tangents go to vertices
  5125. var f, fl, v, vl, i, il, vertexIndex,
  5126. face, uv, vA, vB, vC, uvA, uvB, uvC,
  5127. x1, x2, y1, y2, z1, z2,
  5128. s1, s2, t1, t2, r, t, test,
  5129. tan1 = [], tan2 = [],
  5130. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  5131. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  5132. n = new THREE.Vector3(), w;
  5133. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5134. tan1[ v ] = new THREE.Vector3();
  5135. tan2[ v ] = new THREE.Vector3();
  5136. }
  5137. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  5138. vA = context.vertices[ a ];
  5139. vB = context.vertices[ b ];
  5140. vC = context.vertices[ c ];
  5141. uvA = uv[ ua ];
  5142. uvB = uv[ ub ];
  5143. uvC = uv[ uc ];
  5144. x1 = vB.x - vA.x;
  5145. x2 = vC.x - vA.x;
  5146. y1 = vB.y - vA.y;
  5147. y2 = vC.y - vA.y;
  5148. z1 = vB.z - vA.z;
  5149. z2 = vC.z - vA.z;
  5150. s1 = uvB.x - uvA.x;
  5151. s2 = uvC.x - uvA.x;
  5152. t1 = uvB.y - uvA.y;
  5153. t2 = uvC.y - uvA.y;
  5154. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5155. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  5156. ( t2 * y1 - t1 * y2 ) * r,
  5157. ( t2 * z1 - t1 * z2 ) * r );
  5158. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  5159. ( s1 * y2 - s2 * y1 ) * r,
  5160. ( s1 * z2 - s2 * z1 ) * r );
  5161. tan1[ a ].add( sdir );
  5162. tan1[ b ].add( sdir );
  5163. tan1[ c ].add( sdir );
  5164. tan2[ a ].add( tdir );
  5165. tan2[ b ].add( tdir );
  5166. tan2[ c ].add( tdir );
  5167. }
  5168. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5169. face = this.faces[ f ];
  5170. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  5171. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  5172. }
  5173. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  5174. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5175. face = this.faces[ f ];
  5176. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i++ ) {
  5177. n.copy( face.vertexNormals[ i ] );
  5178. vertexIndex = face[ faceIndex[ i ] ];
  5179. t = tan1[ vertexIndex ];
  5180. // Gram-Schmidt orthogonalize
  5181. tmp.copy( t );
  5182. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5183. // Calculate handedness
  5184. tmp2.crossVectors( face.vertexNormals[ i ], t );
  5185. test = tmp2.dot( tan2[ vertexIndex ] );
  5186. w = (test < 0.0) ? -1.0 : 1.0;
  5187. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  5188. }
  5189. }
  5190. this.hasTangents = true;
  5191. },
  5192. computeLineDistances: function ( ) {
  5193. var d = 0;
  5194. var vertices = this.vertices;
  5195. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5196. if ( i > 0 ) {
  5197. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  5198. }
  5199. this.lineDistances[ i ] = d;
  5200. }
  5201. },
  5202. computeBoundingBox: function () {
  5203. if ( this.boundingBox === null ) {
  5204. this.boundingBox = new THREE.Box3();
  5205. }
  5206. this.boundingBox.setFromPoints( this.vertices );
  5207. },
  5208. computeBoundingSphere: function () {
  5209. if ( this.boundingSphere === null ) {
  5210. this.boundingSphere = new THREE.Sphere();
  5211. }
  5212. this.boundingSphere.setFromPoints( this.vertices );
  5213. },
  5214. /*
  5215. * Checks for duplicate vertices with hashmap.
  5216. * Duplicated vertices are removed
  5217. * and faces' vertices are updated.
  5218. */
  5219. mergeVertices: function () {
  5220. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  5221. var unique = [], changes = [];
  5222. var v, key;
  5223. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  5224. var precision = Math.pow( 10, precisionPoints );
  5225. var i,il, face;
  5226. var indices, k, j, jl, u;
  5227. // reset cache of vertices as it now will be changing.
  5228. this.__tmpVertices = undefined;
  5229. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  5230. v = this.vertices[ i ];
  5231. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  5232. if ( verticesMap[ key ] === undefined ) {
  5233. verticesMap[ key ] = i;
  5234. unique.push( this.vertices[ i ] );
  5235. changes[ i ] = unique.length - 1;
  5236. } else {
  5237. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  5238. changes[ i ] = changes[ verticesMap[ key ] ];
  5239. }
  5240. };
  5241. // if faces are completely degenerate after merging vertices, we
  5242. // have to remove them from the geometry.
  5243. var faceIndicesToRemove = [];
  5244. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  5245. face = this.faces[ i ];
  5246. face.a = changes[ face.a ];
  5247. face.b = changes[ face.b ];
  5248. face.c = changes[ face.c ];
  5249. indices = [ face.a, face.b, face.c ];
  5250. var dupIndex = -1;
  5251. // if any duplicate vertices are found in a Face3
  5252. // we have to remove the face as nothing can be saved
  5253. for ( var n = 0; n < 3; n ++ ) {
  5254. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  5255. dupIndex = n;
  5256. faceIndicesToRemove.push( i );
  5257. break;
  5258. }
  5259. }
  5260. }
  5261. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  5262. var idx = faceIndicesToRemove[ i ];
  5263. this.faces.splice( idx, 1 );
  5264. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5265. this.faceVertexUvs[ j ].splice( idx, 1 );
  5266. }
  5267. }
  5268. // Use unique set of vertices
  5269. var diff = this.vertices.length - unique.length;
  5270. this.vertices = unique;
  5271. return diff;
  5272. },
  5273. clone: function () {
  5274. var geometry = new THREE.Geometry();
  5275. var vertices = this.vertices;
  5276. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5277. geometry.vertices.push( vertices[ i ].clone() );
  5278. }
  5279. var faces = this.faces;
  5280. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  5281. geometry.faces.push( faces[ i ].clone() );
  5282. }
  5283. var uvs = this.faceVertexUvs[ 0 ];
  5284. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  5285. var uv = uvs[ i ], uvCopy = [];
  5286. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5287. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  5288. }
  5289. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  5290. }
  5291. return geometry;
  5292. },
  5293. dispose: function () {
  5294. this.dispatchEvent( { type: 'dispose' } );
  5295. }
  5296. };
  5297. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  5298. THREE.GeometryIdCount = 0;
  5299. /**
  5300. * @author alteredq / http://alteredqualia.com/
  5301. */
  5302. THREE.BufferGeometry = function () {
  5303. this.id = THREE.GeometryIdCount ++;
  5304. this.uuid = THREE.Math.generateUUID();
  5305. this.name = '';
  5306. // attributes
  5307. this.attributes = {};
  5308. // attributes typed arrays are kept only if dynamic flag is set
  5309. this.dynamic = true;
  5310. // offsets for chunks when using indexed elements
  5311. this.offsets = [];
  5312. // boundings
  5313. this.boundingBox = null;
  5314. this.boundingSphere = null;
  5315. this.hasTangents = false;
  5316. // for compatibility
  5317. this.morphTargets = [];
  5318. };
  5319. THREE.BufferGeometry.prototype = {
  5320. constructor: THREE.BufferGeometry,
  5321. addAttribute: function( name, type, numItems, itemSize ) {
  5322. this.attributes[ name ] = {
  5323. itemSize: itemSize,
  5324. array: new type( numItems * itemSize )
  5325. };
  5326. },
  5327. applyMatrix: function ( matrix ) {
  5328. var positionArray;
  5329. var normalArray;
  5330. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  5331. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  5332. if ( positionArray !== undefined ) {
  5333. matrix.multiplyVector3Array( positionArray );
  5334. this.verticesNeedUpdate = true;
  5335. }
  5336. if ( normalArray !== undefined ) {
  5337. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5338. normalMatrix.multiplyVector3Array( normalArray );
  5339. this.normalizeNormals();
  5340. this.normalsNeedUpdate = true;
  5341. }
  5342. },
  5343. computeBoundingBox: function () {
  5344. if ( this.boundingBox === null ) {
  5345. this.boundingBox = new THREE.Box3();
  5346. }
  5347. var positions = this.attributes[ "position" ].array;
  5348. if ( positions ) {
  5349. var bb = this.boundingBox;
  5350. var x, y, z;
  5351. if( positions.length >= 3 ) {
  5352. bb.min.x = bb.max.x = positions[ 0 ];
  5353. bb.min.y = bb.max.y = positions[ 1 ];
  5354. bb.min.z = bb.max.z = positions[ 2 ];
  5355. }
  5356. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5357. x = positions[ i ];
  5358. y = positions[ i + 1 ];
  5359. z = positions[ i + 2 ];
  5360. // bounding box
  5361. if ( x < bb.min.x ) {
  5362. bb.min.x = x;
  5363. } else if ( x > bb.max.x ) {
  5364. bb.max.x = x;
  5365. }
  5366. if ( y < bb.min.y ) {
  5367. bb.min.y = y;
  5368. } else if ( y > bb.max.y ) {
  5369. bb.max.y = y;
  5370. }
  5371. if ( z < bb.min.z ) {
  5372. bb.min.z = z;
  5373. } else if ( z > bb.max.z ) {
  5374. bb.max.z = z;
  5375. }
  5376. }
  5377. }
  5378. if ( positions === undefined || positions.length === 0 ) {
  5379. this.boundingBox.min.set( 0, 0, 0 );
  5380. this.boundingBox.max.set( 0, 0, 0 );
  5381. }
  5382. },
  5383. computeBoundingSphere: function () {
  5384. var box = new THREE.Box3();
  5385. var vector = new THREE.Vector3();
  5386. return function () {
  5387. if ( this.boundingSphere === null ) {
  5388. this.boundingSphere = new THREE.Sphere();
  5389. }
  5390. var positions = this.attributes[ "position" ].array;
  5391. if ( positions ) {
  5392. var center = this.boundingSphere.center;
  5393. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5394. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5395. box.addPoint( vector );
  5396. }
  5397. box.center( center );
  5398. var maxRadiusSq = 0;
  5399. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5400. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5401. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5402. }
  5403. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5404. }
  5405. }
  5406. }(),
  5407. computeVertexNormals: function () {
  5408. if ( this.attributes[ "position" ] ) {
  5409. var i, il;
  5410. var j, jl;
  5411. var nVertexElements = this.attributes[ "position" ].array.length;
  5412. if ( this.attributes[ "normal" ] === undefined ) {
  5413. this.attributes[ "normal" ] = {
  5414. itemSize: 3,
  5415. array: new Float32Array( nVertexElements )
  5416. };
  5417. } else {
  5418. // reset existing normals to zero
  5419. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5420. this.attributes[ "normal" ].array[ i ] = 0;
  5421. }
  5422. }
  5423. var positions = this.attributes[ "position" ].array;
  5424. var normals = this.attributes[ "normal" ].array;
  5425. var vA, vB, vC, x, y, z,
  5426. pA = new THREE.Vector3(),
  5427. pB = new THREE.Vector3(),
  5428. pC = new THREE.Vector3(),
  5429. cb = new THREE.Vector3(),
  5430. ab = new THREE.Vector3();
  5431. // indexed elements
  5432. if ( this.attributes[ "index" ] ) {
  5433. var indices = this.attributes[ "index" ].array;
  5434. var offsets = this.offsets;
  5435. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5436. var start = offsets[ j ].start;
  5437. var count = offsets[ j ].count;
  5438. var index = offsets[ j ].index;
  5439. for ( i = start, il = start + count; i < il; i += 3 ) {
  5440. vA = index + indices[ i ];
  5441. vB = index + indices[ i + 1 ];
  5442. vC = index + indices[ i + 2 ];
  5443. x = positions[ vA * 3 ];
  5444. y = positions[ vA * 3 + 1 ];
  5445. z = positions[ vA * 3 + 2 ];
  5446. pA.set( x, y, z );
  5447. x = positions[ vB * 3 ];
  5448. y = positions[ vB * 3 + 1 ];
  5449. z = positions[ vB * 3 + 2 ];
  5450. pB.set( x, y, z );
  5451. x = positions[ vC * 3 ];
  5452. y = positions[ vC * 3 + 1 ];
  5453. z = positions[ vC * 3 + 2 ];
  5454. pC.set( x, y, z );
  5455. cb.subVectors( pC, pB );
  5456. ab.subVectors( pA, pB );
  5457. cb.cross( ab );
  5458. normals[ vA * 3 ] += cb.x;
  5459. normals[ vA * 3 + 1 ] += cb.y;
  5460. normals[ vA * 3 + 2 ] += cb.z;
  5461. normals[ vB * 3 ] += cb.x;
  5462. normals[ vB * 3 + 1 ] += cb.y;
  5463. normals[ vB * 3 + 2 ] += cb.z;
  5464. normals[ vC * 3 ] += cb.x;
  5465. normals[ vC * 3 + 1 ] += cb.y;
  5466. normals[ vC * 3 + 2 ] += cb.z;
  5467. }
  5468. }
  5469. // non-indexed elements (unconnected triangle soup)
  5470. } else {
  5471. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5472. x = positions[ i ];
  5473. y = positions[ i + 1 ];
  5474. z = positions[ i + 2 ];
  5475. pA.set( x, y, z );
  5476. x = positions[ i + 3 ];
  5477. y = positions[ i + 4 ];
  5478. z = positions[ i + 5 ];
  5479. pB.set( x, y, z );
  5480. x = positions[ i + 6 ];
  5481. y = positions[ i + 7 ];
  5482. z = positions[ i + 8 ];
  5483. pC.set( x, y, z );
  5484. cb.subVectors( pC, pB );
  5485. ab.subVectors( pA, pB );
  5486. cb.cross( ab );
  5487. normals[ i ] = cb.x;
  5488. normals[ i + 1 ] = cb.y;
  5489. normals[ i + 2 ] = cb.z;
  5490. normals[ i + 3 ] = cb.x;
  5491. normals[ i + 4 ] = cb.y;
  5492. normals[ i + 5 ] = cb.z;
  5493. normals[ i + 6 ] = cb.x;
  5494. normals[ i + 7 ] = cb.y;
  5495. normals[ i + 8 ] = cb.z;
  5496. }
  5497. }
  5498. this.normalizeNormals();
  5499. this.normalsNeedUpdate = true;
  5500. }
  5501. },
  5502. normalizeNormals: function () {
  5503. var normals = this.attributes[ "normal" ].array;
  5504. var x, y, z, n;
  5505. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5506. x = normals[ i ];
  5507. y = normals[ i + 1 ];
  5508. z = normals[ i + 2 ];
  5509. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5510. normals[ i ] *= n;
  5511. normals[ i + 1 ] *= n;
  5512. normals[ i + 2 ] *= n;
  5513. }
  5514. },
  5515. computeTangents: function () {
  5516. // based on http://www.terathon.com/code/tangent.html
  5517. // (per vertex tangents)
  5518. if ( this.attributes[ "index" ] === undefined ||
  5519. this.attributes[ "position" ] === undefined ||
  5520. this.attributes[ "normal" ] === undefined ||
  5521. this.attributes[ "uv" ] === undefined ) {
  5522. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5523. return;
  5524. }
  5525. var indices = this.attributes[ "index" ].array;
  5526. var positions = this.attributes[ "position" ].array;
  5527. var normals = this.attributes[ "normal" ].array;
  5528. var uvs = this.attributes[ "uv" ].array;
  5529. var nVertices = positions.length / 3;
  5530. if ( this.attributes[ "tangent" ] === undefined ) {
  5531. var nTangentElements = 4 * nVertices;
  5532. this.attributes[ "tangent" ] = {
  5533. itemSize: 4,
  5534. array: new Float32Array( nTangentElements )
  5535. };
  5536. }
  5537. var tangents = this.attributes[ "tangent" ].array;
  5538. var tan1 = [], tan2 = [];
  5539. for ( var k = 0; k < nVertices; k ++ ) {
  5540. tan1[ k ] = new THREE.Vector3();
  5541. tan2[ k ] = new THREE.Vector3();
  5542. }
  5543. var xA, yA, zA,
  5544. xB, yB, zB,
  5545. xC, yC, zC,
  5546. uA, vA,
  5547. uB, vB,
  5548. uC, vC,
  5549. x1, x2, y1, y2, z1, z2,
  5550. s1, s2, t1, t2, r;
  5551. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5552. function handleTriangle( a, b, c ) {
  5553. xA = positions[ a * 3 ];
  5554. yA = positions[ a * 3 + 1 ];
  5555. zA = positions[ a * 3 + 2 ];
  5556. xB = positions[ b * 3 ];
  5557. yB = positions[ b * 3 + 1 ];
  5558. zB = positions[ b * 3 + 2 ];
  5559. xC = positions[ c * 3 ];
  5560. yC = positions[ c * 3 + 1 ];
  5561. zC = positions[ c * 3 + 2 ];
  5562. uA = uvs[ a * 2 ];
  5563. vA = uvs[ a * 2 + 1 ];
  5564. uB = uvs[ b * 2 ];
  5565. vB = uvs[ b * 2 + 1 ];
  5566. uC = uvs[ c * 2 ];
  5567. vC = uvs[ c * 2 + 1 ];
  5568. x1 = xB - xA;
  5569. x2 = xC - xA;
  5570. y1 = yB - yA;
  5571. y2 = yC - yA;
  5572. z1 = zB - zA;
  5573. z2 = zC - zA;
  5574. s1 = uB - uA;
  5575. s2 = uC - uA;
  5576. t1 = vB - vA;
  5577. t2 = vC - vA;
  5578. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5579. sdir.set(
  5580. ( t2 * x1 - t1 * x2 ) * r,
  5581. ( t2 * y1 - t1 * y2 ) * r,
  5582. ( t2 * z1 - t1 * z2 ) * r
  5583. );
  5584. tdir.set(
  5585. ( s1 * x2 - s2 * x1 ) * r,
  5586. ( s1 * y2 - s2 * y1 ) * r,
  5587. ( s1 * z2 - s2 * z1 ) * r
  5588. );
  5589. tan1[ a ].add( sdir );
  5590. tan1[ b ].add( sdir );
  5591. tan1[ c ].add( sdir );
  5592. tan2[ a ].add( tdir );
  5593. tan2[ b ].add( tdir );
  5594. tan2[ c ].add( tdir );
  5595. }
  5596. var i, il;
  5597. var j, jl;
  5598. var iA, iB, iC;
  5599. var offsets = this.offsets;
  5600. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5601. var start = offsets[ j ].start;
  5602. var count = offsets[ j ].count;
  5603. var index = offsets[ j ].index;
  5604. for ( i = start, il = start + count; i < il; i += 3 ) {
  5605. iA = index + indices[ i ];
  5606. iB = index + indices[ i + 1 ];
  5607. iC = index + indices[ i + 2 ];
  5608. handleTriangle( iA, iB, iC );
  5609. }
  5610. }
  5611. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5612. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5613. var w, t, test;
  5614. function handleVertex( v ) {
  5615. n.x = normals[ v * 3 ];
  5616. n.y = normals[ v * 3 + 1 ];
  5617. n.z = normals[ v * 3 + 2 ];
  5618. n2.copy( n );
  5619. t = tan1[ v ];
  5620. // Gram-Schmidt orthogonalize
  5621. tmp.copy( t );
  5622. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5623. // Calculate handedness
  5624. tmp2.crossVectors( n2, t );
  5625. test = tmp2.dot( tan2[ v ] );
  5626. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5627. tangents[ v * 4 ] = tmp.x;
  5628. tangents[ v * 4 + 1 ] = tmp.y;
  5629. tangents[ v * 4 + 2 ] = tmp.z;
  5630. tangents[ v * 4 + 3 ] = w;
  5631. }
  5632. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5633. var start = offsets[ j ].start;
  5634. var count = offsets[ j ].count;
  5635. var index = offsets[ j ].index;
  5636. for ( i = start, il = start + count; i < il; i += 3 ) {
  5637. iA = index + indices[ i ];
  5638. iB = index + indices[ i + 1 ];
  5639. iC = index + indices[ i + 2 ];
  5640. handleVertex( iA );
  5641. handleVertex( iB );
  5642. handleVertex( iC );
  5643. }
  5644. }
  5645. this.hasTangents = true;
  5646. this.tangentsNeedUpdate = true;
  5647. },
  5648. clone: function () {
  5649. var geometry = new THREE.BufferGeometry();
  5650. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5651. for ( var attr in this.attributes ) {
  5652. var sourceAttr = this.attributes[ attr ];
  5653. var sourceArray = sourceAttr.array;
  5654. var attribute = {
  5655. itemSize: sourceAttr.itemSize,
  5656. numItems: sourceAttr.numItems,
  5657. array: null
  5658. };
  5659. for ( var i = 0, il = types.length; i < il; i ++ ) {
  5660. var type = types[ i ];
  5661. if ( sourceArray instanceof type ) {
  5662. attribute.array = new type( sourceArray );
  5663. break;
  5664. }
  5665. }
  5666. geometry.attributes[ attr ] = attribute;
  5667. }
  5668. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  5669. var offset = this.offsets[ i ];
  5670. geometry.offsets.push( {
  5671. start: offset.start,
  5672. index: offset.index,
  5673. count: offset.count
  5674. } );
  5675. }
  5676. return geometry;
  5677. },
  5678. dispose: function () {
  5679. this.dispatchEvent( { type: 'dispose' } );
  5680. }
  5681. };
  5682. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  5683. /**
  5684. * @author mrdoob / http://mrdoob.com/
  5685. * @author mikael emtinger / http://gomo.se/
  5686. * @author WestLangley / http://github.com/WestLangley
  5687. */
  5688. THREE.Camera = function () {
  5689. THREE.Object3D.call( this );
  5690. this.matrixWorldInverse = new THREE.Matrix4();
  5691. this.projectionMatrix = new THREE.Matrix4();
  5692. this.projectionMatrixInverse = new THREE.Matrix4();
  5693. };
  5694. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5695. THREE.Camera.prototype.lookAt = function () {
  5696. // This routine does not support cameras with rotated and/or translated parent(s)
  5697. var m1 = new THREE.Matrix4();
  5698. return function ( vector ) {
  5699. m1.lookAt( this.position, vector, this.up );
  5700. this.quaternion.setFromRotationMatrix( m1 );
  5701. };
  5702. }();
  5703. THREE.Camera.prototype.clone = function (camera) {
  5704. if ( camera === undefined ) camera = new THREE.Camera();
  5705. THREE.Object3D.prototype.clone.call( this, camera );
  5706. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  5707. camera.projectionMatrix.copy( this.projectionMatrix );
  5708. camera.projectionMatrixInverse.copy( this.projectionMatrixInverse );
  5709. return camera;
  5710. };
  5711. /**
  5712. * @author alteredq / http://alteredqualia.com/
  5713. */
  5714. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5715. THREE.Camera.call( this );
  5716. this.left = left;
  5717. this.right = right;
  5718. this.top = top;
  5719. this.bottom = bottom;
  5720. this.near = ( near !== undefined ) ? near : 0.1;
  5721. this.far = ( far !== undefined ) ? far : 2000;
  5722. this.updateProjectionMatrix();
  5723. };
  5724. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5725. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5726. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5727. };
  5728. THREE.OrthographicCamera.prototype.clone = function () {
  5729. var camera = new THREE.OrthographicCamera();
  5730. THREE.Camera.prototype.clone.call( this, camera );
  5731. camera.left = this.left;
  5732. camera.right = this.right;
  5733. camera.top = this.top;
  5734. camera.bottom = this.bottom;
  5735. camera.near = this.near;
  5736. camera.far = this.far;
  5737. return camera;
  5738. };
  5739. /**
  5740. * @author mrdoob / http://mrdoob.com/
  5741. * @author greggman / http://games.greggman.com/
  5742. * @author zz85 / http://www.lab4games.net/zz85/blog
  5743. */
  5744. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5745. THREE.Camera.call( this );
  5746. this.fov = fov !== undefined ? fov : 50;
  5747. this.aspect = aspect !== undefined ? aspect : 1;
  5748. this.near = near !== undefined ? near : 0.1;
  5749. this.far = far !== undefined ? far : 2000;
  5750. this.updateProjectionMatrix();
  5751. };
  5752. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5753. /**
  5754. * Uses Focal Length (in mm) to estimate and set FOV
  5755. * 35mm (fullframe) camera is used if frame size is not specified;
  5756. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5757. */
  5758. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5759. if ( frameHeight === undefined ) frameHeight = 24;
  5760. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5761. this.updateProjectionMatrix();
  5762. }
  5763. /**
  5764. * Sets an offset in a larger frustum. This is useful for multi-window or
  5765. * multi-monitor/multi-machine setups.
  5766. *
  5767. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5768. * the monitors are in grid like this
  5769. *
  5770. * +---+---+---+
  5771. * | A | B | C |
  5772. * +---+---+---+
  5773. * | D | E | F |
  5774. * +---+---+---+
  5775. *
  5776. * then for each monitor you would call it like this
  5777. *
  5778. * var w = 1920;
  5779. * var h = 1080;
  5780. * var fullWidth = w * 3;
  5781. * var fullHeight = h * 2;
  5782. *
  5783. * --A--
  5784. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5785. * --B--
  5786. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5787. * --C--
  5788. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5789. * --D--
  5790. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5791. * --E--
  5792. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5793. * --F--
  5794. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5795. *
  5796. * Note there is no reason monitors have to be the same size or in a grid.
  5797. */
  5798. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5799. this.fullWidth = fullWidth;
  5800. this.fullHeight = fullHeight;
  5801. this.x = x;
  5802. this.y = y;
  5803. this.width = width;
  5804. this.height = height;
  5805. this.updateProjectionMatrix();
  5806. };
  5807. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5808. if ( this.fullWidth ) {
  5809. var aspect = this.fullWidth / this.fullHeight;
  5810. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5811. var bottom = -top;
  5812. var left = aspect * bottom;
  5813. var right = aspect * top;
  5814. var width = Math.abs( right - left );
  5815. var height = Math.abs( top - bottom );
  5816. this.projectionMatrix.makeFrustum(
  5817. left + this.x * width / this.fullWidth,
  5818. left + ( this.x + this.width ) * width / this.fullWidth,
  5819. top - ( this.y + this.height ) * height / this.fullHeight,
  5820. top - this.y * height / this.fullHeight,
  5821. this.near,
  5822. this.far
  5823. );
  5824. } else {
  5825. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5826. }
  5827. };
  5828. THREE.PerspectiveCamera.prototype.clone = function () {
  5829. var camera = new THREE.PerspectiveCamera();
  5830. THREE.Camera.prototype.clone.call( this, camera );
  5831. camera.fov = this.fov;
  5832. camera.aspect = this.aspect;
  5833. camera.near = this.near;
  5834. camera.far = this.far;
  5835. return camera;
  5836. };
  5837. /**
  5838. * @author mrdoob / http://mrdoob.com/
  5839. * @author alteredq / http://alteredqualia.com/
  5840. */
  5841. THREE.Light = function ( hex ) {
  5842. THREE.Object3D.call( this );
  5843. this.color = new THREE.Color( hex );
  5844. };
  5845. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5846. THREE.Light.prototype.clone = function ( light ) {
  5847. if ( light === undefined ) light = new THREE.Light();
  5848. THREE.Object3D.prototype.clone.call( this, light );
  5849. light.color.copy( this.color );
  5850. return light;
  5851. };
  5852. /**
  5853. * @author mrdoob / http://mrdoob.com/
  5854. */
  5855. THREE.AmbientLight = function ( hex ) {
  5856. THREE.Light.call( this, hex );
  5857. };
  5858. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5859. THREE.AmbientLight.prototype.clone = function () {
  5860. var light = new THREE.AmbientLight();
  5861. THREE.Light.prototype.clone.call( this, light );
  5862. return light;
  5863. };
  5864. /**
  5865. * @author MPanknin / http://www.redplant.de/
  5866. * @author alteredq / http://alteredqualia.com/
  5867. */
  5868. THREE.AreaLight = function ( hex, intensity ) {
  5869. THREE.Light.call( this, hex );
  5870. this.normal = new THREE.Vector3( 0, -1, 0 );
  5871. this.right = new THREE.Vector3( 1, 0, 0 );
  5872. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5873. this.width = 1.0;
  5874. this.height = 1.0;
  5875. this.constantAttenuation = 1.5;
  5876. this.linearAttenuation = 0.5;
  5877. this.quadraticAttenuation = 0.1;
  5878. };
  5879. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5880. /**
  5881. * @author mrdoob / http://mrdoob.com/
  5882. * @author alteredq / http://alteredqualia.com/
  5883. */
  5884. THREE.DirectionalLight = function ( hex, intensity ) {
  5885. THREE.Light.call( this, hex );
  5886. this.position.set( 0, 1, 0 );
  5887. this.target = new THREE.Object3D();
  5888. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5889. this.castShadow = false;
  5890. this.onlyShadow = false;
  5891. //
  5892. this.shadowCameraNear = 50;
  5893. this.shadowCameraFar = 5000;
  5894. this.shadowCameraLeft = -500;
  5895. this.shadowCameraRight = 500;
  5896. this.shadowCameraTop = 500;
  5897. this.shadowCameraBottom = -500;
  5898. this.shadowCameraVisible = false;
  5899. this.shadowBias = 0;
  5900. this.shadowDarkness = 0.5;
  5901. this.shadowMapWidth = 512;
  5902. this.shadowMapHeight = 512;
  5903. //
  5904. this.shadowCascade = false;
  5905. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5906. this.shadowCascadeCount = 2;
  5907. this.shadowCascadeBias = [ 0, 0, 0 ];
  5908. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5909. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5910. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5911. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5912. this.shadowCascadeArray = [];
  5913. //
  5914. this.shadowMap = null;
  5915. this.shadowMapSize = null;
  5916. this.shadowCamera = null;
  5917. this.shadowMatrix = null;
  5918. };
  5919. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5920. THREE.DirectionalLight.prototype.clone = function () {
  5921. var light = new THREE.DirectionalLight();
  5922. THREE.Light.prototype.clone.call( this, light );
  5923. light.target = this.target.clone();
  5924. light.intensity = this.intensity;
  5925. light.castShadow = this.castShadow;
  5926. light.onlyShadow = this.onlyShadow;
  5927. return light;
  5928. };
  5929. /**
  5930. * @author alteredq / http://alteredqualia.com/
  5931. */
  5932. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5933. THREE.Light.call( this, skyColorHex );
  5934. this.position.set( 0, 100, 0 );
  5935. this.groundColor = new THREE.Color( groundColorHex );
  5936. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5937. };
  5938. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5939. THREE.HemisphereLight.prototype.clone = function () {
  5940. var light = new THREE.HemisphereLight();
  5941. THREE.Light.prototype.clone.call( this, light );
  5942. light.groundColor.copy( this.groundColor );
  5943. light.intensity = this.intensity;
  5944. return light;
  5945. };
  5946. /**
  5947. * @author mrdoob / http://mrdoob.com/
  5948. */
  5949. THREE.PointLight = function ( hex, intensity, distance ) {
  5950. THREE.Light.call( this, hex );
  5951. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5952. this.distance = ( distance !== undefined ) ? distance : 0;
  5953. };
  5954. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5955. THREE.PointLight.prototype.clone = function () {
  5956. var light = new THREE.PointLight();
  5957. THREE.Light.prototype.clone.call( this, light );
  5958. light.intensity = this.intensity;
  5959. light.distance = this.distance;
  5960. return light;
  5961. };
  5962. /**
  5963. * @author alteredq / http://alteredqualia.com/
  5964. */
  5965. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5966. THREE.Light.call( this, hex );
  5967. this.position.set( 0, 1, 0 );
  5968. this.target = new THREE.Object3D();
  5969. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5970. this.distance = ( distance !== undefined ) ? distance : 0;
  5971. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  5972. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5973. this.castShadow = false;
  5974. this.onlyShadow = false;
  5975. //
  5976. this.shadowCameraNear = 50;
  5977. this.shadowCameraFar = 5000;
  5978. this.shadowCameraFov = 50;
  5979. this.shadowCameraVisible = false;
  5980. this.shadowBias = 0;
  5981. this.shadowDarkness = 0.5;
  5982. this.shadowMapWidth = 512;
  5983. this.shadowMapHeight = 512;
  5984. //
  5985. this.shadowMap = null;
  5986. this.shadowMapSize = null;
  5987. this.shadowCamera = null;
  5988. this.shadowMatrix = null;
  5989. };
  5990. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  5991. THREE.SpotLight.prototype.clone = function () {
  5992. var light = new THREE.SpotLight();
  5993. THREE.Light.prototype.clone.call( this, light );
  5994. light.target = this.target.clone();
  5995. light.intensity = this.intensity;
  5996. light.distance = this.distance;
  5997. light.angle = this.angle;
  5998. light.exponent = this.exponent;
  5999. light.castShadow = this.castShadow;
  6000. light.onlyShadow = this.onlyShadow;
  6001. return light;
  6002. };
  6003. /**
  6004. * @author alteredq / http://alteredqualia.com/
  6005. */
  6006. THREE.Loader = function ( showStatus ) {
  6007. this.showStatus = showStatus;
  6008. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6009. this.onLoadStart = function () {};
  6010. this.onLoadProgress = function () {};
  6011. this.onLoadComplete = function () {};
  6012. };
  6013. THREE.Loader.prototype = {
  6014. constructor: THREE.Loader,
  6015. crossOrigin: 'anonymous',
  6016. addStatusElement: function () {
  6017. var e = document.createElement( "div" );
  6018. e.style.position = "absolute";
  6019. e.style.right = "0px";
  6020. e.style.top = "0px";
  6021. e.style.fontSize = "0.8em";
  6022. e.style.textAlign = "left";
  6023. e.style.background = "rgba(0,0,0,0.25)";
  6024. e.style.color = "#fff";
  6025. e.style.width = "120px";
  6026. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  6027. e.style.zIndex = 1000;
  6028. e.innerHTML = "Loading ...";
  6029. return e;
  6030. },
  6031. updateProgress: function ( progress ) {
  6032. var message = "Loaded ";
  6033. if ( progress.total ) {
  6034. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  6035. } else {
  6036. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  6037. }
  6038. this.statusDomElement.innerHTML = message;
  6039. },
  6040. extractUrlBase: function ( url ) {
  6041. var parts = url.split( '/' );
  6042. parts.pop();
  6043. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  6044. },
  6045. initMaterials: function ( materials, texturePath ) {
  6046. var array = [];
  6047. for ( var i = 0; i < materials.length; ++ i ) {
  6048. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  6049. }
  6050. return array;
  6051. },
  6052. needsTangents: function ( materials ) {
  6053. for( var i = 0, il = materials.length; i < il; i ++ ) {
  6054. var m = materials[ i ];
  6055. if ( m instanceof THREE.ShaderMaterial ) return true;
  6056. }
  6057. return false;
  6058. },
  6059. createMaterial: function ( m, texturePath ) {
  6060. var _this = this;
  6061. function is_pow2( n ) {
  6062. var l = Math.log( n ) / Math.LN2;
  6063. return Math.floor( l ) == l;
  6064. }
  6065. function nearest_pow2( n ) {
  6066. var l = Math.log( n ) / Math.LN2;
  6067. return Math.pow( 2, Math.round( l ) );
  6068. }
  6069. function load_image( where, url ) {
  6070. var image = new Image();
  6071. image.onload = function () {
  6072. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  6073. var width = nearest_pow2( this.width );
  6074. var height = nearest_pow2( this.height );
  6075. where.image.width = width;
  6076. where.image.height = height;
  6077. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  6078. } else {
  6079. where.image = this;
  6080. }
  6081. where.needsUpdate = true;
  6082. };
  6083. image.crossOrigin = _this.crossOrigin;
  6084. image.src = url;
  6085. }
  6086. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  6087. var isCompressed = /\.dds$/i.test( sourceFile );
  6088. var fullPath = texturePath + "/" + sourceFile;
  6089. if ( isCompressed ) {
  6090. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  6091. where[ name ] = texture;
  6092. } else {
  6093. var texture = document.createElement( 'canvas' );
  6094. where[ name ] = new THREE.Texture( texture );
  6095. }
  6096. where[ name ].sourceFile = sourceFile;
  6097. if( repeat ) {
  6098. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6099. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  6100. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  6101. }
  6102. if ( offset ) {
  6103. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  6104. }
  6105. if ( wrap ) {
  6106. var wrapMap = {
  6107. "repeat": THREE.RepeatWrapping,
  6108. "mirror": THREE.MirroredRepeatWrapping
  6109. }
  6110. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  6111. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  6112. }
  6113. if ( anisotropy ) {
  6114. where[ name ].anisotropy = anisotropy;
  6115. }
  6116. if ( ! isCompressed ) {
  6117. load_image( where[ name ], fullPath );
  6118. }
  6119. }
  6120. function rgb2hex( rgb ) {
  6121. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6122. }
  6123. // defaults
  6124. var mtype = "MeshLambertMaterial";
  6125. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  6126. // parameters from model file
  6127. if ( m.shading ) {
  6128. var shading = m.shading.toLowerCase();
  6129. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  6130. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  6131. }
  6132. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6133. mpars.blending = THREE[ m.blending ];
  6134. }
  6135. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  6136. mpars.transparent = m.transparent;
  6137. }
  6138. if ( m.depthTest !== undefined ) {
  6139. mpars.depthTest = m.depthTest;
  6140. }
  6141. if ( m.depthWrite !== undefined ) {
  6142. mpars.depthWrite = m.depthWrite;
  6143. }
  6144. if ( m.visible !== undefined ) {
  6145. mpars.visible = m.visible;
  6146. }
  6147. if ( m.flipSided !== undefined ) {
  6148. mpars.side = THREE.BackSide;
  6149. }
  6150. if ( m.doubleSided !== undefined ) {
  6151. mpars.side = THREE.DoubleSide;
  6152. }
  6153. if ( m.wireframe !== undefined ) {
  6154. mpars.wireframe = m.wireframe;
  6155. }
  6156. if ( m.vertexColors !== undefined ) {
  6157. if ( m.vertexColors === "face" ) {
  6158. mpars.vertexColors = THREE.FaceColors;
  6159. } else if ( m.vertexColors ) {
  6160. mpars.vertexColors = THREE.VertexColors;
  6161. }
  6162. }
  6163. // colors
  6164. if ( m.colorDiffuse ) {
  6165. mpars.color = rgb2hex( m.colorDiffuse );
  6166. } else if ( m.DbgColor ) {
  6167. mpars.color = m.DbgColor;
  6168. }
  6169. if ( m.colorSpecular ) {
  6170. mpars.specular = rgb2hex( m.colorSpecular );
  6171. }
  6172. if ( m.colorAmbient ) {
  6173. mpars.ambient = rgb2hex( m.colorAmbient );
  6174. }
  6175. // modifiers
  6176. if ( m.transparency ) {
  6177. mpars.opacity = m.transparency;
  6178. }
  6179. if ( m.specularCoef ) {
  6180. mpars.shininess = m.specularCoef;
  6181. }
  6182. // textures
  6183. if ( m.mapDiffuse && texturePath ) {
  6184. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  6185. }
  6186. if ( m.mapLight && texturePath ) {
  6187. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  6188. }
  6189. if ( m.mapBump && texturePath ) {
  6190. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  6191. }
  6192. if ( m.mapNormal && texturePath ) {
  6193. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  6194. }
  6195. if ( m.mapSpecular && texturePath ) {
  6196. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  6197. }
  6198. //
  6199. if ( m.mapBumpScale ) {
  6200. mpars.bumpScale = m.mapBumpScale;
  6201. }
  6202. // special case for normal mapped material
  6203. if ( m.mapNormal ) {
  6204. var shader = THREE.ShaderLib[ "normalmap" ];
  6205. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6206. uniforms[ "tNormal" ].value = mpars.normalMap;
  6207. if ( m.mapNormalFactor ) {
  6208. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  6209. }
  6210. if ( mpars.map ) {
  6211. uniforms[ "tDiffuse" ].value = mpars.map;
  6212. uniforms[ "enableDiffuse" ].value = true;
  6213. }
  6214. if ( mpars.specularMap ) {
  6215. uniforms[ "tSpecular" ].value = mpars.specularMap;
  6216. uniforms[ "enableSpecular" ].value = true;
  6217. }
  6218. if ( mpars.lightMap ) {
  6219. uniforms[ "tAO" ].value = mpars.lightMap;
  6220. uniforms[ "enableAO" ].value = true;
  6221. }
  6222. // for the moment don't handle displacement texture
  6223. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  6224. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  6225. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  6226. uniforms[ "uShininess" ].value = mpars.shininess;
  6227. if ( mpars.opacity !== undefined ) {
  6228. uniforms[ "uOpacity" ].value = mpars.opacity;
  6229. }
  6230. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6231. var material = new THREE.ShaderMaterial( parameters );
  6232. if ( mpars.transparent ) {
  6233. material.transparent = true;
  6234. }
  6235. } else {
  6236. var material = new THREE[ mtype ]( mpars );
  6237. }
  6238. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6239. return material;
  6240. }
  6241. };
  6242. /**
  6243. * @author mrdoob / http://mrdoob.com/
  6244. */
  6245. THREE.XHRLoader = function ( manager ) {
  6246. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6247. };
  6248. THREE.XHRLoader.prototype = {
  6249. constructor: THREE.XHRLoader,
  6250. load: function ( url, onLoad, onProgress, onError ) {
  6251. var scope = this;
  6252. var request = new XMLHttpRequest();
  6253. if ( onLoad !== undefined ) {
  6254. request.addEventListener( 'load', function ( event ) {
  6255. onLoad( event.target.responseText );
  6256. scope.manager.itemEnd( url );
  6257. }, false );
  6258. }
  6259. if ( onProgress !== undefined ) {
  6260. request.addEventListener( 'progress', function ( event ) {
  6261. onProgress( event );
  6262. }, false );
  6263. }
  6264. if ( onError !== undefined ) {
  6265. request.addEventListener( 'error', function ( event ) {
  6266. onError( event );
  6267. }, false );
  6268. }
  6269. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6270. request.open( 'GET', url, true );
  6271. request.send( null );
  6272. scope.manager.itemStart( url );
  6273. },
  6274. setCrossOrigin: function ( value ) {
  6275. this.crossOrigin = value;
  6276. }
  6277. };
  6278. /**
  6279. * @author mrdoob / http://mrdoob.com/
  6280. */
  6281. THREE.ImageLoader = function ( manager ) {
  6282. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6283. };
  6284. THREE.ImageLoader.prototype = {
  6285. constructor: THREE.ImageLoader,
  6286. load: function ( url, onLoad, onProgress, onError ) {
  6287. var scope = this;
  6288. var image = document.createElement( 'img' );
  6289. if ( onLoad !== undefined ) {
  6290. image.addEventListener( 'load', function ( event ) {
  6291. scope.manager.itemEnd( url );
  6292. onLoad( this );
  6293. }, false );
  6294. }
  6295. if ( onProgress !== undefined ) {
  6296. image.addEventListener( 'progress', function ( event ) {
  6297. onProgress( event );
  6298. }, false );
  6299. }
  6300. if ( onError !== undefined ) {
  6301. image.addEventListener( 'error', function ( event ) {
  6302. onError( event );
  6303. }, false );
  6304. }
  6305. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  6306. image.src = url;
  6307. scope.manager.itemStart( url );
  6308. return image;
  6309. },
  6310. setCrossOrigin: function ( value ) {
  6311. this.crossOrigin = value;
  6312. }
  6313. }
  6314. /**
  6315. * @author mrdoob / http://mrdoob.com/
  6316. * @author alteredq / http://alteredqualia.com/
  6317. */
  6318. THREE.JSONLoader = function ( showStatus ) {
  6319. THREE.Loader.call( this, showStatus );
  6320. this.withCredentials = false;
  6321. };
  6322. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  6323. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  6324. var scope = this;
  6325. // todo: unify load API to for easier SceneLoader use
  6326. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  6327. this.onLoadStart();
  6328. this.loadAjaxJSON( this, url, callback, texturePath );
  6329. };
  6330. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  6331. var xhr = new XMLHttpRequest();
  6332. var length = 0;
  6333. xhr.onreadystatechange = function () {
  6334. if ( xhr.readyState === xhr.DONE ) {
  6335. if ( xhr.status === 200 || xhr.status === 0 ) {
  6336. if ( xhr.responseText ) {
  6337. var json = JSON.parse( xhr.responseText );
  6338. var result = context.parse( json, texturePath );
  6339. callback( result.geometry, result.materials );
  6340. } else {
  6341. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  6342. }
  6343. // in context of more complex asset initialization
  6344. // do not block on single failed file
  6345. // maybe should go even one more level up
  6346. context.onLoadComplete();
  6347. } else {
  6348. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  6349. }
  6350. } else if ( xhr.readyState === xhr.LOADING ) {
  6351. if ( callbackProgress ) {
  6352. if ( length === 0 ) {
  6353. length = xhr.getResponseHeader( "Content-Length" );
  6354. }
  6355. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  6356. }
  6357. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  6358. if ( callbackProgress !== undefined ) {
  6359. length = xhr.getResponseHeader( "Content-Length" );
  6360. }
  6361. }
  6362. };
  6363. xhr.open( "GET", url, true );
  6364. xhr.withCredentials = this.withCredentials;
  6365. xhr.send( null );
  6366. };
  6367. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  6368. var scope = this,
  6369. geometry = new THREE.Geometry(),
  6370. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  6371. parseModel( scale );
  6372. parseSkin();
  6373. parseMorphing( scale );
  6374. geometry.computeCentroids();
  6375. geometry.computeFaceNormals();
  6376. geometry.computeBoundingSphere();
  6377. function parseModel( scale ) {
  6378. function isBitSet( value, position ) {
  6379. return value & ( 1 << position );
  6380. }
  6381. var i, j, fi,
  6382. offset, zLength,
  6383. colorIndex, normalIndex, uvIndex, materialIndex,
  6384. type,
  6385. isQuad,
  6386. hasMaterial,
  6387. hasFaceVertexUv,
  6388. hasFaceNormal, hasFaceVertexNormal,
  6389. hasFaceColor, hasFaceVertexColor,
  6390. vertex, face, faceA, faceB, color, hex, normal,
  6391. uvLayer, uv, u, v,
  6392. faces = json.faces,
  6393. vertices = json.vertices,
  6394. normals = json.normals,
  6395. colors = json.colors,
  6396. nUvLayers = 0;
  6397. if ( json.uvs !== undefined ) {
  6398. // disregard empty arrays
  6399. for ( i = 0; i < json.uvs.length; i++ ) {
  6400. if ( json.uvs[ i ].length ) nUvLayers ++;
  6401. }
  6402. for ( i = 0; i < nUvLayers; i++ ) {
  6403. geometry.faceVertexUvs[ i ] = [];
  6404. }
  6405. }
  6406. offset = 0;
  6407. zLength = vertices.length;
  6408. while ( offset < zLength ) {
  6409. vertex = new THREE.Vector3();
  6410. vertex.x = vertices[ offset ++ ] * scale;
  6411. vertex.y = vertices[ offset ++ ] * scale;
  6412. vertex.z = vertices[ offset ++ ] * scale;
  6413. geometry.vertices.push( vertex );
  6414. }
  6415. offset = 0;
  6416. zLength = faces.length;
  6417. while ( offset < zLength ) {
  6418. type = faces[ offset ++ ];
  6419. isQuad = isBitSet( type, 0 );
  6420. hasMaterial = isBitSet( type, 1 );
  6421. hasFaceVertexUv = isBitSet( type, 3 );
  6422. hasFaceNormal = isBitSet( type, 4 );
  6423. hasFaceVertexNormal = isBitSet( type, 5 );
  6424. hasFaceColor = isBitSet( type, 6 );
  6425. hasFaceVertexColor = isBitSet( type, 7 );
  6426. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  6427. if ( isQuad ) {
  6428. faceA = new THREE.Face3();
  6429. faceA.a = faces[ offset ];
  6430. faceA.b = faces[ offset + 1 ];
  6431. faceA.c = faces[ offset + 3 ];
  6432. faceB = new THREE.Face3();
  6433. faceB.a = faces[ offset + 1 ];
  6434. faceB.b = faces[ offset + 2 ];
  6435. faceB.c = faces[ offset + 3 ];
  6436. offset += 4;
  6437. if ( hasMaterial ) {
  6438. materialIndex = faces[ offset ++ ];
  6439. faceA.materialIndex = materialIndex;
  6440. faceB.materialIndex = materialIndex;
  6441. }
  6442. // to get face <=> uv index correspondence
  6443. fi = geometry.faces.length;
  6444. if ( hasFaceVertexUv ) {
  6445. for ( i = 0; i < nUvLayers; i++ ) {
  6446. uvLayer = json.uvs[ i ];
  6447. geometry.faceVertexUvs[ i ][ fi ] = [];
  6448. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  6449. for ( j = 0; j < 4; j ++ ) {
  6450. uvIndex = faces[ offset ++ ];
  6451. u = uvLayer[ uvIndex * 2 ];
  6452. v = uvLayer[ uvIndex * 2 + 1 ];
  6453. uv = new THREE.Vector2( u, v );
  6454. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  6455. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  6456. }
  6457. }
  6458. }
  6459. if ( hasFaceNormal ) {
  6460. normalIndex = faces[ offset ++ ] * 3;
  6461. faceA.normal.set(
  6462. normals[ normalIndex ++ ],
  6463. normals[ normalIndex ++ ],
  6464. normals[ normalIndex ]
  6465. );
  6466. faceB.normal.copy( faceA.normal );
  6467. }
  6468. if ( hasFaceVertexNormal ) {
  6469. for ( i = 0; i < 4; i++ ) {
  6470. normalIndex = faces[ offset ++ ] * 3;
  6471. normal = new THREE.Vector3(
  6472. normals[ normalIndex ++ ],
  6473. normals[ normalIndex ++ ],
  6474. normals[ normalIndex ]
  6475. );
  6476. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  6477. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  6478. }
  6479. }
  6480. if ( hasFaceColor ) {
  6481. colorIndex = faces[ offset ++ ];
  6482. hex = colors[ colorIndex ];
  6483. faceA.color.setHex( hex );
  6484. faceB.color.setHex( hex );
  6485. }
  6486. if ( hasFaceVertexColor ) {
  6487. for ( i = 0; i < 4; i++ ) {
  6488. colorIndex = faces[ offset ++ ];
  6489. hex = colors[ colorIndex ];
  6490. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  6491. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  6492. }
  6493. }
  6494. geometry.faces.push( faceA );
  6495. geometry.faces.push( faceB );
  6496. } else {
  6497. face = new THREE.Face3();
  6498. face.a = faces[ offset ++ ];
  6499. face.b = faces[ offset ++ ];
  6500. face.c = faces[ offset ++ ];
  6501. if ( hasMaterial ) {
  6502. materialIndex = faces[ offset ++ ];
  6503. face.materialIndex = materialIndex;
  6504. }
  6505. // to get face <=> uv index correspondence
  6506. fi = geometry.faces.length;
  6507. if ( hasFaceVertexUv ) {
  6508. for ( i = 0; i < nUvLayers; i++ ) {
  6509. uvLayer = json.uvs[ i ];
  6510. geometry.faceVertexUvs[ i ][ fi ] = [];
  6511. for ( j = 0; j < 3; j ++ ) {
  6512. uvIndex = faces[ offset ++ ];
  6513. u = uvLayer[ uvIndex * 2 ];
  6514. v = uvLayer[ uvIndex * 2 + 1 ];
  6515. uv = new THREE.Vector2( u, v );
  6516. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  6517. }
  6518. }
  6519. }
  6520. if ( hasFaceNormal ) {
  6521. normalIndex = faces[ offset ++ ] * 3;
  6522. face.normal.set(
  6523. normals[ normalIndex ++ ],
  6524. normals[ normalIndex ++ ],
  6525. normals[ normalIndex ]
  6526. );
  6527. }
  6528. if ( hasFaceVertexNormal ) {
  6529. for ( i = 0; i < 3; i++ ) {
  6530. normalIndex = faces[ offset ++ ] * 3;
  6531. normal = new THREE.Vector3(
  6532. normals[ normalIndex ++ ],
  6533. normals[ normalIndex ++ ],
  6534. normals[ normalIndex ]
  6535. );
  6536. face.vertexNormals.push( normal );
  6537. }
  6538. }
  6539. if ( hasFaceColor ) {
  6540. colorIndex = faces[ offset ++ ];
  6541. face.color.setHex( colors[ colorIndex ] );
  6542. }
  6543. if ( hasFaceVertexColor ) {
  6544. for ( i = 0; i < 3; i++ ) {
  6545. colorIndex = faces[ offset ++ ];
  6546. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  6547. }
  6548. }
  6549. geometry.faces.push( face );
  6550. }
  6551. }
  6552. };
  6553. function parseSkin() {
  6554. var i, l, x, y, z, w, a, b, c, d;
  6555. if ( json.skinWeights ) {
  6556. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  6557. x = json.skinWeights[ i ];
  6558. y = json.skinWeights[ i + 1 ];
  6559. z = 0;
  6560. w = 0;
  6561. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  6562. }
  6563. }
  6564. if ( json.skinIndices ) {
  6565. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  6566. a = json.skinIndices[ i ];
  6567. b = json.skinIndices[ i + 1 ];
  6568. c = 0;
  6569. d = 0;
  6570. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  6571. }
  6572. }
  6573. geometry.bones = json.bones;
  6574. // could change this to json.animations[0] or remove completely
  6575. geometry.animation = json.animation;
  6576. geometry.animations = json.animations;
  6577. };
  6578. function parseMorphing( scale ) {
  6579. if ( json.morphTargets !== undefined ) {
  6580. var i, l, v, vl, dstVertices, srcVertices;
  6581. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  6582. geometry.morphTargets[ i ] = {};
  6583. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  6584. geometry.morphTargets[ i ].vertices = [];
  6585. dstVertices = geometry.morphTargets[ i ].vertices;
  6586. srcVertices = json.morphTargets [ i ].vertices;
  6587. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  6588. var vertex = new THREE.Vector3();
  6589. vertex.x = srcVertices[ v ] * scale;
  6590. vertex.y = srcVertices[ v + 1 ] * scale;
  6591. vertex.z = srcVertices[ v + 2 ] * scale;
  6592. dstVertices.push( vertex );
  6593. }
  6594. }
  6595. }
  6596. if ( json.morphColors !== undefined ) {
  6597. var i, l, c, cl, dstColors, srcColors, color;
  6598. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  6599. geometry.morphColors[ i ] = {};
  6600. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  6601. geometry.morphColors[ i ].colors = [];
  6602. dstColors = geometry.morphColors[ i ].colors;
  6603. srcColors = json.morphColors [ i ].colors;
  6604. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  6605. color = new THREE.Color( 0xffaa00 );
  6606. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  6607. dstColors.push( color );
  6608. }
  6609. }
  6610. }
  6611. };
  6612. if ( json.materials === undefined ) {
  6613. return { geometry: geometry };
  6614. } else {
  6615. var materials = this.initMaterials( json.materials, texturePath );
  6616. if ( this.needsTangents( materials ) ) {
  6617. geometry.computeTangents();
  6618. }
  6619. return { geometry: geometry, materials: materials };
  6620. }
  6621. };
  6622. /**
  6623. * @author mrdoob / http://mrdoob.com/
  6624. */
  6625. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  6626. var scope = this;
  6627. var loaded = 0, total = 0;
  6628. this.onLoad = onLoad;
  6629. this.onProgress = onProgress;
  6630. this.onError = onError;
  6631. this.itemStart = function ( url ) {
  6632. total ++;
  6633. };
  6634. this.itemEnd = function ( url ) {
  6635. loaded ++;
  6636. if ( scope.onProgress !== undefined ) {
  6637. scope.onProgress( url, loaded, total );
  6638. }
  6639. if ( loaded === total && scope.onLoad !== undefined ) {
  6640. scope.onLoad();
  6641. }
  6642. };
  6643. };
  6644. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  6645. /**
  6646. * @author mrdoob / http://mrdoob.com/
  6647. */
  6648. THREE.BufferGeometryLoader = function ( manager ) {
  6649. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6650. };
  6651. THREE.BufferGeometryLoader.prototype = {
  6652. constructor: THREE.BufferGeometryLoader,
  6653. load: function ( url, onLoad, onProgress, onError ) {
  6654. var scope = this;
  6655. var loader = new THREE.XHRLoader();
  6656. loader.setCrossOrigin( this.crossOrigin );
  6657. loader.load( url, function ( text ) {
  6658. onLoad( scope.parse( JSON.parse( text ) ) );
  6659. } );
  6660. },
  6661. setCrossOrigin: function ( value ) {
  6662. this.crossOrigin = value;
  6663. },
  6664. parse: function ( json ) {
  6665. var geometry = new THREE.BufferGeometry();
  6666. var attributes = json.attributes;
  6667. var offsets = json.offsets;
  6668. var boundingSphere = json.boundingSphere;
  6669. for ( var key in attributes ) {
  6670. var attribute = attributes[ key ];
  6671. geometry.attributes[ key ] = {
  6672. itemSize: attribute.itemSize,
  6673. array: new self[ attribute.type ]( attribute.array )
  6674. }
  6675. }
  6676. if ( offsets !== undefined ) {
  6677. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  6678. }
  6679. if ( boundingSphere !== undefined ) {
  6680. geometry.boundingSphere = new THREE.Sphere(
  6681. new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
  6682. boundingSphere.radius
  6683. );
  6684. }
  6685. return geometry;
  6686. }
  6687. };
  6688. /**
  6689. * @author mrdoob / http://mrdoob.com/
  6690. */
  6691. THREE.GeometryLoader = function ( manager ) {
  6692. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6693. };
  6694. THREE.GeometryLoader.prototype = {
  6695. constructor: THREE.GeometryLoader,
  6696. load: function ( url, onLoad, onProgress, onError ) {
  6697. var scope = this;
  6698. var loader = new THREE.XHRLoader();
  6699. loader.setCrossOrigin( this.crossOrigin );
  6700. loader.load( url, function ( text ) {
  6701. onLoad( scope.parse( JSON.parse( text ) ) );
  6702. } );
  6703. },
  6704. setCrossOrigin: function ( value ) {
  6705. this.crossOrigin = value;
  6706. },
  6707. parse: function ( json ) {
  6708. }
  6709. };
  6710. /**
  6711. * @author mrdoob / http://mrdoob.com/
  6712. */
  6713. THREE.MaterialLoader = function ( manager ) {
  6714. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6715. };
  6716. THREE.MaterialLoader.prototype = {
  6717. constructor: THREE.MaterialLoader,
  6718. load: function ( url, onLoad, onProgress, onError ) {
  6719. var scope = this;
  6720. var loader = new THREE.XHRLoader();
  6721. loader.setCrossOrigin( this.crossOrigin );
  6722. loader.load( url, function ( text ) {
  6723. onLoad( scope.parse( JSON.parse( text ) ) );
  6724. } );
  6725. },
  6726. setCrossOrigin: function ( value ) {
  6727. this.crossOrigin = value;
  6728. },
  6729. parse: function ( json ) {
  6730. var material = new THREE[ json.type ];
  6731. if ( json.color !== undefined ) material.color.setHex( json.color );
  6732. if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient );
  6733. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  6734. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  6735. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  6736. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  6737. if ( json.blending !== undefined ) material.blending = json.blending;
  6738. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  6739. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  6740. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  6741. if ( json.materials !== undefined ) {
  6742. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  6743. material.materials.push( this.parse( json.materials[ i ] ) );
  6744. }
  6745. }
  6746. return material;
  6747. }
  6748. };
  6749. /**
  6750. * @author mrdoob / http://mrdoob.com/
  6751. */
  6752. THREE.ObjectLoader = function ( manager ) {
  6753. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6754. };
  6755. THREE.ObjectLoader.prototype = {
  6756. constructor: THREE.ObjectLoader,
  6757. load: function ( url, onLoad, onProgress, onError ) {
  6758. var scope = this;
  6759. var loader = new THREE.XHRLoader( scope.manager );
  6760. loader.setCrossOrigin( this.crossOrigin );
  6761. loader.load( url, function ( text ) {
  6762. onLoad( scope.parse( JSON.parse( text ) ) );
  6763. } );
  6764. },
  6765. setCrossOrigin: function ( value ) {
  6766. this.crossOrigin = value;
  6767. },
  6768. parse: function ( json ) {
  6769. var geometries = this.parseGeometries( json.geometries );
  6770. var materials = this.parseMaterials( json.materials );
  6771. var object = this.parseObject( json.object, geometries, materials );
  6772. return object;
  6773. },
  6774. parseGeometries: function ( json ) {
  6775. var geometries = {};
  6776. if ( json !== undefined ) {
  6777. var geometryLoader = new THREE.JSONLoader();
  6778. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  6779. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6780. var geometry;
  6781. var data = json[ i ];
  6782. switch ( data.type ) {
  6783. case 'PlaneGeometry':
  6784. geometry = new THREE.PlaneGeometry(
  6785. data.width,
  6786. data.height,
  6787. data.widthSegments,
  6788. data.heightSegments
  6789. );
  6790. break;
  6791. case 'CircleGeometry':
  6792. geometry = new THREE.CircleGeometry(
  6793. data.radius,
  6794. data.segments
  6795. );
  6796. break;
  6797. case 'CubeGeometry':
  6798. geometry = new THREE.CubeGeometry(
  6799. data.width,
  6800. data.height,
  6801. data.depth,
  6802. data.widthSegments,
  6803. data.heightSegments,
  6804. data.depthSegments
  6805. );
  6806. break;
  6807. case 'CylinderGeometry':
  6808. geometry = new THREE.CylinderGeometry(
  6809. data.radiusTop,
  6810. data.radiusBottom,
  6811. data.height,
  6812. data.radiusSegments,
  6813. data.heightSegments,
  6814. data.openEnded
  6815. );
  6816. break;
  6817. case 'SphereGeometry':
  6818. geometry = new THREE.SphereGeometry(
  6819. data.radius,
  6820. data.widthSegments,
  6821. data.heightSegments,
  6822. data.phiStart,
  6823. data.phiLength,
  6824. data.thetaStart,
  6825. data.thetaLength
  6826. );
  6827. break;
  6828. case 'IcosahedronGeometry':
  6829. geometry = new THREE.IcosahedronGeometry(
  6830. data.radius,
  6831. data.detail
  6832. );
  6833. break;
  6834. case 'TorusGeometry':
  6835. geometry = new THREE.TorusGeometry(
  6836. data.radius,
  6837. data.tube,
  6838. data.radialSegments,
  6839. data.tubularSegments,
  6840. data.arc
  6841. );
  6842. break;
  6843. case 'TorusKnotGeometry':
  6844. geometry = new THREE.TorusKnotGeometry(
  6845. data.radius,
  6846. data.tube,
  6847. data.radialSegments,
  6848. data.tubularSegments,
  6849. data.p,
  6850. data.q,
  6851. data.heightScale
  6852. );
  6853. break;
  6854. case 'BufferGeometry':
  6855. geometry = bufferGeometryLoader.parse( data.data );
  6856. break;
  6857. case 'Geometry':
  6858. geometry = geometryLoader.parse( data.data ).geometry;
  6859. break;
  6860. }
  6861. geometry.uuid = data.uuid;
  6862. if ( data.name !== undefined ) geometry.name = data.name;
  6863. geometries[ data.uuid ] = geometry;
  6864. }
  6865. }
  6866. return geometries;
  6867. },
  6868. parseMaterials: function ( json ) {
  6869. var materials = {};
  6870. if ( json !== undefined ) {
  6871. var loader = new THREE.MaterialLoader();
  6872. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6873. var data = json[ i ];
  6874. var material = loader.parse( data );
  6875. material.uuid = data.uuid;
  6876. if ( data.name !== undefined ) material.name = data.name;
  6877. materials[ data.uuid ] = material;
  6878. }
  6879. }
  6880. return materials;
  6881. },
  6882. parseObject: function () {
  6883. var matrix = new THREE.Matrix4();
  6884. return function ( data, geometries, materials ) {
  6885. var object;
  6886. switch ( data.type ) {
  6887. case 'Scene':
  6888. object = new THREE.Scene();
  6889. break;
  6890. case 'PerspectiveCamera':
  6891. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  6892. break;
  6893. case 'OrthographicCamera':
  6894. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  6895. break;
  6896. case 'AmbientLight':
  6897. object = new THREE.AmbientLight( data.color );
  6898. break;
  6899. case 'DirectionalLight':
  6900. object = new THREE.DirectionalLight( data.color, data.intensity );
  6901. break;
  6902. case 'PointLight':
  6903. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  6904. break;
  6905. case 'SpotLight':
  6906. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  6907. break;
  6908. case 'HemisphereLight':
  6909. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  6910. break;
  6911. case 'Mesh':
  6912. var geometry = geometries[ data.geometry ];
  6913. var material = materials[ data.material ];
  6914. if ( geometry === undefined ) {
  6915. console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry );
  6916. }
  6917. if ( material === undefined ) {
  6918. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  6919. }
  6920. object = new THREE.Mesh( geometry, material );
  6921. break;
  6922. default:
  6923. object = new THREE.Object3D();
  6924. }
  6925. object.uuid = data.uuid;
  6926. if ( data.name !== undefined ) object.name = data.name;
  6927. if ( data.matrix !== undefined ) {
  6928. matrix.fromArray( data.matrix );
  6929. matrix.decompose( object.position, object.quaternion, object.scale );
  6930. } else {
  6931. if ( data.position !== undefined ) object.position.fromArray( data.position );
  6932. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  6933. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  6934. }
  6935. if ( data.visible !== undefined ) object.visible = data.visible;
  6936. if ( data.userData !== undefined ) object.userData = data.userData;
  6937. if ( data.children !== undefined ) {
  6938. for ( var child in data.children ) {
  6939. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  6940. }
  6941. }
  6942. return object;
  6943. }
  6944. }()
  6945. };
  6946. /**
  6947. * @author alteredq / http://alteredqualia.com/
  6948. */
  6949. THREE.SceneLoader = function () {
  6950. this.onLoadStart = function () {};
  6951. this.onLoadProgress = function() {};
  6952. this.onLoadComplete = function () {};
  6953. this.callbackSync = function () {};
  6954. this.callbackProgress = function () {};
  6955. this.geometryHandlers = {};
  6956. this.hierarchyHandlers = {};
  6957. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  6958. };
  6959. THREE.SceneLoader.prototype = {
  6960. constructor: THREE.SceneLoader,
  6961. load: function ( url, onLoad, onProgress, onError ) {
  6962. var scope = this;
  6963. var loader = new THREE.XHRLoader( scope.manager );
  6964. loader.setCrossOrigin( this.crossOrigin );
  6965. loader.load( url, function ( text ) {
  6966. scope.parse( JSON.parse( text ), onLoad, url );
  6967. } );
  6968. },
  6969. setCrossOrigin: function ( value ) {
  6970. this.crossOrigin = value;
  6971. },
  6972. addGeometryHandler: function ( typeID, loaderClass ) {
  6973. this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass };
  6974. },
  6975. addHierarchyHandler: function ( typeID, loaderClass ) {
  6976. this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass };
  6977. },
  6978. parse: function ( json, callbackFinished, url ) {
  6979. var scope = this;
  6980. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  6981. var geometry, material, camera, fog,
  6982. texture, images, color,
  6983. light, hex, intensity,
  6984. counter_models, counter_textures,
  6985. total_models, total_textures,
  6986. result;
  6987. var target_array = [];
  6988. var data = json;
  6989. // async geometry loaders
  6990. for ( var typeID in this.geometryHandlers ) {
  6991. var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ];
  6992. this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  6993. }
  6994. // async hierachy loaders
  6995. for ( var typeID in this.hierarchyHandlers ) {
  6996. var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ];
  6997. this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  6998. }
  6999. counter_models = 0;
  7000. counter_textures = 0;
  7001. result = {
  7002. scene: new THREE.Scene(),
  7003. geometries: {},
  7004. face_materials: {},
  7005. materials: {},
  7006. textures: {},
  7007. objects: {},
  7008. cameras: {},
  7009. lights: {},
  7010. fogs: {},
  7011. empties: {},
  7012. groups: {}
  7013. };
  7014. if ( data.transform ) {
  7015. var position = data.transform.position,
  7016. rotation = data.transform.rotation,
  7017. scale = data.transform.scale;
  7018. if ( position ) {
  7019. result.scene.position.fromArray( position );
  7020. }
  7021. if ( rotation ) {
  7022. result.scene.rotation.fromArray( rotation );
  7023. }
  7024. if ( scale ) {
  7025. result.scene.scale.fromArray( scale );
  7026. }
  7027. if ( position || rotation || scale ) {
  7028. result.scene.updateMatrix();
  7029. result.scene.updateMatrixWorld();
  7030. }
  7031. }
  7032. function get_url( source_url, url_type ) {
  7033. if ( url_type == "relativeToHTML" ) {
  7034. return source_url;
  7035. } else {
  7036. return urlBase + "/" + source_url;
  7037. }
  7038. };
  7039. // toplevel loader function, delegates to handle_children
  7040. function handle_objects() {
  7041. handle_children( result.scene, data.objects );
  7042. }
  7043. // handle all the children from the loaded json and attach them to given parent
  7044. function handle_children( parent, children ) {
  7045. var mat, dst, pos, rot, scl, quat;
  7046. for ( var objID in children ) {
  7047. // check by id if child has already been handled,
  7048. // if not, create new object
  7049. var object = result.objects[ objID ];
  7050. var objJSON = children[ objID ];
  7051. if ( object === undefined ) {
  7052. // meshes
  7053. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7054. if ( objJSON.loading === undefined ) {
  7055. var reservedTypes = {
  7056. "type": 1, "url": 1, "material": 1,
  7057. "position": 1, "rotation": 1, "scale" : 1,
  7058. "visible": 1, "children": 1, "userData": 1,
  7059. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
  7060. };
  7061. var loaderParameters = {};
  7062. for ( var parType in objJSON ) {
  7063. if ( ! ( parType in reservedTypes ) ) {
  7064. loaderParameters[ parType ] = objJSON[ parType ];
  7065. }
  7066. }
  7067. material = result.materials[ objJSON.material ];
  7068. objJSON.loading = true;
  7069. var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
  7070. // ColladaLoader
  7071. if ( loader.options ) {
  7072. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  7073. // UTF8Loader
  7074. // OBJLoader
  7075. } else {
  7076. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  7077. }
  7078. }
  7079. } else if ( objJSON.geometry !== undefined ) {
  7080. geometry = result.geometries[ objJSON.geometry ];
  7081. // geometry already loaded
  7082. if ( geometry ) {
  7083. var needsTangents = false;
  7084. material = result.materials[ objJSON.material ];
  7085. needsTangents = material instanceof THREE.ShaderMaterial;
  7086. pos = objJSON.position;
  7087. rot = objJSON.rotation;
  7088. scl = objJSON.scale;
  7089. mat = objJSON.matrix;
  7090. quat = objJSON.quaternion;
  7091. // use materials from the model file
  7092. // if there is no material specified in the object
  7093. if ( ! objJSON.material ) {
  7094. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7095. }
  7096. // use materials from the model file
  7097. // if there is just empty face material
  7098. // (must create new material as each model has its own face material)
  7099. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  7100. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7101. }
  7102. if ( material instanceof THREE.MeshFaceMaterial ) {
  7103. for ( var i = 0; i < material.materials.length; i ++ ) {
  7104. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  7105. }
  7106. }
  7107. if ( needsTangents ) {
  7108. geometry.computeTangents();
  7109. }
  7110. if ( objJSON.skin ) {
  7111. object = new THREE.SkinnedMesh( geometry, material );
  7112. } else if ( objJSON.morph ) {
  7113. object = new THREE.MorphAnimMesh( geometry, material );
  7114. if ( objJSON.duration !== undefined ) {
  7115. object.duration = objJSON.duration;
  7116. }
  7117. if ( objJSON.time !== undefined ) {
  7118. object.time = objJSON.time;
  7119. }
  7120. if ( objJSON.mirroredLoop !== undefined ) {
  7121. object.mirroredLoop = objJSON.mirroredLoop;
  7122. }
  7123. if ( material.morphNormals ) {
  7124. geometry.computeMorphNormals();
  7125. }
  7126. } else {
  7127. object = new THREE.Mesh( geometry, material );
  7128. }
  7129. object.name = objID;
  7130. if ( mat ) {
  7131. object.matrixAutoUpdate = false;
  7132. object.matrix.set(
  7133. mat[0], mat[1], mat[2], mat[3],
  7134. mat[4], mat[5], mat[6], mat[7],
  7135. mat[8], mat[9], mat[10], mat[11],
  7136. mat[12], mat[13], mat[14], mat[15]
  7137. );
  7138. } else {
  7139. object.position.fromArray( pos );
  7140. if ( quat ) {
  7141. object.quaternion.fromArray( quat );
  7142. } else {
  7143. object.rotation.fromArray( rot );
  7144. }
  7145. object.scale.fromArray( scl );
  7146. }
  7147. object.visible = objJSON.visible;
  7148. object.castShadow = objJSON.castShadow;
  7149. object.receiveShadow = objJSON.receiveShadow;
  7150. parent.add( object );
  7151. result.objects[ objID ] = object;
  7152. }
  7153. // lights
  7154. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  7155. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  7156. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  7157. if ( objJSON.type === "DirectionalLight" ) {
  7158. pos = objJSON.direction;
  7159. light = new THREE.DirectionalLight( hex, intensity );
  7160. light.position.fromArray( pos );
  7161. if ( objJSON.target ) {
  7162. target_array.push( { "object": light, "targetName" : objJSON.target } );
  7163. // kill existing default target
  7164. // otherwise it gets added to scene when parent gets added
  7165. light.target = null;
  7166. }
  7167. } else if ( objJSON.type === "PointLight" ) {
  7168. pos = objJSON.position;
  7169. dst = objJSON.distance;
  7170. light = new THREE.PointLight( hex, intensity, dst );
  7171. light.position.fromArray( pos );
  7172. } else if ( objJSON.type === "AmbientLight" ) {
  7173. light = new THREE.AmbientLight( hex );
  7174. }
  7175. parent.add( light );
  7176. light.name = objID;
  7177. result.lights[ objID ] = light;
  7178. result.objects[ objID ] = light;
  7179. // cameras
  7180. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  7181. pos = objJSON.position;
  7182. rot = objJSON.rotation;
  7183. quat = objJSON.quaternion;
  7184. if ( objJSON.type === "PerspectiveCamera" ) {
  7185. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  7186. } else if ( objJSON.type === "OrthographicCamera" ) {
  7187. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  7188. }
  7189. camera.name = objID;
  7190. camera.position.fromArray( pos );
  7191. if ( quat !== undefined ) {
  7192. camera.quaternion.fromArray( quat );
  7193. } else if ( rot !== undefined ) {
  7194. camera.rotation.fromArray( rot );
  7195. }
  7196. parent.add( camera );
  7197. result.cameras[ objID ] = camera;
  7198. result.objects[ objID ] = camera;
  7199. // pure Object3D
  7200. } else {
  7201. pos = objJSON.position;
  7202. rot = objJSON.rotation;
  7203. scl = objJSON.scale;
  7204. quat = objJSON.quaternion;
  7205. object = new THREE.Object3D();
  7206. object.name = objID;
  7207. object.position.fromArray( pos );
  7208. if ( quat ) {
  7209. object.quaternion.fromArray( quat );
  7210. } else {
  7211. object.rotation.fromArray( rot );
  7212. }
  7213. object.scale.fromArray( scl );
  7214. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  7215. parent.add( object );
  7216. result.objects[ objID ] = object;
  7217. result.empties[ objID ] = object;
  7218. }
  7219. if ( object ) {
  7220. if ( objJSON.userData !== undefined ) {
  7221. for ( var key in objJSON.userData ) {
  7222. var value = objJSON.userData[ key ];
  7223. object.userData[ key ] = value;
  7224. }
  7225. }
  7226. if ( objJSON.groups !== undefined ) {
  7227. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  7228. var groupID = objJSON.groups[ i ];
  7229. if ( result.groups[ groupID ] === undefined ) {
  7230. result.groups[ groupID ] = [];
  7231. }
  7232. result.groups[ groupID ].push( objID );
  7233. }
  7234. }
  7235. }
  7236. }
  7237. if ( object !== undefined && objJSON.children !== undefined ) {
  7238. handle_children( object, objJSON.children );
  7239. }
  7240. }
  7241. };
  7242. function handle_mesh( geo, mat, id ) {
  7243. result.geometries[ id ] = geo;
  7244. result.face_materials[ id ] = mat;
  7245. handle_objects();
  7246. };
  7247. function handle_hierarchy( node, id, parent, material, obj ) {
  7248. var p = obj.position;
  7249. var r = obj.rotation;
  7250. var q = obj.quaternion;
  7251. var s = obj.scale;
  7252. node.position.fromArray( p );
  7253. if ( q ) {
  7254. node.quaternion.fromArray( q );
  7255. } else {
  7256. node.rotation.fromArray( r );
  7257. }
  7258. node.scale.fromArray( s );
  7259. // override children materials
  7260. // if object material was specified in JSON explicitly
  7261. if ( material ) {
  7262. node.traverse( function ( child ) {
  7263. child.material = material;
  7264. } );
  7265. }
  7266. // override children visibility
  7267. // with root node visibility as specified in JSON
  7268. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  7269. node.traverse( function ( child ) {
  7270. child.visible = visible;
  7271. } );
  7272. parent.add( node );
  7273. node.name = id;
  7274. result.objects[ id ] = node;
  7275. handle_objects();
  7276. };
  7277. function create_callback_geometry( id ) {
  7278. return function ( geo, mat ) {
  7279. geo.name = id;
  7280. handle_mesh( geo, mat, id );
  7281. counter_models -= 1;
  7282. scope.onLoadComplete();
  7283. async_callback_gate();
  7284. }
  7285. };
  7286. function create_callback_hierachy( id, parent, material, obj ) {
  7287. return function ( event ) {
  7288. var result;
  7289. // loaders which use EventDispatcher
  7290. if ( event.content ) {
  7291. result = event.content;
  7292. // ColladaLoader
  7293. } else if ( event.dae ) {
  7294. result = event.scene;
  7295. // UTF8Loader
  7296. } else {
  7297. result = event;
  7298. }
  7299. handle_hierarchy( result, id, parent, material, obj );
  7300. counter_models -= 1;
  7301. scope.onLoadComplete();
  7302. async_callback_gate();
  7303. }
  7304. };
  7305. function create_callback_embed( id ) {
  7306. return function ( geo, mat ) {
  7307. geo.name = id;
  7308. result.geometries[ id ] = geo;
  7309. result.face_materials[ id ] = mat;
  7310. }
  7311. };
  7312. function async_callback_gate() {
  7313. var progress = {
  7314. totalModels : total_models,
  7315. totalTextures : total_textures,
  7316. loadedModels : total_models - counter_models,
  7317. loadedTextures : total_textures - counter_textures
  7318. };
  7319. scope.callbackProgress( progress, result );
  7320. scope.onLoadProgress();
  7321. if ( counter_models === 0 && counter_textures === 0 ) {
  7322. finalize();
  7323. callbackFinished( result );
  7324. }
  7325. };
  7326. function finalize() {
  7327. // take care of targets which could be asynchronously loaded objects
  7328. for ( var i = 0; i < target_array.length; i ++ ) {
  7329. var ta = target_array[ i ];
  7330. var target = result.objects[ ta.targetName ];
  7331. if ( target ) {
  7332. ta.object.target = target;
  7333. } else {
  7334. // if there was error and target of specified name doesn't exist in the scene file
  7335. // create instead dummy target
  7336. // (target must be added to scene explicitly as parent is already added)
  7337. ta.object.target = new THREE.Object3D();
  7338. result.scene.add( ta.object.target );
  7339. }
  7340. ta.object.target.userData.targetInverse = ta.object;
  7341. }
  7342. };
  7343. var callbackTexture = function ( count ) {
  7344. counter_textures -= count;
  7345. async_callback_gate();
  7346. scope.onLoadComplete();
  7347. };
  7348. // must use this instead of just directly calling callbackTexture
  7349. // because of closure in the calling context loop
  7350. var generateTextureCallback = function ( count ) {
  7351. return function () {
  7352. callbackTexture( count );
  7353. };
  7354. };
  7355. function traverse_json_hierarchy( objJSON, callback ) {
  7356. callback( objJSON );
  7357. if ( objJSON.children !== undefined ) {
  7358. for ( var objChildID in objJSON.children ) {
  7359. traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
  7360. }
  7361. }
  7362. };
  7363. // first go synchronous elements
  7364. // fogs
  7365. var fogID, fogJSON;
  7366. for ( fogID in data.fogs ) {
  7367. fogJSON = data.fogs[ fogID ];
  7368. if ( fogJSON.type === "linear" ) {
  7369. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  7370. } else if ( fogJSON.type === "exp2" ) {
  7371. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  7372. }
  7373. color = fogJSON.color;
  7374. fog.color.setRGB( color[0], color[1], color[2] );
  7375. result.fogs[ fogID ] = fog;
  7376. }
  7377. // now come potentially asynchronous elements
  7378. // geometries
  7379. // count how many geometries will be loaded asynchronously
  7380. var geoID, geoJSON;
  7381. for ( geoID in data.geometries ) {
  7382. geoJSON = data.geometries[ geoID ];
  7383. if ( geoJSON.type in this.geometryHandlers ) {
  7384. counter_models += 1;
  7385. scope.onLoadStart();
  7386. }
  7387. }
  7388. // count how many hierarchies will be loaded asynchronously
  7389. for ( var objID in data.objects ) {
  7390. traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
  7391. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7392. counter_models += 1;
  7393. scope.onLoadStart();
  7394. }
  7395. });
  7396. }
  7397. total_models = counter_models;
  7398. for ( geoID in data.geometries ) {
  7399. geoJSON = data.geometries[ geoID ];
  7400. if ( geoJSON.type === "cube" ) {
  7401. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  7402. geometry.name = geoID;
  7403. result.geometries[ geoID ] = geometry;
  7404. } else if ( geoJSON.type === "plane" ) {
  7405. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  7406. geometry.name = geoID;
  7407. result.geometries[ geoID ] = geometry;
  7408. } else if ( geoJSON.type === "sphere" ) {
  7409. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  7410. geometry.name = geoID;
  7411. result.geometries[ geoID ] = geometry;
  7412. } else if ( geoJSON.type === "cylinder" ) {
  7413. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  7414. geometry.name = geoID;
  7415. result.geometries[ geoID ] = geometry;
  7416. } else if ( geoJSON.type === "torus" ) {
  7417. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  7418. geometry.name = geoID;
  7419. result.geometries[ geoID ] = geometry;
  7420. } else if ( geoJSON.type === "icosahedron" ) {
  7421. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  7422. geometry.name = geoID;
  7423. result.geometries[ geoID ] = geometry;
  7424. } else if ( geoJSON.type in this.geometryHandlers ) {
  7425. var loaderParameters = {};
  7426. for ( var parType in geoJSON ) {
  7427. if ( parType !== "type" && parType !== "url" ) {
  7428. loaderParameters[ parType ] = geoJSON[ parType ];
  7429. }
  7430. }
  7431. var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ];
  7432. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  7433. } else if ( geoJSON.type === "embedded" ) {
  7434. var modelJson = data.embeds[ geoJSON.id ],
  7435. texture_path = "";
  7436. // pass metadata along to jsonLoader so it knows the format version
  7437. modelJson.metadata = data.metadata;
  7438. if ( modelJson ) {
  7439. var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ];
  7440. var model = jsonLoader.parse( modelJson, texture_path );
  7441. create_callback_embed( geoID )( model.geometry, model.materials );
  7442. }
  7443. }
  7444. }
  7445. // textures
  7446. // count how many textures will be loaded asynchronously
  7447. var textureID, textureJSON;
  7448. for ( textureID in data.textures ) {
  7449. textureJSON = data.textures[ textureID ];
  7450. if ( textureJSON.url instanceof Array ) {
  7451. counter_textures += textureJSON.url.length;
  7452. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  7453. scope.onLoadStart();
  7454. }
  7455. } else {
  7456. counter_textures += 1;
  7457. scope.onLoadStart();
  7458. }
  7459. }
  7460. total_textures = counter_textures;
  7461. for ( textureID in data.textures ) {
  7462. textureJSON = data.textures[ textureID ];
  7463. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  7464. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  7465. }
  7466. if ( textureJSON.url instanceof Array ) {
  7467. var count = textureJSON.url.length;
  7468. var url_array = [];
  7469. for( var i = 0; i < count; i ++ ) {
  7470. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  7471. }
  7472. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  7473. if ( isCompressed ) {
  7474. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7475. } else {
  7476. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7477. }
  7478. } else {
  7479. var isCompressed = /\.dds$/i.test( textureJSON.url );
  7480. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  7481. var textureCallback = generateTextureCallback( 1 );
  7482. if ( isCompressed ) {
  7483. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  7484. } else {
  7485. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  7486. }
  7487. if ( THREE[ textureJSON.minFilter ] !== undefined )
  7488. texture.minFilter = THREE[ textureJSON.minFilter ];
  7489. if ( THREE[ textureJSON.magFilter ] !== undefined )
  7490. texture.magFilter = THREE[ textureJSON.magFilter ];
  7491. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  7492. if ( textureJSON.repeat ) {
  7493. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  7494. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  7495. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  7496. }
  7497. if ( textureJSON.offset ) {
  7498. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  7499. }
  7500. // handle wrap after repeat so that default repeat can be overriden
  7501. if ( textureJSON.wrap ) {
  7502. var wrapMap = {
  7503. "repeat": THREE.RepeatWrapping,
  7504. "mirror": THREE.MirroredRepeatWrapping
  7505. }
  7506. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  7507. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  7508. }
  7509. }
  7510. result.textures[ textureID ] = texture;
  7511. }
  7512. // materials
  7513. var matID, matJSON;
  7514. var parID;
  7515. for ( matID in data.materials ) {
  7516. matJSON = data.materials[ matID ];
  7517. for ( parID in matJSON.parameters ) {
  7518. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  7519. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  7520. } else if ( parID === "shading" ) {
  7521. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  7522. } else if ( parID === "side" ) {
  7523. if ( matJSON.parameters[ parID ] == "double" ) {
  7524. matJSON.parameters[ parID ] = THREE.DoubleSide;
  7525. } else if ( matJSON.parameters[ parID ] == "back" ) {
  7526. matJSON.parameters[ parID ] = THREE.BackSide;
  7527. } else {
  7528. matJSON.parameters[ parID ] = THREE.FrontSide;
  7529. }
  7530. } else if ( parID === "blending" ) {
  7531. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  7532. } else if ( parID === "combine" ) {
  7533. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  7534. } else if ( parID === "vertexColors" ) {
  7535. if ( matJSON.parameters[ parID ] == "face" ) {
  7536. matJSON.parameters[ parID ] = THREE.FaceColors;
  7537. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  7538. } else if ( matJSON.parameters[ parID ] ) {
  7539. matJSON.parameters[ parID ] = THREE.VertexColors;
  7540. }
  7541. } else if ( parID === "wrapRGB" ) {
  7542. var v3 = matJSON.parameters[ parID ];
  7543. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  7544. }
  7545. }
  7546. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  7547. matJSON.parameters.transparent = true;
  7548. }
  7549. if ( matJSON.parameters.normalMap ) {
  7550. var shader = THREE.ShaderLib[ "normalmap" ];
  7551. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  7552. var diffuse = matJSON.parameters.color;
  7553. var specular = matJSON.parameters.specular;
  7554. var ambient = matJSON.parameters.ambient;
  7555. var shininess = matJSON.parameters.shininess;
  7556. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  7557. if ( matJSON.parameters.normalScale ) {
  7558. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  7559. }
  7560. if ( matJSON.parameters.map ) {
  7561. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  7562. uniforms[ "enableDiffuse" ].value = true;
  7563. }
  7564. if ( matJSON.parameters.envMap ) {
  7565. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  7566. uniforms[ "enableReflection" ].value = true;
  7567. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  7568. }
  7569. if ( matJSON.parameters.lightMap ) {
  7570. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  7571. uniforms[ "enableAO" ].value = true;
  7572. }
  7573. if ( matJSON.parameters.specularMap ) {
  7574. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  7575. uniforms[ "enableSpecular" ].value = true;
  7576. }
  7577. if ( matJSON.parameters.displacementMap ) {
  7578. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  7579. uniforms[ "enableDisplacement" ].value = true;
  7580. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  7581. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  7582. }
  7583. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  7584. uniforms[ "uSpecularColor" ].value.setHex( specular );
  7585. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  7586. uniforms[ "uShininess" ].value = shininess;
  7587. if ( matJSON.parameters.opacity ) {
  7588. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  7589. }
  7590. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  7591. material = new THREE.ShaderMaterial( parameters );
  7592. } else {
  7593. material = new THREE[ matJSON.type ]( matJSON.parameters );
  7594. }
  7595. material.name = matID;
  7596. result.materials[ matID ] = material;
  7597. }
  7598. // second pass through all materials to initialize MeshFaceMaterials
  7599. // that could be referring to other materials out of order
  7600. for ( matID in data.materials ) {
  7601. matJSON = data.materials[ matID ];
  7602. if ( matJSON.parameters.materials ) {
  7603. var materialArray = [];
  7604. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  7605. var label = matJSON.parameters.materials[ i ];
  7606. materialArray.push( result.materials[ label ] );
  7607. }
  7608. result.materials[ matID ].materials = materialArray;
  7609. }
  7610. }
  7611. // objects ( synchronous init of procedural primitives )
  7612. handle_objects();
  7613. // defaults
  7614. if ( result.cameras && data.defaults.camera ) {
  7615. result.currentCamera = result.cameras[ data.defaults.camera ];
  7616. }
  7617. if ( result.fogs && data.defaults.fog ) {
  7618. result.scene.fog = result.fogs[ data.defaults.fog ];
  7619. }
  7620. // synchronous callback
  7621. scope.callbackSync( result );
  7622. // just in case there are no async elements
  7623. async_callback_gate();
  7624. }
  7625. }
  7626. /**
  7627. * @author mrdoob / http://mrdoob.com/
  7628. */
  7629. THREE.TextureLoader = function ( manager ) {
  7630. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7631. };
  7632. THREE.TextureLoader.prototype = {
  7633. constructor: THREE.TextureLoader,
  7634. load: function ( url, onLoad, onProgress, onError ) {
  7635. var scope = this;
  7636. var loader = new THREE.ImageLoader( scope.manager );
  7637. loader.setCrossOrigin( this.crossOrigin );
  7638. loader.load( url, function ( image ) {
  7639. var texture = new THREE.Texture( image );
  7640. texture.needsUpdate = true;
  7641. if ( onLoad !== undefined ) {
  7642. onLoad( texture );
  7643. }
  7644. } );
  7645. },
  7646. setCrossOrigin: function ( value ) {
  7647. this.crossOrigin = value;
  7648. }
  7649. };
  7650. /**
  7651. * @author mrdoob / http://mrdoob.com/
  7652. * @author alteredq / http://alteredqualia.com/
  7653. */
  7654. THREE.Material = function () {
  7655. this.id = THREE.MaterialIdCount ++;
  7656. this.uuid = THREE.Math.generateUUID();
  7657. this.name = '';
  7658. this.side = THREE.FrontSide;
  7659. this.opacity = 1;
  7660. this.transparent = false;
  7661. this.blending = THREE.NormalBlending;
  7662. this.blendSrc = THREE.SrcAlphaFactor;
  7663. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  7664. this.blendEquation = THREE.AddEquation;
  7665. this.depthTest = true;
  7666. this.depthWrite = true;
  7667. this.polygonOffset = false;
  7668. this.polygonOffsetFactor = 0;
  7669. this.polygonOffsetUnits = 0;
  7670. this.alphaTest = 0;
  7671. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  7672. this.visible = true;
  7673. this.needsUpdate = true;
  7674. };
  7675. THREE.Material.prototype = {
  7676. constructor: THREE.Material,
  7677. setValues: function ( values ) {
  7678. if ( values === undefined ) return;
  7679. for ( var key in values ) {
  7680. var newValue = values[ key ];
  7681. if ( newValue === undefined ) {
  7682. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  7683. continue;
  7684. }
  7685. if ( key in this ) {
  7686. var currentValue = this[ key ];
  7687. if ( currentValue instanceof THREE.Color ) {
  7688. currentValue.set( newValue );
  7689. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  7690. currentValue.copy( newValue );
  7691. } else if ( key == 'overdraw') {
  7692. // ensure overdraw is backwards-compatable with legacy boolean type
  7693. this[ key ] = Number(newValue);
  7694. } else {
  7695. this[ key ] = newValue;
  7696. }
  7697. }
  7698. }
  7699. },
  7700. clone: function ( material ) {
  7701. if ( material === undefined ) material = new THREE.Material();
  7702. material.name = this.name;
  7703. material.side = this.side;
  7704. material.opacity = this.opacity;
  7705. material.transparent = this.transparent;
  7706. material.blending = this.blending;
  7707. material.blendSrc = this.blendSrc;
  7708. material.blendDst = this.blendDst;
  7709. material.blendEquation = this.blendEquation;
  7710. material.depthTest = this.depthTest;
  7711. material.depthWrite = this.depthWrite;
  7712. material.polygonOffset = this.polygonOffset;
  7713. material.polygonOffsetFactor = this.polygonOffsetFactor;
  7714. material.polygonOffsetUnits = this.polygonOffsetUnits;
  7715. material.alphaTest = this.alphaTest;
  7716. material.overdraw = this.overdraw;
  7717. material.visible = this.visible;
  7718. return material;
  7719. },
  7720. dispose: function () {
  7721. this.dispatchEvent( { type: 'dispose' } );
  7722. }
  7723. };
  7724. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  7725. THREE.MaterialIdCount = 0;
  7726. /**
  7727. * @author mrdoob / http://mrdoob.com/
  7728. * @author alteredq / http://alteredqualia.com/
  7729. *
  7730. * parameters = {
  7731. * color: <hex>,
  7732. * opacity: <float>,
  7733. *
  7734. * blending: THREE.NormalBlending,
  7735. * depthTest: <bool>,
  7736. * depthWrite: <bool>,
  7737. *
  7738. * linewidth: <float>,
  7739. * linecap: "round",
  7740. * linejoin: "round",
  7741. *
  7742. * vertexColors: <bool>
  7743. *
  7744. * fog: <bool>
  7745. * }
  7746. */
  7747. THREE.LineBasicMaterial = function ( parameters ) {
  7748. THREE.Material.call( this );
  7749. this.color = new THREE.Color( 0xffffff );
  7750. this.linewidth = 1;
  7751. this.linecap = 'round';
  7752. this.linejoin = 'round';
  7753. this.vertexColors = false;
  7754. this.fog = true;
  7755. this.setValues( parameters );
  7756. };
  7757. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7758. THREE.LineBasicMaterial.prototype.clone = function () {
  7759. var material = new THREE.LineBasicMaterial();
  7760. THREE.Material.prototype.clone.call( this, material );
  7761. material.color.copy( this.color );
  7762. material.linewidth = this.linewidth;
  7763. material.linecap = this.linecap;
  7764. material.linejoin = this.linejoin;
  7765. material.vertexColors = this.vertexColors;
  7766. material.fog = this.fog;
  7767. return material;
  7768. };
  7769. /**
  7770. * @author alteredq / http://alteredqualia.com/
  7771. *
  7772. * parameters = {
  7773. * color: <hex>,
  7774. * opacity: <float>,
  7775. *
  7776. * blending: THREE.NormalBlending,
  7777. * depthTest: <bool>,
  7778. * depthWrite: <bool>,
  7779. *
  7780. * linewidth: <float>,
  7781. *
  7782. * scale: <float>,
  7783. * dashSize: <float>,
  7784. * gapSize: <float>,
  7785. *
  7786. * vertexColors: <bool>
  7787. *
  7788. * fog: <bool>
  7789. * }
  7790. */
  7791. THREE.LineDashedMaterial = function ( parameters ) {
  7792. THREE.Material.call( this );
  7793. this.color = new THREE.Color( 0xffffff );
  7794. this.linewidth = 1;
  7795. this.scale = 1;
  7796. this.dashSize = 3;
  7797. this.gapSize = 1;
  7798. this.vertexColors = false;
  7799. this.fog = true;
  7800. this.setValues( parameters );
  7801. };
  7802. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  7803. THREE.LineDashedMaterial.prototype.clone = function () {
  7804. var material = new THREE.LineDashedMaterial();
  7805. THREE.Material.prototype.clone.call( this, material );
  7806. material.color.copy( this.color );
  7807. material.linewidth = this.linewidth;
  7808. material.scale = this.scale;
  7809. material.dashSize = this.dashSize;
  7810. material.gapSize = this.gapSize;
  7811. material.vertexColors = this.vertexColors;
  7812. material.fog = this.fog;
  7813. return material;
  7814. };
  7815. /**
  7816. * @author mrdoob / http://mrdoob.com/
  7817. * @author alteredq / http://alteredqualia.com/
  7818. *
  7819. * parameters = {
  7820. * color: <hex>,
  7821. * opacity: <float>,
  7822. * map: new THREE.Texture( <Image> ),
  7823. *
  7824. * lightMap: new THREE.Texture( <Image> ),
  7825. *
  7826. * specularMap: new THREE.Texture( <Image> ),
  7827. *
  7828. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7829. * combine: THREE.Multiply,
  7830. * reflectivity: <float>,
  7831. * refractionRatio: <float>,
  7832. *
  7833. * shading: THREE.SmoothShading,
  7834. * blending: THREE.NormalBlending,
  7835. * depthTest: <bool>,
  7836. * depthWrite: <bool>,
  7837. *
  7838. * wireframe: <boolean>,
  7839. * wireframeLinewidth: <float>,
  7840. *
  7841. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7842. *
  7843. * skinning: <bool>,
  7844. * morphTargets: <bool>,
  7845. *
  7846. * fog: <bool>
  7847. * }
  7848. */
  7849. THREE.MeshBasicMaterial = function ( parameters ) {
  7850. THREE.Material.call( this );
  7851. this.color = new THREE.Color( 0xffffff ); // emissive
  7852. this.map = null;
  7853. this.lightMap = null;
  7854. this.specularMap = null;
  7855. this.envMap = null;
  7856. this.combine = THREE.MultiplyOperation;
  7857. this.reflectivity = 1;
  7858. this.refractionRatio = 0.98;
  7859. this.fog = true;
  7860. this.shading = THREE.SmoothShading;
  7861. this.wireframe = false;
  7862. this.wireframeLinewidth = 1;
  7863. this.wireframeLinecap = 'round';
  7864. this.wireframeLinejoin = 'round';
  7865. this.vertexColors = THREE.NoColors;
  7866. this.skinning = false;
  7867. this.morphTargets = false;
  7868. this.setValues( parameters );
  7869. };
  7870. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7871. THREE.MeshBasicMaterial.prototype.clone = function () {
  7872. var material = new THREE.MeshBasicMaterial();
  7873. THREE.Material.prototype.clone.call( this, material );
  7874. material.color.copy( this.color );
  7875. material.map = this.map;
  7876. material.lightMap = this.lightMap;
  7877. material.specularMap = this.specularMap;
  7878. material.envMap = this.envMap;
  7879. material.combine = this.combine;
  7880. material.reflectivity = this.reflectivity;
  7881. material.refractionRatio = this.refractionRatio;
  7882. material.fog = this.fog;
  7883. material.shading = this.shading;
  7884. material.wireframe = this.wireframe;
  7885. material.wireframeLinewidth = this.wireframeLinewidth;
  7886. material.wireframeLinecap = this.wireframeLinecap;
  7887. material.wireframeLinejoin = this.wireframeLinejoin;
  7888. material.vertexColors = this.vertexColors;
  7889. material.skinning = this.skinning;
  7890. material.morphTargets = this.morphTargets;
  7891. return material;
  7892. };
  7893. /**
  7894. * @author mrdoob / http://mrdoob.com/
  7895. * @author alteredq / http://alteredqualia.com/
  7896. *
  7897. * parameters = {
  7898. * color: <hex>,
  7899. * ambient: <hex>,
  7900. * emissive: <hex>,
  7901. * opacity: <float>,
  7902. *
  7903. * map: new THREE.Texture( <Image> ),
  7904. *
  7905. * lightMap: new THREE.Texture( <Image> ),
  7906. *
  7907. * specularMap: new THREE.Texture( <Image> ),
  7908. *
  7909. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7910. * combine: THREE.Multiply,
  7911. * reflectivity: <float>,
  7912. * refractionRatio: <float>,
  7913. *
  7914. * shading: THREE.SmoothShading,
  7915. * blending: THREE.NormalBlending,
  7916. * depthTest: <bool>,
  7917. * depthWrite: <bool>,
  7918. *
  7919. * wireframe: <boolean>,
  7920. * wireframeLinewidth: <float>,
  7921. *
  7922. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7923. *
  7924. * skinning: <bool>,
  7925. * morphTargets: <bool>,
  7926. * morphNormals: <bool>,
  7927. *
  7928. * fog: <bool>
  7929. * }
  7930. */
  7931. THREE.MeshLambertMaterial = function ( parameters ) {
  7932. THREE.Material.call( this );
  7933. this.color = new THREE.Color( 0xffffff ); // diffuse
  7934. this.ambient = new THREE.Color( 0xffffff );
  7935. this.emissive = new THREE.Color( 0x000000 );
  7936. this.wrapAround = false;
  7937. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7938. this.map = null;
  7939. this.lightMap = null;
  7940. this.specularMap = null;
  7941. this.envMap = null;
  7942. this.combine = THREE.MultiplyOperation;
  7943. this.reflectivity = 1;
  7944. this.refractionRatio = 0.98;
  7945. this.fog = true;
  7946. this.shading = THREE.SmoothShading;
  7947. this.wireframe = false;
  7948. this.wireframeLinewidth = 1;
  7949. this.wireframeLinecap = 'round';
  7950. this.wireframeLinejoin = 'round';
  7951. this.vertexColors = THREE.NoColors;
  7952. this.skinning = false;
  7953. this.morphTargets = false;
  7954. this.morphNormals = false;
  7955. this.setValues( parameters );
  7956. };
  7957. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  7958. THREE.MeshLambertMaterial.prototype.clone = function () {
  7959. var material = new THREE.MeshLambertMaterial();
  7960. THREE.Material.prototype.clone.call( this, material );
  7961. material.color.copy( this.color );
  7962. material.ambient.copy( this.ambient );
  7963. material.emissive.copy( this.emissive );
  7964. material.wrapAround = this.wrapAround;
  7965. material.wrapRGB.copy( this.wrapRGB );
  7966. material.map = this.map;
  7967. material.lightMap = this.lightMap;
  7968. material.specularMap = this.specularMap;
  7969. material.envMap = this.envMap;
  7970. material.combine = this.combine;
  7971. material.reflectivity = this.reflectivity;
  7972. material.refractionRatio = this.refractionRatio;
  7973. material.fog = this.fog;
  7974. material.shading = this.shading;
  7975. material.wireframe = this.wireframe;
  7976. material.wireframeLinewidth = this.wireframeLinewidth;
  7977. material.wireframeLinecap = this.wireframeLinecap;
  7978. material.wireframeLinejoin = this.wireframeLinejoin;
  7979. material.vertexColors = this.vertexColors;
  7980. material.skinning = this.skinning;
  7981. material.morphTargets = this.morphTargets;
  7982. material.morphNormals = this.morphNormals;
  7983. return material;
  7984. };
  7985. /**
  7986. * @author mrdoob / http://mrdoob.com/
  7987. * @author alteredq / http://alteredqualia.com/
  7988. *
  7989. * parameters = {
  7990. * color: <hex>,
  7991. * ambient: <hex>,
  7992. * emissive: <hex>,
  7993. * specular: <hex>,
  7994. * shininess: <float>,
  7995. * opacity: <float>,
  7996. *
  7997. * map: new THREE.Texture( <Image> ),
  7998. *
  7999. * lightMap: new THREE.Texture( <Image> ),
  8000. *
  8001. * bumpMap: new THREE.Texture( <Image> ),
  8002. * bumpScale: <float>,
  8003. *
  8004. * normalMap: new THREE.Texture( <Image> ),
  8005. * normalScale: <Vector2>,
  8006. *
  8007. * specularMap: new THREE.Texture( <Image> ),
  8008. *
  8009. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8010. * combine: THREE.Multiply,
  8011. * reflectivity: <float>,
  8012. * refractionRatio: <float>,
  8013. *
  8014. * shading: THREE.SmoothShading,
  8015. * blending: THREE.NormalBlending,
  8016. * depthTest: <bool>,
  8017. * depthWrite: <bool>,
  8018. *
  8019. * wireframe: <boolean>,
  8020. * wireframeLinewidth: <float>,
  8021. *
  8022. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8023. *
  8024. * skinning: <bool>,
  8025. * morphTargets: <bool>,
  8026. * morphNormals: <bool>,
  8027. *
  8028. * fog: <bool>
  8029. * }
  8030. */
  8031. THREE.MeshPhongMaterial = function ( parameters ) {
  8032. THREE.Material.call( this );
  8033. this.color = new THREE.Color( 0xffffff ); // diffuse
  8034. this.ambient = new THREE.Color( 0xffffff );
  8035. this.emissive = new THREE.Color( 0x000000 );
  8036. this.specular = new THREE.Color( 0x111111 );
  8037. this.shininess = 30;
  8038. this.metal = false;
  8039. this.perPixel = true;
  8040. this.wrapAround = false;
  8041. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8042. this.map = null;
  8043. this.lightMap = null;
  8044. this.bumpMap = null;
  8045. this.bumpScale = 1;
  8046. this.normalMap = null;
  8047. this.normalScale = new THREE.Vector2( 1, 1 );
  8048. this.specularMap = null;
  8049. this.envMap = null;
  8050. this.combine = THREE.MultiplyOperation;
  8051. this.reflectivity = 1;
  8052. this.refractionRatio = 0.98;
  8053. this.fog = true;
  8054. this.shading = THREE.SmoothShading;
  8055. this.wireframe = false;
  8056. this.wireframeLinewidth = 1;
  8057. this.wireframeLinecap = 'round';
  8058. this.wireframeLinejoin = 'round';
  8059. this.vertexColors = THREE.NoColors;
  8060. this.skinning = false;
  8061. this.morphTargets = false;
  8062. this.morphNormals = false;
  8063. this.setValues( parameters );
  8064. };
  8065. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8066. THREE.MeshPhongMaterial.prototype.clone = function () {
  8067. var material = new THREE.MeshPhongMaterial();
  8068. THREE.Material.prototype.clone.call( this, material );
  8069. material.color.copy( this.color );
  8070. material.ambient.copy( this.ambient );
  8071. material.emissive.copy( this.emissive );
  8072. material.specular.copy( this.specular );
  8073. material.shininess = this.shininess;
  8074. material.metal = this.metal;
  8075. material.perPixel = this.perPixel;
  8076. material.wrapAround = this.wrapAround;
  8077. material.wrapRGB.copy( this.wrapRGB );
  8078. material.map = this.map;
  8079. material.lightMap = this.lightMap;
  8080. material.bumpMap = this.bumpMap;
  8081. material.bumpScale = this.bumpScale;
  8082. material.normalMap = this.normalMap;
  8083. material.normalScale.copy( this.normalScale );
  8084. material.specularMap = this.specularMap;
  8085. material.envMap = this.envMap;
  8086. material.combine = this.combine;
  8087. material.reflectivity = this.reflectivity;
  8088. material.refractionRatio = this.refractionRatio;
  8089. material.fog = this.fog;
  8090. material.shading = this.shading;
  8091. material.wireframe = this.wireframe;
  8092. material.wireframeLinewidth = this.wireframeLinewidth;
  8093. material.wireframeLinecap = this.wireframeLinecap;
  8094. material.wireframeLinejoin = this.wireframeLinejoin;
  8095. material.vertexColors = this.vertexColors;
  8096. material.skinning = this.skinning;
  8097. material.morphTargets = this.morphTargets;
  8098. material.morphNormals = this.morphNormals;
  8099. return material;
  8100. };
  8101. /**
  8102. * @author mrdoob / http://mrdoob.com/
  8103. * @author alteredq / http://alteredqualia.com/
  8104. *
  8105. * parameters = {
  8106. * opacity: <float>,
  8107. *
  8108. * blending: THREE.NormalBlending,
  8109. * depthTest: <bool>,
  8110. * depthWrite: <bool>,
  8111. *
  8112. * wireframe: <boolean>,
  8113. * wireframeLinewidth: <float>
  8114. * }
  8115. */
  8116. THREE.MeshDepthMaterial = function ( parameters ) {
  8117. THREE.Material.call( this );
  8118. this.wireframe = false;
  8119. this.wireframeLinewidth = 1;
  8120. this.setValues( parameters );
  8121. };
  8122. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  8123. THREE.MeshDepthMaterial.prototype.clone = function () {
  8124. var material = new THREE.MeshDepthMaterial();
  8125. THREE.Material.prototype.clone.call( this, material );
  8126. material.wireframe = this.wireframe;
  8127. material.wireframeLinewidth = this.wireframeLinewidth;
  8128. return material;
  8129. };
  8130. /**
  8131. * @author mrdoob / http://mrdoob.com/
  8132. *
  8133. * parameters = {
  8134. * opacity: <float>,
  8135. *
  8136. * shading: THREE.FlatShading,
  8137. * blending: THREE.NormalBlending,
  8138. * depthTest: <bool>,
  8139. * depthWrite: <bool>,
  8140. *
  8141. * wireframe: <boolean>,
  8142. * wireframeLinewidth: <float>
  8143. * }
  8144. */
  8145. THREE.MeshNormalMaterial = function ( parameters ) {
  8146. THREE.Material.call( this, parameters );
  8147. this.shading = THREE.FlatShading;
  8148. this.wireframe = false;
  8149. this.wireframeLinewidth = 1;
  8150. this.morphTargets = false;
  8151. this.setValues( parameters );
  8152. };
  8153. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  8154. THREE.MeshNormalMaterial.prototype.clone = function () {
  8155. var material = new THREE.MeshNormalMaterial();
  8156. THREE.Material.prototype.clone.call( this, material );
  8157. material.shading = this.shading;
  8158. material.wireframe = this.wireframe;
  8159. material.wireframeLinewidth = this.wireframeLinewidth;
  8160. return material;
  8161. };
  8162. /**
  8163. * @author mrdoob / http://mrdoob.com/
  8164. */
  8165. THREE.MeshFaceMaterial = function ( materials ) {
  8166. this.materials = materials instanceof Array ? materials : [];
  8167. };
  8168. THREE.MeshFaceMaterial.prototype.clone = function () {
  8169. var material = new THREE.MeshFaceMaterial();
  8170. for ( var i = 0; i < this.materials.length; i ++ ) {
  8171. material.materials.push( this.materials[ i ].clone() );
  8172. }
  8173. return material;
  8174. };
  8175. /**
  8176. * @author mrdoob / http://mrdoob.com/
  8177. * @author alteredq / http://alteredqualia.com/
  8178. *
  8179. * parameters = {
  8180. * color: <hex>,
  8181. * opacity: <float>,
  8182. * map: new THREE.Texture( <Image> ),
  8183. *
  8184. * size: <float>,
  8185. *
  8186. * blending: THREE.NormalBlending,
  8187. * depthTest: <bool>,
  8188. * depthWrite: <bool>,
  8189. *
  8190. * vertexColors: <bool>,
  8191. *
  8192. * fog: <bool>
  8193. * }
  8194. */
  8195. THREE.ParticleSystemMaterial = function ( parameters ) {
  8196. THREE.Material.call( this );
  8197. this.color = new THREE.Color( 0xffffff );
  8198. this.map = null;
  8199. this.size = 1;
  8200. this.sizeAttenuation = true;
  8201. this.vertexColors = false;
  8202. this.fog = true;
  8203. this.setValues( parameters );
  8204. };
  8205. THREE.ParticleSystemMaterial.prototype = Object.create( THREE.Material.prototype );
  8206. THREE.ParticleSystemMaterial.prototype.clone = function () {
  8207. var material = new THREE.ParticleSystemMaterial();
  8208. THREE.Material.prototype.clone.call( this, material );
  8209. material.color.copy( this.color );
  8210. material.map = this.map;
  8211. material.size = this.size;
  8212. material.sizeAttenuation = this.sizeAttenuation;
  8213. material.vertexColors = this.vertexColors;
  8214. material.fog = this.fog;
  8215. return material;
  8216. };
  8217. // backwards compatibility
  8218. THREE.ParticleBasicMaterial = THREE.ParticleSystemMaterial;
  8219. /**
  8220. * @author alteredq / http://alteredqualia.com/
  8221. *
  8222. * parameters = {
  8223. * fragmentShader: <string>,
  8224. * vertexShader: <string>,
  8225. *
  8226. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  8227. *
  8228. * defines: { "label" : "value" },
  8229. *
  8230. * shading: THREE.SmoothShading,
  8231. * blending: THREE.NormalBlending,
  8232. * depthTest: <bool>,
  8233. * depthWrite: <bool>,
  8234. *
  8235. * wireframe: <boolean>,
  8236. * wireframeLinewidth: <float>,
  8237. *
  8238. * lights: <bool>,
  8239. *
  8240. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8241. *
  8242. * skinning: <bool>,
  8243. * morphTargets: <bool>,
  8244. * morphNormals: <bool>,
  8245. *
  8246. * fog: <bool>
  8247. * }
  8248. */
  8249. THREE.ShaderMaterial = function ( parameters ) {
  8250. THREE.Material.call( this );
  8251. this.fragmentShader = "void main() {}";
  8252. this.vertexShader = "void main() {}";
  8253. this.uniforms = {};
  8254. this.defines = {};
  8255. this.attributes = null;
  8256. this.shading = THREE.SmoothShading;
  8257. this.linewidth = 1;
  8258. this.wireframe = false;
  8259. this.wireframeLinewidth = 1;
  8260. this.fog = false; // set to use scene fog
  8261. this.lights = false; // set to use scene lights
  8262. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  8263. this.skinning = false; // set to use skinning attribute streams
  8264. this.morphTargets = false; // set to use morph targets
  8265. this.morphNormals = false; // set to use morph normals
  8266. // When rendered geometry doesn't include these attributes but the material does,
  8267. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8268. this.defaultAttributeValues = {
  8269. "color" : [ 1, 1, 1],
  8270. "uv" : [ 0, 0 ],
  8271. "uv2" : [ 0, 0 ]
  8272. };
  8273. // By default, bind position to attribute index 0. In WebGL, attribute 0
  8274. // should always be used to avoid potentially expensive emulation.
  8275. this.index0AttributeName = "position";
  8276. this.setValues( parameters );
  8277. };
  8278. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  8279. THREE.ShaderMaterial.prototype.clone = function () {
  8280. var material = new THREE.ShaderMaterial();
  8281. THREE.Material.prototype.clone.call( this, material );
  8282. material.fragmentShader = this.fragmentShader;
  8283. material.vertexShader = this.vertexShader;
  8284. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  8285. material.attributes = this.attributes;
  8286. material.defines = this.defines;
  8287. material.shading = this.shading;
  8288. material.wireframe = this.wireframe;
  8289. material.wireframeLinewidth = this.wireframeLinewidth;
  8290. material.fog = this.fog;
  8291. material.lights = this.lights;
  8292. material.vertexColors = this.vertexColors;
  8293. material.skinning = this.skinning;
  8294. material.morphTargets = this.morphTargets;
  8295. material.morphNormals = this.morphNormals;
  8296. return material;
  8297. };
  8298. /**
  8299. * @author alteredq / http://alteredqualia.com/
  8300. *
  8301. * parameters = {
  8302. * color: <hex>,
  8303. * opacity: <float>,
  8304. * map: new THREE.Texture( <Image> ),
  8305. *
  8306. * blending: THREE.NormalBlending,
  8307. * depthTest: <bool>,
  8308. * depthWrite: <bool>,
  8309. *
  8310. * useScreenCoordinates: <bool>,
  8311. * sizeAttenuation: <bool>,
  8312. * alignment: THREE.SpriteAlignment.center,
  8313. *
  8314. * uvOffset: new THREE.Vector2(),
  8315. * uvScale: new THREE.Vector2(),
  8316. *
  8317. * fog: <bool>
  8318. * }
  8319. */
  8320. THREE.SpriteMaterial = function ( parameters ) {
  8321. THREE.Material.call( this );
  8322. // defaults
  8323. this.color = new THREE.Color( 0xffffff );
  8324. this.map = new THREE.Texture();
  8325. this.useScreenCoordinates = true;
  8326. this.depthTest = !this.useScreenCoordinates;
  8327. this.sizeAttenuation = !this.useScreenCoordinates;
  8328. this.alignment = THREE.SpriteAlignment.center.clone();
  8329. this.fog = false;
  8330. this.uvOffset = new THREE.Vector2( 0, 0 );
  8331. this.uvScale = new THREE.Vector2( 1, 1 );
  8332. // set parameters
  8333. this.setValues( parameters );
  8334. // override coupled defaults if not specified explicitly by parameters
  8335. parameters = parameters || {};
  8336. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  8337. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  8338. };
  8339. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8340. THREE.SpriteMaterial.prototype.clone = function () {
  8341. var material = new THREE.SpriteMaterial();
  8342. THREE.Material.prototype.clone.call( this, material );
  8343. material.color.copy( this.color );
  8344. material.map = this.map;
  8345. material.useScreenCoordinates = this.useScreenCoordinates;
  8346. material.sizeAttenuation = this.sizeAttenuation;
  8347. material.alignment.copy( this.alignment );
  8348. material.uvOffset.copy( this.uvOffset );
  8349. material.uvScale.copy( this.uvScale );
  8350. material.fog = this.fog;
  8351. return material;
  8352. };
  8353. // Alignment enums
  8354. THREE.SpriteAlignment = {};
  8355. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 0.5, -0.5 );
  8356. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -0.5 );
  8357. THREE.SpriteAlignment.topRight = new THREE.Vector2( -0.5, -0.5 );
  8358. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 0.5, 0 );
  8359. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  8360. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -0.5, 0 );
  8361. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 0.5, 0.5 );
  8362. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 0.5 );
  8363. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -0.5, 0.5 );
  8364. /**
  8365. * @author mrdoob / http://mrdoob.com/
  8366. *
  8367. * parameters = {
  8368. * color: <hex>,
  8369. * program: <function>,
  8370. * opacity: <float>,
  8371. * blending: THREE.NormalBlending
  8372. * }
  8373. */
  8374. THREE.SpriteCanvasMaterial = function ( parameters ) {
  8375. THREE.Material.call( this );
  8376. this.color = new THREE.Color( 0xffffff );
  8377. this.program = function ( context, color ) {};
  8378. this.setValues( parameters );
  8379. };
  8380. THREE.SpriteCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  8381. THREE.SpriteCanvasMaterial.prototype.clone = function () {
  8382. var material = new THREE.SpriteCanvasMaterial();
  8383. THREE.Material.prototype.clone.call( this, material );
  8384. material.color.copy( this.color );
  8385. material.program = this.program;
  8386. return material;
  8387. };
  8388. // backwards compatibility
  8389. THREE.ParticleCanvasMaterial = THREE.SpriteCanvasMaterial;
  8390. /**
  8391. * @author mrdoob / http://mrdoob.com/
  8392. * @author alteredq / http://alteredqualia.com/
  8393. * @author szimek / https://github.com/szimek/
  8394. */
  8395. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8396. this.id = THREE.TextureIdCount ++;
  8397. this.uuid = THREE.Math.generateUUID();
  8398. this.name = '';
  8399. this.image = image;
  8400. this.mipmaps = [];
  8401. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  8402. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8403. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8404. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8405. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8406. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8407. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8408. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8409. this.offset = new THREE.Vector2( 0, 0 );
  8410. this.repeat = new THREE.Vector2( 1, 1 );
  8411. this.generateMipmaps = true;
  8412. this.premultiplyAlpha = false;
  8413. this.flipY = true;
  8414. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8415. this.needsUpdate = false;
  8416. this.onUpdate = null;
  8417. };
  8418. THREE.Texture.prototype = {
  8419. constructor: THREE.Texture,
  8420. clone: function ( texture ) {
  8421. if ( texture === undefined ) texture = new THREE.Texture();
  8422. texture.image = this.image;
  8423. texture.mipmaps = this.mipmaps.slice(0);
  8424. texture.mapping = this.mapping;
  8425. texture.wrapS = this.wrapS;
  8426. texture.wrapT = this.wrapT;
  8427. texture.magFilter = this.magFilter;
  8428. texture.minFilter = this.minFilter;
  8429. texture.anisotropy = this.anisotropy;
  8430. texture.format = this.format;
  8431. texture.type = this.type;
  8432. texture.offset.copy( this.offset );
  8433. texture.repeat.copy( this.repeat );
  8434. texture.generateMipmaps = this.generateMipmaps;
  8435. texture.premultiplyAlpha = this.premultiplyAlpha;
  8436. texture.flipY = this.flipY;
  8437. texture.unpackAlignment = this.unpackAlignment;
  8438. return texture;
  8439. },
  8440. dispose: function () {
  8441. this.dispatchEvent( { type: 'dispose' } );
  8442. }
  8443. };
  8444. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  8445. THREE.TextureIdCount = 0;
  8446. /**
  8447. * @author alteredq / http://alteredqualia.com/
  8448. */
  8449. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8450. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8451. this.image = { width: width, height: height };
  8452. this.mipmaps = mipmaps;
  8453. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  8454. };
  8455. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8456. THREE.CompressedTexture.prototype.clone = function () {
  8457. var texture = new THREE.CompressedTexture();
  8458. THREE.Texture.prototype.clone.call( this, texture );
  8459. return texture;
  8460. };
  8461. /**
  8462. * @author alteredq / http://alteredqualia.com/
  8463. */
  8464. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8465. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8466. this.image = { data: data, width: width, height: height };
  8467. };
  8468. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8469. THREE.DataTexture.prototype.clone = function () {
  8470. var texture = new THREE.DataTexture();
  8471. THREE.Texture.prototype.clone.call( this, texture );
  8472. return texture;
  8473. };
  8474. /**
  8475. * @author alteredq / http://alteredqualia.com/
  8476. */
  8477. THREE.ParticleSystem = function ( geometry, material ) {
  8478. THREE.Object3D.call( this );
  8479. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8480. this.material = material !== undefined ? material : new THREE.ParticleSystemMaterial( { color: Math.random() * 0xffffff } );
  8481. this.sortParticles = false;
  8482. this.frustumCulled = false;
  8483. };
  8484. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  8485. THREE.ParticleSystem.prototype.clone = function ( object ) {
  8486. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  8487. object.sortParticles = this.sortParticles;
  8488. THREE.Object3D.prototype.clone.call( this, object );
  8489. return object;
  8490. };
  8491. /**
  8492. * @author mrdoob / http://mrdoob.com/
  8493. */
  8494. THREE.Line = function ( geometry, material, type ) {
  8495. THREE.Object3D.call( this );
  8496. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8497. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  8498. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  8499. };
  8500. THREE.LineStrip = 0;
  8501. THREE.LinePieces = 1;
  8502. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  8503. THREE.Line.prototype.clone = function ( object ) {
  8504. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  8505. THREE.Object3D.prototype.clone.call( this, object );
  8506. return object;
  8507. };
  8508. /**
  8509. * @author mrdoob / http://mrdoob.com/
  8510. * @author alteredq / http://alteredqualia.com/
  8511. * @author mikael emtinger / http://gomo.se/
  8512. * @author jonobr1 / http://jonobr1.com/
  8513. */
  8514. THREE.Mesh = function ( geometry, material ) {
  8515. THREE.Object3D.call( this );
  8516. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8517. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  8518. this.updateMorphTargets();
  8519. };
  8520. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  8521. THREE.Mesh.prototype.updateMorphTargets = function () {
  8522. if ( this.geometry.morphTargets.length > 0 ) {
  8523. this.morphTargetBase = -1;
  8524. this.morphTargetForcedOrder = [];
  8525. this.morphTargetInfluences = [];
  8526. this.morphTargetDictionary = {};
  8527. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  8528. this.morphTargetInfluences.push( 0 );
  8529. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  8530. }
  8531. }
  8532. };
  8533. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  8534. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  8535. return this.morphTargetDictionary[ name ];
  8536. }
  8537. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  8538. return 0;
  8539. };
  8540. THREE.Mesh.prototype.clone = function ( object ) {
  8541. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  8542. THREE.Object3D.prototype.clone.call( this, object );
  8543. return object;
  8544. };
  8545. /**
  8546. * @author mikael emtinger / http://gomo.se/
  8547. * @author alteredq / http://alteredqualia.com/
  8548. */
  8549. THREE.Bone = function( belongsToSkin ) {
  8550. THREE.Object3D.call( this );
  8551. this.skin = belongsToSkin;
  8552. this.skinMatrix = new THREE.Matrix4();
  8553. };
  8554. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  8555. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  8556. // update local
  8557. if ( this.matrixAutoUpdate ) {
  8558. forceUpdate |= this.updateMatrix();
  8559. }
  8560. // update skin matrix
  8561. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  8562. if( parentSkinMatrix ) {
  8563. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  8564. } else {
  8565. this.skinMatrix.copy( this.matrix );
  8566. }
  8567. this.matrixWorldNeedsUpdate = false;
  8568. forceUpdate = true;
  8569. }
  8570. // update children
  8571. var child, i, l = this.children.length;
  8572. for ( i = 0; i < l; i ++ ) {
  8573. this.children[ i ].update( this.skinMatrix, forceUpdate );
  8574. }
  8575. };
  8576. /**
  8577. * @author mikael emtinger / http://gomo.se/
  8578. * @author alteredq / http://alteredqualia.com/
  8579. */
  8580. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  8581. THREE.Mesh.call( this, geometry, material );
  8582. //
  8583. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  8584. // init bones
  8585. this.identityMatrix = new THREE.Matrix4();
  8586. this.bones = [];
  8587. this.boneMatrices = [];
  8588. var b, bone, gbone, p, q, s;
  8589. if ( this.geometry && this.geometry.bones !== undefined ) {
  8590. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  8591. gbone = this.geometry.bones[ b ];
  8592. p = gbone.pos;
  8593. q = gbone.rotq;
  8594. s = gbone.scl;
  8595. bone = this.addBone();
  8596. bone.name = gbone.name;
  8597. bone.position.set( p[0], p[1], p[2] );
  8598. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  8599. if ( s !== undefined ) {
  8600. bone.scale.set( s[0], s[1], s[2] );
  8601. } else {
  8602. bone.scale.set( 1, 1, 1 );
  8603. }
  8604. }
  8605. for ( b = 0; b < this.bones.length; b ++ ) {
  8606. gbone = this.geometry.bones[ b ];
  8607. bone = this.bones[ b ];
  8608. if ( gbone.parent === -1 ) {
  8609. this.add( bone );
  8610. } else {
  8611. this.bones[ gbone.parent ].add( bone );
  8612. }
  8613. }
  8614. //
  8615. var nBones = this.bones.length;
  8616. if ( this.useVertexTexture ) {
  8617. // layout (1 matrix = 4 pixels)
  8618. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8619. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  8620. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  8621. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  8622. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  8623. var size;
  8624. if ( nBones > 256 )
  8625. size = 64;
  8626. else if ( nBones > 64 )
  8627. size = 32;
  8628. else if ( nBones > 16 )
  8629. size = 16;
  8630. else
  8631. size = 8;
  8632. this.boneTextureWidth = size;
  8633. this.boneTextureHeight = size;
  8634. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  8635. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  8636. this.boneTexture.minFilter = THREE.NearestFilter;
  8637. this.boneTexture.magFilter = THREE.NearestFilter;
  8638. this.boneTexture.generateMipmaps = false;
  8639. this.boneTexture.flipY = false;
  8640. } else {
  8641. this.boneMatrices = new Float32Array( 16 * nBones );
  8642. }
  8643. this.pose();
  8644. }
  8645. };
  8646. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  8647. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  8648. if ( bone === undefined ) {
  8649. bone = new THREE.Bone( this );
  8650. }
  8651. this.bones.push( bone );
  8652. return bone;
  8653. };
  8654. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  8655. var offsetMatrix = new THREE.Matrix4();
  8656. return function ( force ) {
  8657. this.matrixAutoUpdate && this.updateMatrix();
  8658. // update matrixWorld
  8659. if ( this.matrixWorldNeedsUpdate || force ) {
  8660. if ( this.parent ) {
  8661. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8662. } else {
  8663. this.matrixWorld.copy( this.matrix );
  8664. }
  8665. this.matrixWorldNeedsUpdate = false;
  8666. force = true;
  8667. }
  8668. // update children
  8669. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8670. var child = this.children[ i ];
  8671. if ( child instanceof THREE.Bone ) {
  8672. child.update( this.identityMatrix, false );
  8673. } else {
  8674. child.updateMatrixWorld( true );
  8675. }
  8676. }
  8677. // make a snapshot of the bones' rest position
  8678. if ( this.boneInverses == undefined ) {
  8679. this.boneInverses = [];
  8680. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8681. var inverse = new THREE.Matrix4();
  8682. inverse.getInverse( this.bones[ b ].skinMatrix );
  8683. this.boneInverses.push( inverse );
  8684. }
  8685. }
  8686. // flatten bone matrices to array
  8687. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8688. // compute the offset between the current and the original transform;
  8689. // TODO: we could get rid of this multiplication step if the skinMatrix
  8690. // was already representing the offset; however, this requires some
  8691. // major changes to the animation system
  8692. offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  8693. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  8694. }
  8695. if ( this.useVertexTexture ) {
  8696. this.boneTexture.needsUpdate = true;
  8697. }
  8698. };
  8699. }();
  8700. THREE.SkinnedMesh.prototype.pose = function () {
  8701. this.updateMatrixWorld( true );
  8702. this.normalizeSkinWeights();
  8703. };
  8704. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  8705. if ( this.geometry instanceof THREE.Geometry ) {
  8706. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  8707. var sw = this.geometry.skinWeights[ i ];
  8708. var scale = 1.0 / sw.lengthManhattan();
  8709. if ( scale !== Infinity ) {
  8710. sw.multiplyScalar( scale );
  8711. } else {
  8712. sw.set( 1 ); // this will be normalized by the shader anyway
  8713. }
  8714. }
  8715. } else {
  8716. // skinning weights assumed to be normalized for THREE.BufferGeometry
  8717. }
  8718. };
  8719. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  8720. if ( object === undefined ) {
  8721. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  8722. }
  8723. THREE.Mesh.prototype.clone.call( this, object );
  8724. return object;
  8725. };
  8726. /**
  8727. * @author alteredq / http://alteredqualia.com/
  8728. */
  8729. THREE.MorphAnimMesh = function ( geometry, material ) {
  8730. THREE.Mesh.call( this, geometry, material );
  8731. // API
  8732. this.duration = 1000; // milliseconds
  8733. this.mirroredLoop = false;
  8734. this.time = 0;
  8735. // internals
  8736. this.lastKeyframe = 0;
  8737. this.currentKeyframe = 0;
  8738. this.direction = 1;
  8739. this.directionBackwards = false;
  8740. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  8741. };
  8742. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  8743. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  8744. this.startKeyframe = start;
  8745. this.endKeyframe = end;
  8746. this.length = this.endKeyframe - this.startKeyframe + 1;
  8747. };
  8748. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  8749. this.direction = 1;
  8750. this.directionBackwards = false;
  8751. };
  8752. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  8753. this.direction = -1;
  8754. this.directionBackwards = true;
  8755. };
  8756. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  8757. var geometry = this.geometry;
  8758. if ( ! geometry.animations ) geometry.animations = {};
  8759. var firstAnimation, animations = geometry.animations;
  8760. var pattern = /([a-z]+)(\d+)/;
  8761. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  8762. var morph = geometry.morphTargets[ i ];
  8763. var parts = morph.name.match( pattern );
  8764. if ( parts && parts.length > 1 ) {
  8765. var label = parts[ 1 ];
  8766. var num = parts[ 2 ];
  8767. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  8768. var animation = animations[ label ];
  8769. if ( i < animation.start ) animation.start = i;
  8770. if ( i > animation.end ) animation.end = i;
  8771. if ( ! firstAnimation ) firstAnimation = label;
  8772. }
  8773. }
  8774. geometry.firstAnimation = firstAnimation;
  8775. };
  8776. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  8777. if ( ! this.geometry.animations ) this.geometry.animations = {};
  8778. this.geometry.animations[ label ] = { start: start, end: end };
  8779. };
  8780. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  8781. var animation = this.geometry.animations[ label ];
  8782. if ( animation ) {
  8783. this.setFrameRange( animation.start, animation.end );
  8784. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  8785. this.time = 0;
  8786. } else {
  8787. console.warn( "animation[" + label + "] undefined" );
  8788. }
  8789. };
  8790. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  8791. var frameTime = this.duration / this.length;
  8792. this.time += this.direction * delta;
  8793. if ( this.mirroredLoop ) {
  8794. if ( this.time > this.duration || this.time < 0 ) {
  8795. this.direction *= -1;
  8796. if ( this.time > this.duration ) {
  8797. this.time = this.duration;
  8798. this.directionBackwards = true;
  8799. }
  8800. if ( this.time < 0 ) {
  8801. this.time = 0;
  8802. this.directionBackwards = false;
  8803. }
  8804. }
  8805. } else {
  8806. this.time = this.time % this.duration;
  8807. if ( this.time < 0 ) this.time += this.duration;
  8808. }
  8809. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  8810. if ( keyframe !== this.currentKeyframe ) {
  8811. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  8812. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  8813. this.morphTargetInfluences[ keyframe ] = 0;
  8814. this.lastKeyframe = this.currentKeyframe;
  8815. this.currentKeyframe = keyframe;
  8816. }
  8817. var mix = ( this.time % frameTime ) / frameTime;
  8818. if ( this.directionBackwards ) {
  8819. mix = 1 - mix;
  8820. }
  8821. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  8822. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  8823. };
  8824. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  8825. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  8826. object.duration = this.duration;
  8827. object.mirroredLoop = this.mirroredLoop;
  8828. object.time = this.time;
  8829. object.lastKeyframe = this.lastKeyframe;
  8830. object.currentKeyframe = this.currentKeyframe;
  8831. object.direction = this.direction;
  8832. object.directionBackwards = this.directionBackwards;
  8833. THREE.Mesh.prototype.clone.call( this, object );
  8834. return object;
  8835. };
  8836. /**
  8837. * @author mikael emtinger / http://gomo.se/
  8838. * @author alteredq / http://alteredqualia.com/
  8839. * @author mrdoob / http://mrdoob.com/
  8840. */
  8841. THREE.LOD = function () {
  8842. THREE.Object3D.call( this );
  8843. this.objects = [];
  8844. };
  8845. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  8846. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  8847. if ( distance === undefined ) distance = 0;
  8848. distance = Math.abs( distance );
  8849. for ( var l = 0; l < this.objects.length; l ++ ) {
  8850. if ( distance < this.objects[ l ].distance ) {
  8851. break;
  8852. }
  8853. }
  8854. this.objects.splice( l, 0, { distance: distance, object: object } );
  8855. this.add( object );
  8856. };
  8857. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  8858. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8859. if ( distance < this.objects[ i ].distance ) {
  8860. break;
  8861. }
  8862. }
  8863. return this.objects[ i - 1 ].object;
  8864. };
  8865. THREE.LOD.prototype.update = function () {
  8866. var v1 = new THREE.Vector3();
  8867. var v2 = new THREE.Vector3();
  8868. return function ( camera ) {
  8869. if ( this.objects.length > 1 ) {
  8870. v1.getPositionFromMatrix( camera.matrixWorld );
  8871. v2.getPositionFromMatrix( this.matrixWorld );
  8872. var distance = v1.distanceTo( v2 );
  8873. this.objects[ 0 ].object.visible = true;
  8874. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8875. if ( distance >= this.objects[ i ].distance ) {
  8876. this.objects[ i - 1 ].object.visible = false;
  8877. this.objects[ i ].object.visible = true;
  8878. } else {
  8879. break;
  8880. }
  8881. }
  8882. for( ; i < l; i ++ ) {
  8883. this.objects[ i ].object.visible = false;
  8884. }
  8885. }
  8886. };
  8887. }();
  8888. THREE.LOD.prototype.clone = function () {
  8889. // TODO
  8890. };
  8891. /**
  8892. * @author mikael emtinger / http://gomo.se/
  8893. * @author alteredq / http://alteredqualia.com/
  8894. */
  8895. THREE.Sprite = function ( material ) {
  8896. THREE.Object3D.call( this );
  8897. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  8898. this.rotation = 0;
  8899. };
  8900. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  8901. /*
  8902. * Custom update matrix
  8903. */
  8904. THREE.Sprite.prototype.updateMatrix = function () {
  8905. this.matrix.compose( this.position, this.quaternion, this.scale );
  8906. this.matrixWorldNeedsUpdate = true;
  8907. };
  8908. THREE.Sprite.prototype.clone = function ( object ) {
  8909. if ( object === undefined ) object = new THREE.Sprite( this.material );
  8910. THREE.Object3D.prototype.clone.call( this, object );
  8911. return object;
  8912. };
  8913. // Backwards compatibility
  8914. THREE.Particle = THREE.Sprite;
  8915. /**
  8916. * @author mrdoob / http://mrdoob.com/
  8917. */
  8918. THREE.Scene = function () {
  8919. THREE.Object3D.call( this );
  8920. this.fog = null;
  8921. this.overrideMaterial = null;
  8922. this.autoUpdate = true; // checked by the renderer
  8923. this.matrixAutoUpdate = false;
  8924. this.__lights = [];
  8925. this.__objectsAdded = [];
  8926. this.__objectsRemoved = [];
  8927. };
  8928. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  8929. THREE.Scene.prototype.__addObject = function ( object ) {
  8930. if ( object instanceof THREE.Light ) {
  8931. if ( this.__lights.indexOf( object ) === - 1 ) {
  8932. this.__lights.push( object );
  8933. }
  8934. if ( object.target && object.target.parent === undefined ) {
  8935. this.add( object.target );
  8936. }
  8937. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  8938. this.__objectsAdded.push( object );
  8939. // check if previously removed
  8940. var i = this.__objectsRemoved.indexOf( object );
  8941. if ( i !== -1 ) {
  8942. this.__objectsRemoved.splice( i, 1 );
  8943. }
  8944. }
  8945. for ( var c = 0; c < object.children.length; c ++ ) {
  8946. this.__addObject( object.children[ c ] );
  8947. }
  8948. };
  8949. THREE.Scene.prototype.__removeObject = function ( object ) {
  8950. if ( object instanceof THREE.Light ) {
  8951. var i = this.__lights.indexOf( object );
  8952. if ( i !== -1 ) {
  8953. this.__lights.splice( i, 1 );
  8954. }
  8955. if ( object.shadowCascadeArray ) {
  8956. for ( var x = 0; x < object.shadowCascadeArray.length; x ++ ) {
  8957. this.__removeObject( object.shadowCascadeArray[ x ] );
  8958. }
  8959. }
  8960. } else if ( !( object instanceof THREE.Camera ) ) {
  8961. this.__objectsRemoved.push( object );
  8962. // check if previously added
  8963. var i = this.__objectsAdded.indexOf( object );
  8964. if ( i !== -1 ) {
  8965. this.__objectsAdded.splice( i, 1 );
  8966. }
  8967. }
  8968. for ( var c = 0; c < object.children.length; c ++ ) {
  8969. this.__removeObject( object.children[ c ] );
  8970. }
  8971. };
  8972. THREE.Scene.prototype.clone = function ( object ) {
  8973. if ( object === undefined ) object = new THREE.Scene();
  8974. THREE.Object3D.prototype.clone.call(this, object);
  8975. if ( this.fog !== null ) object.fog = this.fog.clone();
  8976. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  8977. object.autoUpdate = this.autoUpdate;
  8978. object.matrixAutoUpdate = this.matrixAutoUpdate;
  8979. return object;
  8980. };
  8981. /**
  8982. * @author mrdoob / http://mrdoob.com/
  8983. * @author alteredq / http://alteredqualia.com/
  8984. */
  8985. THREE.Fog = function ( hex, near, far ) {
  8986. this.name = '';
  8987. this.color = new THREE.Color( hex );
  8988. this.near = ( near !== undefined ) ? near : 1;
  8989. this.far = ( far !== undefined ) ? far : 1000;
  8990. };
  8991. THREE.Fog.prototype.clone = function () {
  8992. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  8993. };
  8994. /**
  8995. * @author mrdoob / http://mrdoob.com/
  8996. * @author alteredq / http://alteredqualia.com/
  8997. */
  8998. THREE.FogExp2 = function ( hex, density ) {
  8999. this.name = '';
  9000. this.color = new THREE.Color( hex );
  9001. this.density = ( density !== undefined ) ? density : 0.00025;
  9002. };
  9003. THREE.FogExp2.prototype.clone = function () {
  9004. return new THREE.FogExp2( this.color.getHex(), this.density );
  9005. };
  9006. /**
  9007. * @author mrdoob / http://mrdoob.com/
  9008. */
  9009. THREE.CanvasRenderer = function ( parameters ) {
  9010. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  9011. var smoothstep = THREE.Math.smoothstep;
  9012. parameters = parameters || {};
  9013. var _this = this,
  9014. _renderData, _elements, _lights,
  9015. _projector = new THREE.Projector(),
  9016. _canvas = parameters.canvas !== undefined
  9017. ? parameters.canvas
  9018. : document.createElement( 'canvas' ),
  9019. _canvasWidth = _canvas.width,
  9020. _canvasHeight = _canvas.height,
  9021. _canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
  9022. _canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
  9023. _context = _canvas.getContext( '2d' ),
  9024. _clearColor = new THREE.Color( 0x000000 ),
  9025. _clearAlpha = 0,
  9026. _contextGlobalAlpha = 1,
  9027. _contextGlobalCompositeOperation = 0,
  9028. _contextStrokeStyle = null,
  9029. _contextFillStyle = null,
  9030. _contextLineWidth = null,
  9031. _contextLineCap = null,
  9032. _contextLineJoin = null,
  9033. _contextDashSize = null,
  9034. _contextGapSize = 0,
  9035. _camera,
  9036. _v1, _v2, _v3, _v4,
  9037. _v5 = new THREE.RenderableVertex(),
  9038. _v6 = new THREE.RenderableVertex(),
  9039. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  9040. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  9041. _color = new THREE.Color(),
  9042. _color1 = new THREE.Color(),
  9043. _color2 = new THREE.Color(),
  9044. _color3 = new THREE.Color(),
  9045. _color4 = new THREE.Color(),
  9046. _diffuseColor = new THREE.Color(),
  9047. _emissiveColor = new THREE.Color(),
  9048. _lightColor = new THREE.Color(),
  9049. _patterns = {}, _imagedatas = {},
  9050. _near, _far,
  9051. _image, _uvs,
  9052. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  9053. _clipBox = new THREE.Box2(),
  9054. _clearBox = new THREE.Box2(),
  9055. _elemBox = new THREE.Box2(),
  9056. _ambientLight = new THREE.Color(),
  9057. _directionalLights = new THREE.Color(),
  9058. _pointLights = new THREE.Color(),
  9059. _vector3 = new THREE.Vector3(), // Needed for PointLight
  9060. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  9061. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  9062. _pixelMap = document.createElement( 'canvas' );
  9063. _pixelMap.width = _pixelMap.height = 2;
  9064. _pixelMapContext = _pixelMap.getContext( '2d' );
  9065. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  9066. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  9067. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  9068. _pixelMapData = _pixelMapImage.data;
  9069. _gradientMap = document.createElement( 'canvas' );
  9070. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  9071. _gradientMapContext = _gradientMap.getContext( '2d' );
  9072. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  9073. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  9074. _gradientMapQuality --; // Fix UVs
  9075. // dash+gap fallbacks for Firefox and everything else
  9076. if ( _context.setLineDash === undefined ) {
  9077. if ( _context.mozDash !== undefined ) {
  9078. _context.setLineDash = function ( values ) {
  9079. _context.mozDash = values[ 0 ] !== null ? values : null;
  9080. }
  9081. } else {
  9082. _context.setLineDash = function () {}
  9083. }
  9084. }
  9085. this.domElement = _canvas;
  9086. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  9087. ? parameters.devicePixelRatio
  9088. : self.devicePixelRatio !== undefined
  9089. ? self.devicePixelRatio
  9090. : 1;
  9091. this.autoClear = true;
  9092. this.sortObjects = true;
  9093. this.sortElements = true;
  9094. this.info = {
  9095. render: {
  9096. vertices: 0,
  9097. faces: 0
  9098. }
  9099. }
  9100. // WebGLRenderer compatibility
  9101. this.supportsVertexTextures = function () {};
  9102. this.setFaceCulling = function () {};
  9103. this.setSize = function ( width, height, updateStyle ) {
  9104. _canvasWidth = width * this.devicePixelRatio;
  9105. _canvasHeight = height * this.devicePixelRatio;
  9106. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  9107. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  9108. _canvas.width = _canvasWidth;
  9109. _canvas.height = _canvasHeight;
  9110. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  9111. _canvas.style.width = width + 'px';
  9112. _canvas.style.height = height + 'px';
  9113. }
  9114. _clipBox.set(
  9115. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  9116. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  9117. );
  9118. _clearBox.set(
  9119. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  9120. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  9121. );
  9122. _contextGlobalAlpha = 1;
  9123. _contextGlobalCompositeOperation = 0;
  9124. _contextStrokeStyle = null;
  9125. _contextFillStyle = null;
  9126. _contextLineWidth = null;
  9127. _contextLineCap = null;
  9128. _contextLineJoin = null;
  9129. };
  9130. this.setClearColor = function ( color, alpha ) {
  9131. _clearColor.set( color );
  9132. _clearAlpha = alpha !== undefined ? alpha : 1;
  9133. _clearBox.set(
  9134. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  9135. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  9136. );
  9137. };
  9138. this.setClearColorHex = function ( hex, alpha ) {
  9139. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  9140. this.setClearColor( hex, alpha );
  9141. };
  9142. this.getMaxAnisotropy = function () {
  9143. return 0;
  9144. };
  9145. this.clear = function () {
  9146. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  9147. if ( _clearBox.empty() === false ) {
  9148. _clearBox.intersect( _clipBox );
  9149. _clearBox.expandByScalar( 2 );
  9150. if ( _clearAlpha < 1 ) {
  9151. _context.clearRect(
  9152. _clearBox.min.x | 0,
  9153. _clearBox.min.y | 0,
  9154. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9155. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9156. );
  9157. }
  9158. if ( _clearAlpha > 0 ) {
  9159. setBlending( THREE.NormalBlending );
  9160. setOpacity( 1 );
  9161. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  9162. _context.fillRect(
  9163. _clearBox.min.x | 0,
  9164. _clearBox.min.y | 0,
  9165. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9166. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9167. );
  9168. }
  9169. _clearBox.makeEmpty();
  9170. }
  9171. };
  9172. this.render = function ( scene, camera ) {
  9173. if ( camera instanceof THREE.Camera === false ) {
  9174. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  9175. return;
  9176. }
  9177. if ( this.autoClear === true ) this.clear();
  9178. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  9179. _this.info.render.vertices = 0;
  9180. _this.info.render.faces = 0;
  9181. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  9182. _elements = _renderData.elements;
  9183. _lights = _renderData.lights;
  9184. _camera = camera;
  9185. /* DEBUG
  9186. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  9187. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  9188. */
  9189. calculateLights();
  9190. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  9191. var element = _elements[ e ];
  9192. var material = element.material;
  9193. if ( material === undefined || material.visible === false ) continue;
  9194. _elemBox.makeEmpty();
  9195. if ( element instanceof THREE.RenderableSprite ) {
  9196. _v1 = element;
  9197. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  9198. renderSprite( _v1, element, material );
  9199. } else if ( element instanceof THREE.RenderableLine ) {
  9200. _v1 = element.v1; _v2 = element.v2;
  9201. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9202. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9203. _elemBox.setFromPoints( [
  9204. _v1.positionScreen,
  9205. _v2.positionScreen
  9206. ] );
  9207. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9208. renderLine( _v1, _v2, element, material );
  9209. }
  9210. } else if ( element instanceof THREE.RenderableFace3 ) {
  9211. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  9212. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  9213. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  9214. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  9215. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9216. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9217. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  9218. if ( material.overdraw > 0 ) {
  9219. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  9220. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  9221. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  9222. }
  9223. _elemBox.setFromPoints( [
  9224. _v1.positionScreen,
  9225. _v2.positionScreen,
  9226. _v3.positionScreen
  9227. ] );
  9228. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9229. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  9230. }
  9231. }
  9232. /* DEBUG
  9233. setLineWidth( 1 );
  9234. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  9235. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  9236. */
  9237. _clearBox.union( _elemBox );
  9238. }
  9239. /* DEBUG
  9240. setLineWidth( 1 );
  9241. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  9242. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  9243. */
  9244. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  9245. };
  9246. //
  9247. function calculateLights() {
  9248. _ambientLight.setRGB( 0, 0, 0 );
  9249. _directionalLights.setRGB( 0, 0, 0 );
  9250. _pointLights.setRGB( 0, 0, 0 );
  9251. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9252. var light = _lights[ l ];
  9253. var lightColor = light.color;
  9254. if ( light instanceof THREE.AmbientLight ) {
  9255. _ambientLight.add( lightColor );
  9256. } else if ( light instanceof THREE.DirectionalLight ) {
  9257. // for sprites
  9258. _directionalLights.add( lightColor );
  9259. } else if ( light instanceof THREE.PointLight ) {
  9260. // for sprites
  9261. _pointLights.add( lightColor );
  9262. }
  9263. }
  9264. }
  9265. function calculateLight( position, normal, color ) {
  9266. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9267. var light = _lights[ l ];
  9268. _lightColor.copy( light.color );
  9269. if ( light instanceof THREE.DirectionalLight ) {
  9270. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld ).normalize();
  9271. var amount = normal.dot( lightPosition );
  9272. if ( amount <= 0 ) continue;
  9273. amount *= light.intensity;
  9274. color.add( _lightColor.multiplyScalar( amount ) );
  9275. } else if ( light instanceof THREE.PointLight ) {
  9276. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld );
  9277. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  9278. if ( amount <= 0 ) continue;
  9279. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  9280. if ( amount == 0 ) continue;
  9281. amount *= light.intensity;
  9282. color.add( _lightColor.multiplyScalar( amount ) );
  9283. }
  9284. }
  9285. }
  9286. function renderSprite( v1, element, material ) {
  9287. setOpacity( material.opacity );
  9288. setBlending( material.blending );
  9289. var width, height, scaleX, scaleY,
  9290. bitmap, bitmapWidth, bitmapHeight;
  9291. if ( material instanceof THREE.SpriteMaterial ||
  9292. material instanceof THREE.ParticleSystemMaterial ) { // Backwards compatibility
  9293. if ( material.map.image !== undefined ) {
  9294. bitmap = material.map.image;
  9295. bitmapWidth = bitmap.width >> 1;
  9296. bitmapHeight = bitmap.height >> 1;
  9297. scaleX = element.scale.x * _canvasWidthHalf;
  9298. scaleY = element.scale.y * _canvasHeightHalf;
  9299. width = scaleX * bitmapWidth;
  9300. height = scaleY * bitmapHeight;
  9301. // TODO: Rotations break this...
  9302. _elemBox.min.set( v1.x - width, v1.y - height );
  9303. _elemBox.max.set( v1.x + width, v1.y + height );
  9304. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9305. _elemBox.makeEmpty();
  9306. return;
  9307. }
  9308. _context.save();
  9309. _context.translate( v1.x, v1.y );
  9310. _context.rotate( - element.rotation );
  9311. _context.scale( scaleX, - scaleY );
  9312. _context.translate( - bitmapWidth, - bitmapHeight );
  9313. _context.drawImage( bitmap, 0, 0 );
  9314. _context.restore();
  9315. } else {
  9316. scaleX = element.object.scale.x;
  9317. scaleY = element.object.scale.y;
  9318. // TODO: Be able to disable this
  9319. scaleX *= element.scale.x * _canvasWidthHalf;
  9320. scaleY *= element.scale.y * _canvasHeightHalf;
  9321. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  9322. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  9323. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9324. _elemBox.makeEmpty();
  9325. return;
  9326. }
  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( -1, -1, 2, 2 );
  9333. _context.restore();
  9334. }
  9335. /* DEBUG
  9336. setStrokeStyle( 'rgb(255,255,0)' );
  9337. _context.beginPath();
  9338. _context.moveTo( v1.x - 10, v1.y );
  9339. _context.lineTo( v1.x + 10, v1.y );
  9340. _context.moveTo( v1.x, v1.y - 10 );
  9341. _context.lineTo( v1.x, v1.y + 10 );
  9342. _context.stroke();
  9343. */
  9344. } else if ( material instanceof THREE.SpriteCanvasMaterial ) {
  9345. width = element.scale.x * _canvasWidthHalf;
  9346. height = element.scale.y * _canvasHeightHalf;
  9347. _elemBox.min.set( v1.x - width, v1.y - height );
  9348. _elemBox.max.set( v1.x + width, v1.y + height );
  9349. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9350. _elemBox.makeEmpty();
  9351. return;
  9352. }
  9353. setStrokeStyle( material.color.getStyle() );
  9354. setFillStyle( material.color.getStyle() );
  9355. _context.save();
  9356. _context.translate( v1.x, v1.y );
  9357. _context.rotate( - element.rotation );
  9358. _context.scale( width, height );
  9359. material.program( _context );
  9360. _context.restore();
  9361. }
  9362. }
  9363. function renderLine( v1, v2, element, material ) {
  9364. setOpacity( material.opacity );
  9365. setBlending( material.blending );
  9366. _context.beginPath();
  9367. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  9368. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  9369. if ( material instanceof THREE.LineBasicMaterial ) {
  9370. setLineWidth( material.linewidth );
  9371. setLineCap( material.linecap );
  9372. setLineJoin( material.linejoin );
  9373. if ( material.vertexColors !== THREE.VertexColors ) {
  9374. setStrokeStyle( material.color.getStyle() );
  9375. } else {
  9376. var colorStyle1 = element.vertexColors[0].getStyle();
  9377. var colorStyle2 = element.vertexColors[1].getStyle();
  9378. if ( colorStyle1 === colorStyle2 ) {
  9379. setStrokeStyle( colorStyle1 );
  9380. } else {
  9381. try {
  9382. var grad = _context.createLinearGradient(
  9383. v1.positionScreen.x,
  9384. v1.positionScreen.y,
  9385. v2.positionScreen.x,
  9386. v2.positionScreen.y
  9387. );
  9388. grad.addColorStop( 0, colorStyle1 );
  9389. grad.addColorStop( 1, colorStyle2 );
  9390. } catch ( exception ) {
  9391. grad = colorStyle1;
  9392. }
  9393. setStrokeStyle( grad );
  9394. }
  9395. }
  9396. _context.stroke();
  9397. _elemBox.expandByScalar( material.linewidth * 2 );
  9398. } else if ( material instanceof THREE.LineDashedMaterial ) {
  9399. setLineWidth( material.linewidth );
  9400. setLineCap( material.linecap );
  9401. setLineJoin( material.linejoin );
  9402. setStrokeStyle( material.color.getStyle() );
  9403. setDashAndGap( material.dashSize, material.gapSize );
  9404. _context.stroke();
  9405. _elemBox.expandByScalar( material.linewidth * 2 );
  9406. setDashAndGap( null, null );
  9407. }
  9408. }
  9409. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  9410. _this.info.render.vertices += 3;
  9411. _this.info.render.faces ++;
  9412. setOpacity( material.opacity );
  9413. setBlending( material.blending );
  9414. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9415. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9416. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9417. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  9418. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  9419. _diffuseColor.copy( material.color );
  9420. _emissiveColor.copy( material.emissive );
  9421. if ( material.vertexColors === THREE.FaceColors ) {
  9422. _diffuseColor.multiply( element.color );
  9423. }
  9424. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  9425. _color1.copy( _ambientLight );
  9426. _color2.copy( _ambientLight );
  9427. _color3.copy( _ambientLight );
  9428. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  9429. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  9430. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  9431. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  9432. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  9433. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  9434. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9435. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9436. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9437. } else {
  9438. _color.copy( _ambientLight );
  9439. calculateLight( element.centroidModel, element.normalModel, _color );
  9440. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9441. material.wireframe === true
  9442. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9443. : fillPath( _color );
  9444. }
  9445. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9446. if ( material.map !== null ) {
  9447. if ( material.map.mapping instanceof THREE.UVMapping ) {
  9448. _uvs = element.uvs[ 0 ];
  9449. 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 );
  9450. }
  9451. } else if ( material.envMap !== null ) {
  9452. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  9453. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  9454. _uv1x = 0.5 * _vector3.x + 0.5;
  9455. _uv1y = 0.5 * _vector3.y + 0.5;
  9456. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  9457. _uv2x = 0.5 * _vector3.x + 0.5;
  9458. _uv2y = 0.5 * _vector3.y + 0.5;
  9459. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  9460. _uv3x = 0.5 * _vector3.x + 0.5;
  9461. _uv3y = 0.5 * _vector3.y + 0.5;
  9462. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9463. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  9464. }*/
  9465. } else {
  9466. _color.copy( material.color );
  9467. if ( material.vertexColors === THREE.FaceColors ) {
  9468. _color.multiply( element.color );
  9469. }
  9470. material.wireframe === true
  9471. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9472. : fillPath( _color );
  9473. }
  9474. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9475. _near = _camera.near;
  9476. _far = _camera.far;
  9477. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  9478. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  9479. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  9480. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9481. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9482. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9483. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9484. var normal;
  9485. if ( material.shading == THREE.FlatShading ) {
  9486. normal = element.normalModelView;
  9487. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9488. material.wireframe === true
  9489. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9490. : fillPath( _color );
  9491. } else if ( material.shading == THREE.SmoothShading ) {
  9492. normal = element.vertexNormalsModelView[ uv1 ];
  9493. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9494. normal = element.vertexNormalsModelView[ uv2 ];
  9495. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9496. normal = element.vertexNormalsModelView[ uv3 ];
  9497. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9498. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9499. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9500. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9501. }
  9502. }
  9503. }
  9504. //
  9505. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  9506. _context.beginPath();
  9507. _context.moveTo( x0, y0 );
  9508. _context.lineTo( x1, y1 );
  9509. _context.lineTo( x2, y2 );
  9510. _context.closePath();
  9511. }
  9512. function strokePath( color, linewidth, linecap, linejoin ) {
  9513. setLineWidth( linewidth );
  9514. setLineCap( linecap );
  9515. setLineJoin( linejoin );
  9516. setStrokeStyle( color.getStyle() );
  9517. _context.stroke();
  9518. _elemBox.expandByScalar( linewidth * 2 );
  9519. }
  9520. function fillPath( color ) {
  9521. setFillStyle( color.getStyle() );
  9522. _context.fill();
  9523. }
  9524. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  9525. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  9526. if ( texture.needsUpdate === true ) {
  9527. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  9528. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  9529. _patterns[ texture.id ] = _context.createPattern(
  9530. texture.image, repeatX === true && repeatY === true
  9531. ? 'repeat'
  9532. : repeatX === true && repeatY === false
  9533. ? 'repeat-x'
  9534. : repeatX === false && repeatY === true
  9535. ? 'repeat-y'
  9536. : 'no-repeat'
  9537. );
  9538. texture.needsUpdate = false;
  9539. }
  9540. _patterns[ texture.id ] === undefined
  9541. ? setFillStyle( 'rgba(0,0,0,1)' )
  9542. : setFillStyle( _patterns[ texture.id ] );
  9543. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9544. var a, b, c, d, e, f, det, idet,
  9545. offsetX = texture.offset.x / texture.repeat.x,
  9546. offsetY = texture.offset.y / texture.repeat.y,
  9547. width = texture.image.width * texture.repeat.x,
  9548. height = texture.image.height * texture.repeat.y;
  9549. u0 = ( u0 + offsetX ) * width;
  9550. v0 = ( 1.0 - v0 + offsetY ) * height;
  9551. u1 = ( u1 + offsetX ) * width;
  9552. v1 = ( 1.0 - v1 + offsetY ) * height;
  9553. u2 = ( u2 + offsetX ) * width;
  9554. v2 = ( 1.0 - v2 + offsetY ) * height;
  9555. x1 -= x0; y1 -= y0;
  9556. x2 -= x0; y2 -= y0;
  9557. u1 -= u0; v1 -= v0;
  9558. u2 -= u0; v2 -= v0;
  9559. det = u1 * v2 - u2 * v1;
  9560. if ( det === 0 ) {
  9561. if ( _imagedatas[ texture.id ] === undefined ) {
  9562. var canvas = document.createElement( 'canvas' )
  9563. canvas.width = texture.image.width;
  9564. canvas.height = texture.image.height;
  9565. var context = canvas.getContext( '2d' );
  9566. context.drawImage( texture.image, 0, 0 );
  9567. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  9568. }
  9569. var data = _imagedatas[ texture.id ];
  9570. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  9571. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  9572. fillPath( _color );
  9573. return;
  9574. }
  9575. idet = 1 / det;
  9576. a = ( v2 * x1 - v1 * x2 ) * idet;
  9577. b = ( v2 * y1 - v1 * y2 ) * idet;
  9578. c = ( u1 * x2 - u2 * x1 ) * idet;
  9579. d = ( u1 * y2 - u2 * y1 ) * idet;
  9580. e = x0 - a * u0 - c * v0;
  9581. f = y0 - b * u0 - d * v0;
  9582. _context.save();
  9583. _context.transform( a, b, c, d, e, f );
  9584. _context.fill();
  9585. _context.restore();
  9586. }
  9587. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  9588. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9589. var a, b, c, d, e, f, det, idet,
  9590. width = image.width - 1,
  9591. height = image.height - 1;
  9592. u0 *= width; v0 *= height;
  9593. u1 *= width; v1 *= height;
  9594. u2 *= width; v2 *= height;
  9595. x1 -= x0; y1 -= y0;
  9596. x2 -= x0; y2 -= y0;
  9597. u1 -= u0; v1 -= v0;
  9598. u2 -= u0; v2 -= v0;
  9599. det = u1 * v2 - u2 * v1;
  9600. idet = 1 / det;
  9601. a = ( v2 * x1 - v1 * x2 ) * idet;
  9602. b = ( v2 * y1 - v1 * y2 ) * idet;
  9603. c = ( u1 * x2 - u2 * x1 ) * idet;
  9604. d = ( u1 * y2 - u2 * y1 ) * idet;
  9605. e = x0 - a * u0 - c * v0;
  9606. f = y0 - b * u0 - d * v0;
  9607. _context.save();
  9608. _context.transform( a, b, c, d, e, f );
  9609. _context.clip();
  9610. _context.drawImage( image, 0, 0 );
  9611. _context.restore();
  9612. }
  9613. function getGradientTexture( color1, color2, color3, color4 ) {
  9614. // http://mrdoob.com/blog/post/710
  9615. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  9616. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  9617. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  9618. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  9619. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  9620. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  9621. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  9622. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  9623. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  9624. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  9625. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  9626. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  9627. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  9628. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  9629. return _gradientMap;
  9630. }
  9631. // Hide anti-alias gaps
  9632. function expand( v1, v2, pixels ) {
  9633. var x = v2.x - v1.x, y = v2.y - v1.y,
  9634. det = x * x + y * y, idet;
  9635. if ( det === 0 ) return;
  9636. idet = pixels / Math.sqrt( det );
  9637. x *= idet; y *= idet;
  9638. v2.x += x; v2.y += y;
  9639. v1.x -= x; v1.y -= y;
  9640. }
  9641. // Context cached methods.
  9642. function setOpacity( value ) {
  9643. if ( _contextGlobalAlpha !== value ) {
  9644. _context.globalAlpha = value;
  9645. _contextGlobalAlpha = value;
  9646. }
  9647. }
  9648. function setBlending( value ) {
  9649. if ( _contextGlobalCompositeOperation !== value ) {
  9650. if ( value === THREE.NormalBlending ) {
  9651. _context.globalCompositeOperation = 'source-over';
  9652. } else if ( value === THREE.AdditiveBlending ) {
  9653. _context.globalCompositeOperation = 'lighter';
  9654. } else if ( value === THREE.SubtractiveBlending ) {
  9655. _context.globalCompositeOperation = 'darker';
  9656. }
  9657. _contextGlobalCompositeOperation = value;
  9658. }
  9659. }
  9660. function setLineWidth( value ) {
  9661. if ( _contextLineWidth !== value ) {
  9662. _context.lineWidth = value;
  9663. _contextLineWidth = value;
  9664. }
  9665. }
  9666. function setLineCap( value ) {
  9667. // "butt", "round", "square"
  9668. if ( _contextLineCap !== value ) {
  9669. _context.lineCap = value;
  9670. _contextLineCap = value;
  9671. }
  9672. }
  9673. function setLineJoin( value ) {
  9674. // "round", "bevel", "miter"
  9675. if ( _contextLineJoin !== value ) {
  9676. _context.lineJoin = value;
  9677. _contextLineJoin = value;
  9678. }
  9679. }
  9680. function setStrokeStyle( value ) {
  9681. if ( _contextStrokeStyle !== value ) {
  9682. _context.strokeStyle = value;
  9683. _contextStrokeStyle = value;
  9684. }
  9685. }
  9686. function setFillStyle( value ) {
  9687. if ( _contextFillStyle !== value ) {
  9688. _context.fillStyle = value;
  9689. _contextFillStyle = value;
  9690. }
  9691. }
  9692. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  9693. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  9694. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  9695. _contextDashSize = dashSizeValue;
  9696. _contextGapSize = gapSizeValue;
  9697. }
  9698. }
  9699. };
  9700. /**
  9701. * @author alteredq / http://alteredqualia.com/
  9702. * @author mrdoob / http://mrdoob.com/
  9703. * @author mikael emtinger / http://gomo.se/
  9704. */
  9705. THREE.ShaderChunk = {
  9706. // FOG
  9707. fog_pars_fragment: [
  9708. "#ifdef USE_FOG",
  9709. "uniform vec3 fogColor;",
  9710. "#ifdef FOG_EXP2",
  9711. "uniform float fogDensity;",
  9712. "#else",
  9713. "uniform float fogNear;",
  9714. "uniform float fogFar;",
  9715. "#endif",
  9716. "#endif"
  9717. ].join("\n"),
  9718. fog_fragment: [
  9719. "#ifdef USE_FOG",
  9720. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9721. "#ifdef FOG_EXP2",
  9722. "const float LOG2 = 1.442695;",
  9723. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  9724. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  9725. "#else",
  9726. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  9727. "#endif",
  9728. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  9729. "#endif"
  9730. ].join("\n"),
  9731. // ENVIRONMENT MAP
  9732. envmap_pars_fragment: [
  9733. "#ifdef USE_ENVMAP",
  9734. "uniform float reflectivity;",
  9735. "uniform samplerCube envMap;",
  9736. "uniform float flipEnvMap;",
  9737. "uniform int combine;",
  9738. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9739. "uniform bool useRefract;",
  9740. "uniform float refractionRatio;",
  9741. "#else",
  9742. "varying vec3 vReflect;",
  9743. "#endif",
  9744. "#endif"
  9745. ].join("\n"),
  9746. envmap_fragment: [
  9747. "#ifdef USE_ENVMAP",
  9748. "vec3 reflectVec;",
  9749. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9750. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  9751. "if ( useRefract ) {",
  9752. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  9753. "} else { ",
  9754. "reflectVec = reflect( cameraToVertex, normal );",
  9755. "}",
  9756. "#else",
  9757. "reflectVec = vReflect;",
  9758. "#endif",
  9759. "#ifdef DOUBLE_SIDED",
  9760. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9761. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9762. "#else",
  9763. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9764. "#endif",
  9765. "#ifdef GAMMA_INPUT",
  9766. "cubeColor.xyz *= cubeColor.xyz;",
  9767. "#endif",
  9768. "if ( combine == 1 ) {",
  9769. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  9770. "} else if ( combine == 2 ) {",
  9771. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  9772. "} else {",
  9773. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  9774. "}",
  9775. "#endif"
  9776. ].join("\n"),
  9777. envmap_pars_vertex: [
  9778. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9779. "varying vec3 vReflect;",
  9780. "uniform float refractionRatio;",
  9781. "uniform bool useRefract;",
  9782. "#endif"
  9783. ].join("\n"),
  9784. worldpos_vertex : [
  9785. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  9786. "#ifdef USE_SKINNING",
  9787. "vec4 worldPosition = modelMatrix * skinned;",
  9788. "#endif",
  9789. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9790. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  9791. "#endif",
  9792. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9793. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  9794. "#endif",
  9795. "#endif"
  9796. ].join("\n"),
  9797. envmap_vertex : [
  9798. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9799. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  9800. "worldNormal = normalize( worldNormal );",
  9801. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  9802. "if ( useRefract ) {",
  9803. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  9804. "} else {",
  9805. "vReflect = reflect( cameraToVertex, worldNormal );",
  9806. "}",
  9807. "#endif"
  9808. ].join("\n"),
  9809. // COLOR MAP (particles)
  9810. map_particle_pars_fragment: [
  9811. "#ifdef USE_MAP",
  9812. "uniform sampler2D map;",
  9813. "#endif"
  9814. ].join("\n"),
  9815. map_particle_fragment: [
  9816. "#ifdef USE_MAP",
  9817. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  9818. "#endif"
  9819. ].join("\n"),
  9820. // COLOR MAP (triangles)
  9821. map_pars_vertex: [
  9822. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9823. "varying vec2 vUv;",
  9824. "uniform vec4 offsetRepeat;",
  9825. "#endif"
  9826. ].join("\n"),
  9827. map_pars_fragment: [
  9828. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9829. "varying vec2 vUv;",
  9830. "#endif",
  9831. "#ifdef USE_MAP",
  9832. "uniform sampler2D map;",
  9833. "#endif"
  9834. ].join("\n"),
  9835. map_vertex: [
  9836. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9837. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  9838. "#endif"
  9839. ].join("\n"),
  9840. map_fragment: [
  9841. "#ifdef USE_MAP",
  9842. "vec4 texelColor = texture2D( map, vUv );",
  9843. "#ifdef GAMMA_INPUT",
  9844. "texelColor.xyz *= texelColor.xyz;",
  9845. "#endif",
  9846. "gl_FragColor = gl_FragColor * texelColor;",
  9847. "#endif"
  9848. ].join("\n"),
  9849. // LIGHT MAP
  9850. lightmap_pars_fragment: [
  9851. "#ifdef USE_LIGHTMAP",
  9852. "varying vec2 vUv2;",
  9853. "uniform sampler2D lightMap;",
  9854. "#endif"
  9855. ].join("\n"),
  9856. lightmap_pars_vertex: [
  9857. "#ifdef USE_LIGHTMAP",
  9858. "varying vec2 vUv2;",
  9859. "#endif"
  9860. ].join("\n"),
  9861. lightmap_fragment: [
  9862. "#ifdef USE_LIGHTMAP",
  9863. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  9864. "#endif"
  9865. ].join("\n"),
  9866. lightmap_vertex: [
  9867. "#ifdef USE_LIGHTMAP",
  9868. "vUv2 = uv2;",
  9869. "#endif"
  9870. ].join("\n"),
  9871. // BUMP MAP
  9872. bumpmap_pars_fragment: [
  9873. "#ifdef USE_BUMPMAP",
  9874. "uniform sampler2D bumpMap;",
  9875. "uniform float bumpScale;",
  9876. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  9877. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  9878. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9879. "vec2 dHdxy_fwd() {",
  9880. "vec2 dSTdx = dFdx( vUv );",
  9881. "vec2 dSTdy = dFdy( vUv );",
  9882. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  9883. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  9884. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  9885. "return vec2( dBx, dBy );",
  9886. "}",
  9887. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  9888. "vec3 vSigmaX = dFdx( surf_pos );",
  9889. "vec3 vSigmaY = dFdy( surf_pos );",
  9890. "vec3 vN = surf_norm;", // normalized
  9891. "vec3 R1 = cross( vSigmaY, vN );",
  9892. "vec3 R2 = cross( vN, vSigmaX );",
  9893. "float fDet = dot( vSigmaX, R1 );",
  9894. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  9895. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  9896. "}",
  9897. "#endif"
  9898. ].join("\n"),
  9899. // NORMAL MAP
  9900. normalmap_pars_fragment: [
  9901. "#ifdef USE_NORMALMAP",
  9902. "uniform sampler2D normalMap;",
  9903. "uniform vec2 normalScale;",
  9904. // Per-Pixel Tangent Space Normal Mapping
  9905. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  9906. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  9907. "vec3 q0 = dFdx( eye_pos.xyz );",
  9908. "vec3 q1 = dFdy( eye_pos.xyz );",
  9909. "vec2 st0 = dFdx( vUv.st );",
  9910. "vec2 st1 = dFdy( vUv.st );",
  9911. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  9912. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  9913. "vec3 N = normalize( surf_norm );",
  9914. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  9915. "mapN.xy = normalScale * mapN.xy;",
  9916. "mat3 tsn = mat3( S, T, N );",
  9917. "return normalize( tsn * mapN );",
  9918. "}",
  9919. "#endif"
  9920. ].join("\n"),
  9921. // SPECULAR MAP
  9922. specularmap_pars_fragment: [
  9923. "#ifdef USE_SPECULARMAP",
  9924. "uniform sampler2D specularMap;",
  9925. "#endif"
  9926. ].join("\n"),
  9927. specularmap_fragment: [
  9928. "float specularStrength;",
  9929. "#ifdef USE_SPECULARMAP",
  9930. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  9931. "specularStrength = texelSpecular.r;",
  9932. "#else",
  9933. "specularStrength = 1.0;",
  9934. "#endif"
  9935. ].join("\n"),
  9936. // LIGHTS LAMBERT
  9937. lights_lambert_pars_vertex: [
  9938. "uniform vec3 ambient;",
  9939. "uniform vec3 diffuse;",
  9940. "uniform vec3 emissive;",
  9941. "uniform vec3 ambientLightColor;",
  9942. "#if MAX_DIR_LIGHTS > 0",
  9943. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9944. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9945. "#endif",
  9946. "#if MAX_HEMI_LIGHTS > 0",
  9947. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9948. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9949. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9950. "#endif",
  9951. "#if MAX_POINT_LIGHTS > 0",
  9952. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9953. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9954. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9955. "#endif",
  9956. "#if MAX_SPOT_LIGHTS > 0",
  9957. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9958. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9959. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9960. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9961. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9962. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9963. "#endif",
  9964. "#ifdef WRAP_AROUND",
  9965. "uniform vec3 wrapRGB;",
  9966. "#endif"
  9967. ].join("\n"),
  9968. lights_lambert_vertex: [
  9969. "vLightFront = vec3( 0.0 );",
  9970. "#ifdef DOUBLE_SIDED",
  9971. "vLightBack = vec3( 0.0 );",
  9972. "#endif",
  9973. "transformedNormal = normalize( transformedNormal );",
  9974. "#if MAX_DIR_LIGHTS > 0",
  9975. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9976. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9977. "vec3 dirVector = normalize( lDirection.xyz );",
  9978. "float dotProduct = dot( transformedNormal, dirVector );",
  9979. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9980. "#ifdef DOUBLE_SIDED",
  9981. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9982. "#ifdef WRAP_AROUND",
  9983. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9984. "#endif",
  9985. "#endif",
  9986. "#ifdef WRAP_AROUND",
  9987. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9988. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  9989. "#ifdef DOUBLE_SIDED",
  9990. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  9991. "#endif",
  9992. "#endif",
  9993. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  9994. "#ifdef DOUBLE_SIDED",
  9995. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  9996. "#endif",
  9997. "}",
  9998. "#endif",
  9999. "#if MAX_POINT_LIGHTS > 0",
  10000. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10001. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10002. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10003. "float lDistance = 1.0;",
  10004. "if ( pointLightDistance[ i ] > 0.0 )",
  10005. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10006. "lVector = normalize( lVector );",
  10007. "float dotProduct = dot( transformedNormal, lVector );",
  10008. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10009. "#ifdef DOUBLE_SIDED",
  10010. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10011. "#ifdef WRAP_AROUND",
  10012. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10013. "#endif",
  10014. "#endif",
  10015. "#ifdef WRAP_AROUND",
  10016. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10017. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  10018. "#ifdef DOUBLE_SIDED",
  10019. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  10020. "#endif",
  10021. "#endif",
  10022. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  10023. "#ifdef DOUBLE_SIDED",
  10024. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  10025. "#endif",
  10026. "}",
  10027. "#endif",
  10028. "#if MAX_SPOT_LIGHTS > 0",
  10029. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10030. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10031. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10032. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  10033. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10034. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10035. "float lDistance = 1.0;",
  10036. "if ( spotLightDistance[ i ] > 0.0 )",
  10037. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10038. "lVector = normalize( lVector );",
  10039. "float dotProduct = dot( transformedNormal, lVector );",
  10040. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10041. "#ifdef DOUBLE_SIDED",
  10042. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10043. "#ifdef WRAP_AROUND",
  10044. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10045. "#endif",
  10046. "#endif",
  10047. "#ifdef WRAP_AROUND",
  10048. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10049. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  10050. "#ifdef DOUBLE_SIDED",
  10051. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  10052. "#endif",
  10053. "#endif",
  10054. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  10055. "#ifdef DOUBLE_SIDED",
  10056. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  10057. "#endif",
  10058. "}",
  10059. "}",
  10060. "#endif",
  10061. "#if MAX_HEMI_LIGHTS > 0",
  10062. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10063. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10064. "vec3 lVector = normalize( lDirection.xyz );",
  10065. "float dotProduct = dot( transformedNormal, lVector );",
  10066. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10067. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  10068. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10069. "#ifdef DOUBLE_SIDED",
  10070. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  10071. "#endif",
  10072. "}",
  10073. "#endif",
  10074. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  10075. "#ifdef DOUBLE_SIDED",
  10076. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  10077. "#endif"
  10078. ].join("\n"),
  10079. // LIGHTS PHONG
  10080. lights_phong_pars_vertex: [
  10081. "#ifndef PHONG_PER_PIXEL",
  10082. "#if MAX_POINT_LIGHTS > 0",
  10083. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10084. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10085. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  10086. "#endif",
  10087. "#if MAX_SPOT_LIGHTS > 0",
  10088. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10089. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10090. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  10091. "#endif",
  10092. "#endif",
  10093. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10094. "varying vec3 vWorldPosition;",
  10095. "#endif"
  10096. ].join("\n"),
  10097. lights_phong_vertex: [
  10098. "#ifndef PHONG_PER_PIXEL",
  10099. "#if MAX_POINT_LIGHTS > 0",
  10100. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10101. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10102. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10103. "float lDistance = 1.0;",
  10104. "if ( pointLightDistance[ i ] > 0.0 )",
  10105. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10106. "vPointLight[ i ] = vec4( lVector, lDistance );",
  10107. "}",
  10108. "#endif",
  10109. "#if MAX_SPOT_LIGHTS > 0",
  10110. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10111. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10112. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10113. "float lDistance = 1.0;",
  10114. "if ( spotLightDistance[ i ] > 0.0 )",
  10115. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10116. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  10117. "}",
  10118. "#endif",
  10119. "#endif",
  10120. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10121. "vWorldPosition = worldPosition.xyz;",
  10122. "#endif"
  10123. ].join("\n"),
  10124. lights_phong_pars_fragment: [
  10125. "uniform vec3 ambientLightColor;",
  10126. "#if MAX_DIR_LIGHTS > 0",
  10127. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10128. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10129. "#endif",
  10130. "#if MAX_HEMI_LIGHTS > 0",
  10131. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10132. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10133. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10134. "#endif",
  10135. "#if MAX_POINT_LIGHTS > 0",
  10136. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10137. "#ifdef PHONG_PER_PIXEL",
  10138. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10139. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10140. "#else",
  10141. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  10142. "#endif",
  10143. "#endif",
  10144. "#if MAX_SPOT_LIGHTS > 0",
  10145. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10146. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10147. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10148. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10149. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10150. "#ifdef PHONG_PER_PIXEL",
  10151. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10152. "#else",
  10153. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  10154. "#endif",
  10155. "#endif",
  10156. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10157. "varying vec3 vWorldPosition;",
  10158. "#endif",
  10159. "#ifdef WRAP_AROUND",
  10160. "uniform vec3 wrapRGB;",
  10161. "#endif",
  10162. "varying vec3 vViewPosition;",
  10163. "varying vec3 vNormal;"
  10164. ].join("\n"),
  10165. lights_phong_fragment: [
  10166. "vec3 normal = normalize( vNormal );",
  10167. "vec3 viewPosition = normalize( vViewPosition );",
  10168. "#ifdef DOUBLE_SIDED",
  10169. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10170. "#endif",
  10171. "#ifdef USE_NORMALMAP",
  10172. "normal = perturbNormal2Arb( -vViewPosition, normal );",
  10173. "#elif defined( USE_BUMPMAP )",
  10174. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  10175. "#endif",
  10176. "#if MAX_POINT_LIGHTS > 0",
  10177. "vec3 pointDiffuse = vec3( 0.0 );",
  10178. "vec3 pointSpecular = vec3( 0.0 );",
  10179. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10180. "#ifdef PHONG_PER_PIXEL",
  10181. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10182. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10183. "float lDistance = 1.0;",
  10184. "if ( pointLightDistance[ i ] > 0.0 )",
  10185. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10186. "lVector = normalize( lVector );",
  10187. "#else",
  10188. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  10189. "float lDistance = vPointLight[ i ].w;",
  10190. "#endif",
  10191. // diffuse
  10192. "float dotProduct = dot( normal, lVector );",
  10193. "#ifdef WRAP_AROUND",
  10194. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  10195. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10196. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10197. "#else",
  10198. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  10199. "#endif",
  10200. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  10201. // specular
  10202. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  10203. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10204. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  10205. "#ifdef PHYSICALLY_BASED_SHADING",
  10206. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10207. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10208. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  10209. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  10210. "#else",
  10211. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  10212. "#endif",
  10213. "}",
  10214. "#endif",
  10215. "#if MAX_SPOT_LIGHTS > 0",
  10216. "vec3 spotDiffuse = vec3( 0.0 );",
  10217. "vec3 spotSpecular = vec3( 0.0 );",
  10218. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10219. "#ifdef PHONG_PER_PIXEL",
  10220. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10221. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10222. "float lDistance = 1.0;",
  10223. "if ( spotLightDistance[ i ] > 0.0 )",
  10224. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10225. "lVector = normalize( lVector );",
  10226. "#else",
  10227. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  10228. "float lDistance = vSpotLight[ i ].w;",
  10229. "#endif",
  10230. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10231. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10232. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10233. // diffuse
  10234. "float dotProduct = dot( normal, lVector );",
  10235. "#ifdef WRAP_AROUND",
  10236. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  10237. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10238. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10239. "#else",
  10240. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  10241. "#endif",
  10242. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  10243. // specular
  10244. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  10245. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10246. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  10247. "#ifdef PHYSICALLY_BASED_SHADING",
  10248. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10249. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10250. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  10251. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  10252. "#else",
  10253. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  10254. "#endif",
  10255. "}",
  10256. "}",
  10257. "#endif",
  10258. "#if MAX_DIR_LIGHTS > 0",
  10259. "vec3 dirDiffuse = vec3( 0.0 );",
  10260. "vec3 dirSpecular = vec3( 0.0 );" ,
  10261. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10262. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10263. "vec3 dirVector = normalize( lDirection.xyz );",
  10264. // diffuse
  10265. "float dotProduct = dot( normal, dirVector );",
  10266. "#ifdef WRAP_AROUND",
  10267. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  10268. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10269. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  10270. "#else",
  10271. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  10272. "#endif",
  10273. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  10274. // specular
  10275. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10276. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10277. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  10278. "#ifdef PHYSICALLY_BASED_SHADING",
  10279. /*
  10280. // fresnel term from skin shader
  10281. "const float F0 = 0.128;",
  10282. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  10283. "float exponential = pow( base, 5.0 );",
  10284. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  10285. */
  10286. /*
  10287. // fresnel term from fresnel shader
  10288. "const float mFresnelBias = 0.08;",
  10289. "const float mFresnelScale = 0.3;",
  10290. "const float mFresnelPower = 5.0;",
  10291. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  10292. */
  10293. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10294. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10295. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  10296. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10297. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10298. "#else",
  10299. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  10300. "#endif",
  10301. "}",
  10302. "#endif",
  10303. "#if MAX_HEMI_LIGHTS > 0",
  10304. "vec3 hemiDiffuse = vec3( 0.0 );",
  10305. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10306. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10307. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10308. "vec3 lVector = normalize( lDirection.xyz );",
  10309. // diffuse
  10310. "float dotProduct = dot( normal, lVector );",
  10311. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10312. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10313. "hemiDiffuse += diffuse * hemiColor;",
  10314. // specular (sky light)
  10315. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10316. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10317. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  10318. // specular (ground light)
  10319. "vec3 lVectorGround = -lVector;",
  10320. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10321. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10322. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  10323. "#ifdef PHYSICALLY_BASED_SHADING",
  10324. "float dotProductGround = dot( normal, lVectorGround );",
  10325. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10326. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10327. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10328. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10329. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10330. "#else",
  10331. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  10332. "#endif",
  10333. "}",
  10334. "#endif",
  10335. "vec3 totalDiffuse = vec3( 0.0 );",
  10336. "vec3 totalSpecular = vec3( 0.0 );",
  10337. "#if MAX_DIR_LIGHTS > 0",
  10338. "totalDiffuse += dirDiffuse;",
  10339. "totalSpecular += dirSpecular;",
  10340. "#endif",
  10341. "#if MAX_HEMI_LIGHTS > 0",
  10342. "totalDiffuse += hemiDiffuse;",
  10343. "totalSpecular += hemiSpecular;",
  10344. "#endif",
  10345. "#if MAX_POINT_LIGHTS > 0",
  10346. "totalDiffuse += pointDiffuse;",
  10347. "totalSpecular += pointSpecular;",
  10348. "#endif",
  10349. "#if MAX_SPOT_LIGHTS > 0",
  10350. "totalDiffuse += spotDiffuse;",
  10351. "totalSpecular += spotSpecular;",
  10352. "#endif",
  10353. "#ifdef METAL",
  10354. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  10355. "#else",
  10356. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  10357. "#endif"
  10358. ].join("\n"),
  10359. // VERTEX COLORS
  10360. color_pars_fragment: [
  10361. "#ifdef USE_COLOR",
  10362. "varying vec3 vColor;",
  10363. "#endif"
  10364. ].join("\n"),
  10365. color_fragment: [
  10366. "#ifdef USE_COLOR",
  10367. "gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );",
  10368. "#endif"
  10369. ].join("\n"),
  10370. color_pars_vertex: [
  10371. "#ifdef USE_COLOR",
  10372. "varying vec3 vColor;",
  10373. "#endif"
  10374. ].join("\n"),
  10375. color_vertex: [
  10376. "#ifdef USE_COLOR",
  10377. "#ifdef GAMMA_INPUT",
  10378. "vColor = color * color;",
  10379. "#else",
  10380. "vColor = color;",
  10381. "#endif",
  10382. "#endif"
  10383. ].join("\n"),
  10384. // SKINNING
  10385. skinning_pars_vertex: [
  10386. "#ifdef USE_SKINNING",
  10387. "#ifdef BONE_TEXTURE",
  10388. "uniform sampler2D boneTexture;",
  10389. "uniform int boneTextureWidth;",
  10390. "uniform int boneTextureHeight;",
  10391. "mat4 getBoneMatrix( const in float i ) {",
  10392. "float j = i * 4.0;",
  10393. "float x = mod( j, float( boneTextureWidth ) );",
  10394. "float y = floor( j / float( boneTextureWidth ) );",
  10395. "float dx = 1.0 / float( boneTextureWidth );",
  10396. "float dy = 1.0 / float( boneTextureHeight );",
  10397. "y = dy * ( y + 0.5 );",
  10398. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  10399. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  10400. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  10401. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  10402. "mat4 bone = mat4( v1, v2, v3, v4 );",
  10403. "return bone;",
  10404. "}",
  10405. "#else",
  10406. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  10407. "mat4 getBoneMatrix( const in float i ) {",
  10408. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  10409. "return bone;",
  10410. "}",
  10411. "#endif",
  10412. "#endif"
  10413. ].join("\n"),
  10414. skinbase_vertex: [
  10415. "#ifdef USE_SKINNING",
  10416. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  10417. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  10418. "#endif"
  10419. ].join("\n"),
  10420. skinning_vertex: [
  10421. "#ifdef USE_SKINNING",
  10422. "#ifdef USE_MORPHTARGETS",
  10423. "vec4 skinVertex = vec4( morphed, 1.0 );",
  10424. "#else",
  10425. "vec4 skinVertex = vec4( position, 1.0 );",
  10426. "#endif",
  10427. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10428. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10429. "#endif"
  10430. ].join("\n"),
  10431. // MORPHING
  10432. morphtarget_pars_vertex: [
  10433. "#ifdef USE_MORPHTARGETS",
  10434. "#ifndef USE_MORPHNORMALS",
  10435. "uniform float morphTargetInfluences[ 8 ];",
  10436. "#else",
  10437. "uniform float morphTargetInfluences[ 4 ];",
  10438. "#endif",
  10439. "#endif"
  10440. ].join("\n"),
  10441. morphtarget_vertex: [
  10442. "#ifdef USE_MORPHTARGETS",
  10443. "vec3 morphed = vec3( 0.0 );",
  10444. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  10445. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  10446. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  10447. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  10448. "#ifndef USE_MORPHNORMALS",
  10449. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  10450. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  10451. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  10452. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  10453. "#endif",
  10454. "morphed += position;",
  10455. "#endif"
  10456. ].join("\n"),
  10457. default_vertex : [
  10458. "vec4 mvPosition;",
  10459. "#ifdef USE_SKINNING",
  10460. "mvPosition = modelViewMatrix * skinned;",
  10461. "#endif",
  10462. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  10463. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  10464. "#endif",
  10465. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  10466. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10467. "#endif",
  10468. "gl_Position = projectionMatrix * mvPosition;"
  10469. ].join("\n"),
  10470. morphnormal_vertex: [
  10471. "#ifdef USE_MORPHNORMALS",
  10472. "vec3 morphedNormal = vec3( 0.0 );",
  10473. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  10474. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  10475. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  10476. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  10477. "morphedNormal += normal;",
  10478. "#endif"
  10479. ].join("\n"),
  10480. skinnormal_vertex: [
  10481. "#ifdef USE_SKINNING",
  10482. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  10483. "skinMatrix += skinWeight.y * boneMatY;",
  10484. "#ifdef USE_MORPHNORMALS",
  10485. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  10486. "#else",
  10487. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  10488. "#endif",
  10489. "#endif"
  10490. ].join("\n"),
  10491. defaultnormal_vertex: [
  10492. "vec3 objectNormal;",
  10493. "#ifdef USE_SKINNING",
  10494. "objectNormal = skinnedNormal.xyz;",
  10495. "#endif",
  10496. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  10497. "objectNormal = morphedNormal;",
  10498. "#endif",
  10499. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  10500. "objectNormal = normal;",
  10501. "#endif",
  10502. "#ifdef FLIP_SIDED",
  10503. "objectNormal = -objectNormal;",
  10504. "#endif",
  10505. "vec3 transformedNormal = normalMatrix * objectNormal;"
  10506. ].join("\n"),
  10507. // SHADOW MAP
  10508. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  10509. // http://spidergl.org/example.php?id=6
  10510. // http://fabiensanglard.net/shadowmapping
  10511. shadowmap_pars_fragment: [
  10512. "#ifdef USE_SHADOWMAP",
  10513. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  10514. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  10515. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  10516. "uniform float shadowBias[ MAX_SHADOWS ];",
  10517. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10518. "float unpackDepth( const in vec4 rgba_depth ) {",
  10519. "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 );",
  10520. "float depth = dot( rgba_depth, bit_shift );",
  10521. "return depth;",
  10522. "}",
  10523. "#endif"
  10524. ].join("\n"),
  10525. shadowmap_fragment: [
  10526. "#ifdef USE_SHADOWMAP",
  10527. "#ifdef SHADOWMAP_DEBUG",
  10528. "vec3 frustumColors[3];",
  10529. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  10530. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  10531. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  10532. "#endif",
  10533. "#ifdef SHADOWMAP_CASCADE",
  10534. "int inFrustumCount = 0;",
  10535. "#endif",
  10536. "float fDepth;",
  10537. "vec3 shadowColor = vec3( 1.0 );",
  10538. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10539. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  10540. // "if ( something && something )" breaks ATI OpenGL shader compiler
  10541. // "if ( all( something, something ) )" using this instead
  10542. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  10543. "bool inFrustum = all( inFrustumVec );",
  10544. // don't shadow pixels outside of light frustum
  10545. // use just first frustum (for cascades)
  10546. // don't shadow pixels behind far plane of light frustum
  10547. "#ifdef SHADOWMAP_CASCADE",
  10548. "inFrustumCount += int( inFrustum );",
  10549. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  10550. "#else",
  10551. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  10552. "#endif",
  10553. "bool frustumTest = all( frustumTestVec );",
  10554. "if ( frustumTest ) {",
  10555. "shadowCoord.z += shadowBias[ i ];",
  10556. "#if defined( SHADOWMAP_TYPE_PCF )",
  10557. // Percentage-close filtering
  10558. // (9 pixel kernel)
  10559. // http://fabiensanglard.net/shadowmappingPCF/
  10560. "float shadow = 0.0;",
  10561. /*
  10562. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  10563. // must enroll loop manually
  10564. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  10565. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  10566. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  10567. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  10568. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  10569. "float fDepth = unpackDepth( rgbaDepth );",
  10570. "if ( fDepth < shadowCoord.z )",
  10571. "shadow += 1.0;",
  10572. "}",
  10573. "shadow /= 9.0;",
  10574. */
  10575. "const float shadowDelta = 1.0 / 9.0;",
  10576. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10577. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10578. "float dx0 = -1.25 * xPixelOffset;",
  10579. "float dy0 = -1.25 * yPixelOffset;",
  10580. "float dx1 = 1.25 * xPixelOffset;",
  10581. "float dy1 = 1.25 * yPixelOffset;",
  10582. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10583. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10584. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10585. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10586. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10587. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10588. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10589. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10590. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10591. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10592. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10593. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10594. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10595. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10596. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10597. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10598. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10599. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10600. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10601. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  10602. // Percentage-close filtering
  10603. // (9 pixel kernel)
  10604. // http://fabiensanglard.net/shadowmappingPCF/
  10605. "float shadow = 0.0;",
  10606. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10607. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10608. "float dx0 = -1.0 * xPixelOffset;",
  10609. "float dy0 = -1.0 * yPixelOffset;",
  10610. "float dx1 = 1.0 * xPixelOffset;",
  10611. "float dy1 = 1.0 * yPixelOffset;",
  10612. "mat3 shadowKernel;",
  10613. "mat3 depthKernel;",
  10614. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10615. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10616. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10617. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10618. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10619. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10620. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10621. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10622. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10623. "vec3 shadowZ = vec3( shadowCoord.z );",
  10624. "shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  10625. "shadowKernel[0] *= vec3(0.25);",
  10626. "shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  10627. "shadowKernel[1] *= vec3(0.25);",
  10628. "shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  10629. "shadowKernel[2] *= vec3(0.25);",
  10630. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  10631. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  10632. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  10633. "vec4 shadowValues;",
  10634. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  10635. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  10636. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  10637. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  10638. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  10639. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10640. "#else",
  10641. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  10642. "float fDepth = unpackDepth( rgbaDepth );",
  10643. "if ( fDepth < shadowCoord.z )",
  10644. // spot with multiple shadows is darker
  10645. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  10646. // spot with multiple shadows has the same color as single shadow spot
  10647. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  10648. "#endif",
  10649. "}",
  10650. "#ifdef SHADOWMAP_DEBUG",
  10651. "#ifdef SHADOWMAP_CASCADE",
  10652. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  10653. "#else",
  10654. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  10655. "#endif",
  10656. "#endif",
  10657. "}",
  10658. "#ifdef GAMMA_OUTPUT",
  10659. "shadowColor *= shadowColor;",
  10660. "#endif",
  10661. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  10662. "#endif"
  10663. ].join("\n"),
  10664. shadowmap_pars_vertex: [
  10665. "#ifdef USE_SHADOWMAP",
  10666. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10667. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  10668. "#endif"
  10669. ].join("\n"),
  10670. shadowmap_vertex: [
  10671. "#ifdef USE_SHADOWMAP",
  10672. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10673. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10674. "}",
  10675. "#endif"
  10676. ].join("\n"),
  10677. // ALPHATEST
  10678. alphatest_fragment: [
  10679. "#ifdef ALPHATEST",
  10680. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  10681. "#endif"
  10682. ].join("\n"),
  10683. // LINEAR SPACE
  10684. linear_to_gamma_fragment: [
  10685. "#ifdef GAMMA_OUTPUT",
  10686. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  10687. "#endif"
  10688. ].join("\n")
  10689. };
  10690. THREE.UniformsUtils = {
  10691. merge: function ( uniforms ) {
  10692. var u, p, tmp, merged = {};
  10693. for ( u = 0; u < uniforms.length; u ++ ) {
  10694. tmp = this.clone( uniforms[ u ] );
  10695. for ( p in tmp ) {
  10696. merged[ p ] = tmp[ p ];
  10697. }
  10698. }
  10699. return merged;
  10700. },
  10701. clone: function ( uniforms_src ) {
  10702. var u, p, parameter, parameter_src, uniforms_dst = {};
  10703. for ( u in uniforms_src ) {
  10704. uniforms_dst[ u ] = {};
  10705. for ( p in uniforms_src[ u ] ) {
  10706. parameter_src = uniforms_src[ u ][ p ];
  10707. if ( parameter_src instanceof THREE.Color ||
  10708. parameter_src instanceof THREE.Vector2 ||
  10709. parameter_src instanceof THREE.Vector3 ||
  10710. parameter_src instanceof THREE.Vector4 ||
  10711. parameter_src instanceof THREE.Matrix4 ||
  10712. parameter_src instanceof THREE.Texture ) {
  10713. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10714. } else if ( parameter_src instanceof Array ) {
  10715. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10716. } else {
  10717. uniforms_dst[ u ][ p ] = parameter_src;
  10718. }
  10719. }
  10720. }
  10721. return uniforms_dst;
  10722. }
  10723. };
  10724. THREE.UniformsLib = {
  10725. common: {
  10726. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10727. "opacity" : { type: "f", value: 1.0 },
  10728. "map" : { type: "t", value: null },
  10729. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10730. "lightMap" : { type: "t", value: null },
  10731. "specularMap" : { type: "t", value: null },
  10732. "envMap" : { type: "t", value: null },
  10733. "flipEnvMap" : { type: "f", value: -1 },
  10734. "useRefract" : { type: "i", value: 0 },
  10735. "reflectivity" : { type: "f", value: 1.0 },
  10736. "refractionRatio" : { type: "f", value: 0.98 },
  10737. "combine" : { type: "i", value: 0 },
  10738. "morphTargetInfluences" : { type: "f", value: 0 }
  10739. },
  10740. bump: {
  10741. "bumpMap" : { type: "t", value: null },
  10742. "bumpScale" : { type: "f", value: 1 }
  10743. },
  10744. normalmap: {
  10745. "normalMap" : { type: "t", value: null },
  10746. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10747. },
  10748. fog : {
  10749. "fogDensity" : { type: "f", value: 0.00025 },
  10750. "fogNear" : { type: "f", value: 1 },
  10751. "fogFar" : { type: "f", value: 2000 },
  10752. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10753. },
  10754. lights: {
  10755. "ambientLightColor" : { type: "fv", value: [] },
  10756. "directionalLightDirection" : { type: "fv", value: [] },
  10757. "directionalLightColor" : { type: "fv", value: [] },
  10758. "hemisphereLightDirection" : { type: "fv", value: [] },
  10759. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10760. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10761. "pointLightColor" : { type: "fv", value: [] },
  10762. "pointLightPosition" : { type: "fv", value: [] },
  10763. "pointLightDistance" : { type: "fv1", value: [] },
  10764. "spotLightColor" : { type: "fv", value: [] },
  10765. "spotLightPosition" : { type: "fv", value: [] },
  10766. "spotLightDirection" : { type: "fv", value: [] },
  10767. "spotLightDistance" : { type: "fv1", value: [] },
  10768. "spotLightAngleCos" : { type: "fv1", value: [] },
  10769. "spotLightExponent" : { type: "fv1", value: [] }
  10770. },
  10771. particle: {
  10772. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10773. "opacity" : { type: "f", value: 1.0 },
  10774. "size" : { type: "f", value: 1.0 },
  10775. "scale" : { type: "f", value: 1.0 },
  10776. "map" : { type: "t", value: null },
  10777. "fogDensity" : { type: "f", value: 0.00025 },
  10778. "fogNear" : { type: "f", value: 1 },
  10779. "fogFar" : { type: "f", value: 2000 },
  10780. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10781. },
  10782. shadowmap: {
  10783. "shadowMap": { type: "tv", value: [] },
  10784. "shadowMapSize": { type: "v2v", value: [] },
  10785. "shadowBias" : { type: "fv1", value: [] },
  10786. "shadowDarkness": { type: "fv1", value: [] },
  10787. "shadowMatrix" : { type: "m4v", value: [] }
  10788. }
  10789. };
  10790. THREE.ShaderLib = {
  10791. 'basic': {
  10792. uniforms: THREE.UniformsUtils.merge( [
  10793. THREE.UniformsLib[ "common" ],
  10794. THREE.UniformsLib[ "fog" ],
  10795. THREE.UniformsLib[ "shadowmap" ]
  10796. ] ),
  10797. vertexShader: [
  10798. THREE.ShaderChunk[ "map_pars_vertex" ],
  10799. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10800. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10801. THREE.ShaderChunk[ "color_pars_vertex" ],
  10802. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10803. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10804. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10805. "void main() {",
  10806. THREE.ShaderChunk[ "map_vertex" ],
  10807. THREE.ShaderChunk[ "lightmap_vertex" ],
  10808. THREE.ShaderChunk[ "color_vertex" ],
  10809. THREE.ShaderChunk[ "skinbase_vertex" ],
  10810. "#ifdef USE_ENVMAP",
  10811. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10812. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10813. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10814. "#endif",
  10815. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10816. THREE.ShaderChunk[ "skinning_vertex" ],
  10817. THREE.ShaderChunk[ "default_vertex" ],
  10818. THREE.ShaderChunk[ "worldpos_vertex" ],
  10819. THREE.ShaderChunk[ "envmap_vertex" ],
  10820. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10821. "}"
  10822. ].join("\n"),
  10823. fragmentShader: [
  10824. "uniform vec3 diffuse;",
  10825. "uniform float opacity;",
  10826. THREE.ShaderChunk[ "color_pars_fragment" ],
  10827. THREE.ShaderChunk[ "map_pars_fragment" ],
  10828. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10829. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10830. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10831. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10832. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10833. "void main() {",
  10834. "gl_FragColor = vec4( diffuse, opacity );",
  10835. THREE.ShaderChunk[ "map_fragment" ],
  10836. THREE.ShaderChunk[ "alphatest_fragment" ],
  10837. THREE.ShaderChunk[ "specularmap_fragment" ],
  10838. THREE.ShaderChunk[ "lightmap_fragment" ],
  10839. THREE.ShaderChunk[ "color_fragment" ],
  10840. THREE.ShaderChunk[ "envmap_fragment" ],
  10841. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10842. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10843. THREE.ShaderChunk[ "fog_fragment" ],
  10844. "}"
  10845. ].join("\n")
  10846. },
  10847. 'lambert': {
  10848. uniforms: THREE.UniformsUtils.merge( [
  10849. THREE.UniformsLib[ "common" ],
  10850. THREE.UniformsLib[ "fog" ],
  10851. THREE.UniformsLib[ "lights" ],
  10852. THREE.UniformsLib[ "shadowmap" ],
  10853. {
  10854. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10855. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10856. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10857. }
  10858. ] ),
  10859. vertexShader: [
  10860. "#define LAMBERT",
  10861. "varying vec3 vLightFront;",
  10862. "#ifdef DOUBLE_SIDED",
  10863. "varying vec3 vLightBack;",
  10864. "#endif",
  10865. THREE.ShaderChunk[ "map_pars_vertex" ],
  10866. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10867. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10868. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10869. THREE.ShaderChunk[ "color_pars_vertex" ],
  10870. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10871. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10872. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10873. "void main() {",
  10874. THREE.ShaderChunk[ "map_vertex" ],
  10875. THREE.ShaderChunk[ "lightmap_vertex" ],
  10876. THREE.ShaderChunk[ "color_vertex" ],
  10877. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10878. THREE.ShaderChunk[ "skinbase_vertex" ],
  10879. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10880. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10881. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10882. THREE.ShaderChunk[ "skinning_vertex" ],
  10883. THREE.ShaderChunk[ "default_vertex" ],
  10884. THREE.ShaderChunk[ "worldpos_vertex" ],
  10885. THREE.ShaderChunk[ "envmap_vertex" ],
  10886. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10887. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10888. "}"
  10889. ].join("\n"),
  10890. fragmentShader: [
  10891. "uniform float opacity;",
  10892. "varying vec3 vLightFront;",
  10893. "#ifdef DOUBLE_SIDED",
  10894. "varying vec3 vLightBack;",
  10895. "#endif",
  10896. THREE.ShaderChunk[ "color_pars_fragment" ],
  10897. THREE.ShaderChunk[ "map_pars_fragment" ],
  10898. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10899. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10900. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10901. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10902. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10903. "void main() {",
  10904. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10905. THREE.ShaderChunk[ "map_fragment" ],
  10906. THREE.ShaderChunk[ "alphatest_fragment" ],
  10907. THREE.ShaderChunk[ "specularmap_fragment" ],
  10908. "#ifdef DOUBLE_SIDED",
  10909. //"float isFront = float( gl_FrontFacing );",
  10910. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10911. "if ( gl_FrontFacing )",
  10912. "gl_FragColor.xyz *= vLightFront;",
  10913. "else",
  10914. "gl_FragColor.xyz *= vLightBack;",
  10915. "#else",
  10916. "gl_FragColor.xyz *= vLightFront;",
  10917. "#endif",
  10918. THREE.ShaderChunk[ "lightmap_fragment" ],
  10919. THREE.ShaderChunk[ "color_fragment" ],
  10920. THREE.ShaderChunk[ "envmap_fragment" ],
  10921. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10922. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10923. THREE.ShaderChunk[ "fog_fragment" ],
  10924. "}"
  10925. ].join("\n")
  10926. },
  10927. 'phong': {
  10928. uniforms: THREE.UniformsUtils.merge( [
  10929. THREE.UniformsLib[ "common" ],
  10930. THREE.UniformsLib[ "bump" ],
  10931. THREE.UniformsLib[ "normalmap" ],
  10932. THREE.UniformsLib[ "fog" ],
  10933. THREE.UniformsLib[ "lights" ],
  10934. THREE.UniformsLib[ "shadowmap" ],
  10935. {
  10936. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10937. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10938. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10939. "shininess": { type: "f", value: 30 },
  10940. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10941. }
  10942. ] ),
  10943. vertexShader: [
  10944. "#define PHONG",
  10945. "varying vec3 vViewPosition;",
  10946. "varying vec3 vNormal;",
  10947. THREE.ShaderChunk[ "map_pars_vertex" ],
  10948. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10949. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10950. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10951. THREE.ShaderChunk[ "color_pars_vertex" ],
  10952. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10953. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10954. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10955. "void main() {",
  10956. THREE.ShaderChunk[ "map_vertex" ],
  10957. THREE.ShaderChunk[ "lightmap_vertex" ],
  10958. THREE.ShaderChunk[ "color_vertex" ],
  10959. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10960. THREE.ShaderChunk[ "skinbase_vertex" ],
  10961. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10962. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10963. "vNormal = normalize( transformedNormal );",
  10964. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10965. THREE.ShaderChunk[ "skinning_vertex" ],
  10966. THREE.ShaderChunk[ "default_vertex" ],
  10967. "vViewPosition = -mvPosition.xyz;",
  10968. THREE.ShaderChunk[ "worldpos_vertex" ],
  10969. THREE.ShaderChunk[ "envmap_vertex" ],
  10970. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10971. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10972. "}"
  10973. ].join("\n"),
  10974. fragmentShader: [
  10975. "uniform vec3 diffuse;",
  10976. "uniform float opacity;",
  10977. "uniform vec3 ambient;",
  10978. "uniform vec3 emissive;",
  10979. "uniform vec3 specular;",
  10980. "uniform float shininess;",
  10981. THREE.ShaderChunk[ "color_pars_fragment" ],
  10982. THREE.ShaderChunk[ "map_pars_fragment" ],
  10983. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10984. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10985. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10986. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10987. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10988. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10989. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10990. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10991. "void main() {",
  10992. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10993. THREE.ShaderChunk[ "map_fragment" ],
  10994. THREE.ShaderChunk[ "alphatest_fragment" ],
  10995. THREE.ShaderChunk[ "specularmap_fragment" ],
  10996. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10997. THREE.ShaderChunk[ "lightmap_fragment" ],
  10998. THREE.ShaderChunk[ "color_fragment" ],
  10999. THREE.ShaderChunk[ "envmap_fragment" ],
  11000. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11001. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11002. THREE.ShaderChunk[ "fog_fragment" ],
  11003. "}"
  11004. ].join("\n")
  11005. },
  11006. 'particle_basic': {
  11007. uniforms: THREE.UniformsUtils.merge( [
  11008. THREE.UniformsLib[ "particle" ],
  11009. THREE.UniformsLib[ "shadowmap" ]
  11010. ] ),
  11011. vertexShader: [
  11012. "uniform float size;",
  11013. "uniform float scale;",
  11014. THREE.ShaderChunk[ "color_pars_vertex" ],
  11015. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11016. "void main() {",
  11017. THREE.ShaderChunk[ "color_vertex" ],
  11018. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11019. "#ifdef USE_SIZEATTENUATION",
  11020. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  11021. "#else",
  11022. "gl_PointSize = size;",
  11023. "#endif",
  11024. "gl_Position = projectionMatrix * mvPosition;",
  11025. THREE.ShaderChunk[ "worldpos_vertex" ],
  11026. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11027. "}"
  11028. ].join("\n"),
  11029. fragmentShader: [
  11030. "uniform vec3 psColor;",
  11031. "uniform float opacity;",
  11032. THREE.ShaderChunk[ "color_pars_fragment" ],
  11033. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  11034. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11035. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11036. "void main() {",
  11037. "gl_FragColor = vec4( psColor, opacity );",
  11038. THREE.ShaderChunk[ "map_particle_fragment" ],
  11039. THREE.ShaderChunk[ "alphatest_fragment" ],
  11040. THREE.ShaderChunk[ "color_fragment" ],
  11041. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11042. THREE.ShaderChunk[ "fog_fragment" ],
  11043. "}"
  11044. ].join("\n")
  11045. },
  11046. 'dashed': {
  11047. uniforms: THREE.UniformsUtils.merge( [
  11048. THREE.UniformsLib[ "common" ],
  11049. THREE.UniformsLib[ "fog" ],
  11050. {
  11051. "scale": { type: "f", value: 1 },
  11052. "dashSize": { type: "f", value: 1 },
  11053. "totalSize": { type: "f", value: 2 }
  11054. }
  11055. ] ),
  11056. vertexShader: [
  11057. "uniform float scale;",
  11058. "attribute float lineDistance;",
  11059. "varying float vLineDistance;",
  11060. THREE.ShaderChunk[ "color_pars_vertex" ],
  11061. "void main() {",
  11062. THREE.ShaderChunk[ "color_vertex" ],
  11063. "vLineDistance = scale * lineDistance;",
  11064. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11065. "gl_Position = projectionMatrix * mvPosition;",
  11066. "}"
  11067. ].join("\n"),
  11068. fragmentShader: [
  11069. "uniform vec3 diffuse;",
  11070. "uniform float opacity;",
  11071. "uniform float dashSize;",
  11072. "uniform float totalSize;",
  11073. "varying float vLineDistance;",
  11074. THREE.ShaderChunk[ "color_pars_fragment" ],
  11075. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11076. "void main() {",
  11077. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  11078. "discard;",
  11079. "}",
  11080. "gl_FragColor = vec4( diffuse, opacity );",
  11081. THREE.ShaderChunk[ "color_fragment" ],
  11082. THREE.ShaderChunk[ "fog_fragment" ],
  11083. "}"
  11084. ].join("\n")
  11085. },
  11086. 'depth': {
  11087. uniforms: {
  11088. "mNear": { type: "f", value: 1.0 },
  11089. "mFar" : { type: "f", value: 2000.0 },
  11090. "opacity" : { type: "f", value: 1.0 }
  11091. },
  11092. vertexShader: [
  11093. "void main() {",
  11094. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11095. "}"
  11096. ].join("\n"),
  11097. fragmentShader: [
  11098. "uniform float mNear;",
  11099. "uniform float mFar;",
  11100. "uniform float opacity;",
  11101. "void main() {",
  11102. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  11103. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  11104. "gl_FragColor = vec4( vec3( color ), opacity );",
  11105. "}"
  11106. ].join("\n")
  11107. },
  11108. 'normal': {
  11109. uniforms: {
  11110. "opacity" : { type: "f", value: 1.0 }
  11111. },
  11112. vertexShader: [
  11113. "varying vec3 vNormal;",
  11114. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11115. "void main() {",
  11116. "vNormal = normalize( normalMatrix * normal );",
  11117. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11118. THREE.ShaderChunk[ "default_vertex" ],
  11119. "}"
  11120. ].join("\n"),
  11121. fragmentShader: [
  11122. "uniform float opacity;",
  11123. "varying vec3 vNormal;",
  11124. "void main() {",
  11125. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  11126. "}"
  11127. ].join("\n")
  11128. },
  11129. /* -------------------------------------------------------------------------
  11130. // Normal map shader
  11131. // - Blinn-Phong
  11132. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  11133. // - point and directional lights (use with "lights: true" material option)
  11134. ------------------------------------------------------------------------- */
  11135. 'normalmap' : {
  11136. uniforms: THREE.UniformsUtils.merge( [
  11137. THREE.UniformsLib[ "fog" ],
  11138. THREE.UniformsLib[ "lights" ],
  11139. THREE.UniformsLib[ "shadowmap" ],
  11140. {
  11141. "enableAO" : { type: "i", value: 0 },
  11142. "enableDiffuse" : { type: "i", value: 0 },
  11143. "enableSpecular" : { type: "i", value: 0 },
  11144. "enableReflection": { type: "i", value: 0 },
  11145. "enableDisplacement": { type: "i", value: 0 },
  11146. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  11147. "tDiffuse" : { type: "t", value: null },
  11148. "tCube" : { type: "t", value: null },
  11149. "tNormal" : { type: "t", value: null },
  11150. "tSpecular" : { type: "t", value: null },
  11151. "tAO" : { type: "t", value: null },
  11152. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11153. "uDisplacementBias": { type: "f", value: 0.0 },
  11154. "uDisplacementScale": { type: "f", value: 1.0 },
  11155. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11156. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  11157. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11158. "uShininess": { type: "f", value: 30 },
  11159. "uOpacity": { type: "f", value: 1 },
  11160. "useRefract": { type: "i", value: 0 },
  11161. "uRefractionRatio": { type: "f", value: 0.98 },
  11162. "uReflectivity": { type: "f", value: 0.5 },
  11163. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11164. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11165. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11166. }
  11167. ] ),
  11168. fragmentShader: [
  11169. "uniform vec3 uAmbientColor;",
  11170. "uniform vec3 uDiffuseColor;",
  11171. "uniform vec3 uSpecularColor;",
  11172. "uniform float uShininess;",
  11173. "uniform float uOpacity;",
  11174. "uniform bool enableDiffuse;",
  11175. "uniform bool enableSpecular;",
  11176. "uniform bool enableAO;",
  11177. "uniform bool enableReflection;",
  11178. "uniform sampler2D tDiffuse;",
  11179. "uniform sampler2D tNormal;",
  11180. "uniform sampler2D tSpecular;",
  11181. "uniform sampler2D tAO;",
  11182. "uniform samplerCube tCube;",
  11183. "uniform vec2 uNormalScale;",
  11184. "uniform bool useRefract;",
  11185. "uniform float uRefractionRatio;",
  11186. "uniform float uReflectivity;",
  11187. "varying vec3 vTangent;",
  11188. "varying vec3 vBinormal;",
  11189. "varying vec3 vNormal;",
  11190. "varying vec2 vUv;",
  11191. "uniform vec3 ambientLightColor;",
  11192. "#if MAX_DIR_LIGHTS > 0",
  11193. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11194. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11195. "#endif",
  11196. "#if MAX_HEMI_LIGHTS > 0",
  11197. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11198. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11199. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11200. "#endif",
  11201. "#if MAX_POINT_LIGHTS > 0",
  11202. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11203. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11204. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11205. "#endif",
  11206. "#if MAX_SPOT_LIGHTS > 0",
  11207. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11208. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11209. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11210. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11211. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11212. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11213. "#endif",
  11214. "#ifdef WRAP_AROUND",
  11215. "uniform vec3 wrapRGB;",
  11216. "#endif",
  11217. "varying vec3 vWorldPosition;",
  11218. "varying vec3 vViewPosition;",
  11219. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11220. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11221. "void main() {",
  11222. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  11223. "vec3 specularTex = vec3( 1.0 );",
  11224. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11225. "normalTex.xy *= uNormalScale;",
  11226. "normalTex = normalize( normalTex );",
  11227. "if( enableDiffuse ) {",
  11228. "#ifdef GAMMA_INPUT",
  11229. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  11230. "texelColor.xyz *= texelColor.xyz;",
  11231. "gl_FragColor = gl_FragColor * texelColor;",
  11232. "#else",
  11233. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11234. "#endif",
  11235. "}",
  11236. "if( enableAO ) {",
  11237. "#ifdef GAMMA_INPUT",
  11238. "vec4 aoColor = texture2D( tAO, vUv );",
  11239. "aoColor.xyz *= aoColor.xyz;",
  11240. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11241. "#else",
  11242. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11243. "#endif",
  11244. "}",
  11245. "if( enableSpecular )",
  11246. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  11247. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11248. "vec3 finalNormal = tsb * normalTex;",
  11249. "#ifdef FLIP_SIDED",
  11250. "finalNormal = -finalNormal;",
  11251. "#endif",
  11252. "vec3 normal = normalize( finalNormal );",
  11253. "vec3 viewPosition = normalize( vViewPosition );",
  11254. // point lights
  11255. "#if MAX_POINT_LIGHTS > 0",
  11256. "vec3 pointDiffuse = vec3( 0.0 );",
  11257. "vec3 pointSpecular = vec3( 0.0 );",
  11258. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11259. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11260. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  11261. "float pointDistance = 1.0;",
  11262. "if ( pointLightDistance[ i ] > 0.0 )",
  11263. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  11264. "pointVector = normalize( pointVector );",
  11265. // diffuse
  11266. "#ifdef WRAP_AROUND",
  11267. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11268. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11269. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11270. "#else",
  11271. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11272. "#endif",
  11273. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  11274. // specular
  11275. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11276. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11277. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  11278. "#ifdef PHYSICALLY_BASED_SHADING",
  11279. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11280. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11281. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11282. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11283. "#else",
  11284. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  11285. "#endif",
  11286. "}",
  11287. "#endif",
  11288. // spot lights
  11289. "#if MAX_SPOT_LIGHTS > 0",
  11290. "vec3 spotDiffuse = vec3( 0.0 );",
  11291. "vec3 spotSpecular = vec3( 0.0 );",
  11292. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11293. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11294. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  11295. "float spotDistance = 1.0;",
  11296. "if ( spotLightDistance[ i ] > 0.0 )",
  11297. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  11298. "spotVector = normalize( spotVector );",
  11299. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11300. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11301. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11302. // diffuse
  11303. "#ifdef WRAP_AROUND",
  11304. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  11305. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  11306. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11307. "#else",
  11308. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  11309. "#endif",
  11310. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  11311. // specular
  11312. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  11313. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11314. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  11315. "#ifdef PHYSICALLY_BASED_SHADING",
  11316. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11317. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11318. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  11319. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  11320. "#else",
  11321. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  11322. "#endif",
  11323. "}",
  11324. "}",
  11325. "#endif",
  11326. // directional lights
  11327. "#if MAX_DIR_LIGHTS > 0",
  11328. "vec3 dirDiffuse = vec3( 0.0 );",
  11329. "vec3 dirSpecular = vec3( 0.0 );",
  11330. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11331. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11332. "vec3 dirVector = normalize( lDirection.xyz );",
  11333. // diffuse
  11334. "#ifdef WRAP_AROUND",
  11335. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11336. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11337. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11338. "#else",
  11339. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11340. "#endif",
  11341. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  11342. // specular
  11343. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11344. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11345. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  11346. "#ifdef PHYSICALLY_BASED_SHADING",
  11347. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11348. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11349. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11350. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11351. "#else",
  11352. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  11353. "#endif",
  11354. "}",
  11355. "#endif",
  11356. // hemisphere lights
  11357. "#if MAX_HEMI_LIGHTS > 0",
  11358. "vec3 hemiDiffuse = vec3( 0.0 );",
  11359. "vec3 hemiSpecular = vec3( 0.0 );" ,
  11360. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11361. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11362. "vec3 lVector = normalize( lDirection.xyz );",
  11363. // diffuse
  11364. "float dotProduct = dot( normal, lVector );",
  11365. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11366. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11367. "hemiDiffuse += uDiffuseColor * hemiColor;",
  11368. // specular (sky light)
  11369. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11370. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11371. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  11372. // specular (ground light)
  11373. "vec3 lVectorGround = -lVector;",
  11374. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11375. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11376. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  11377. "#ifdef PHYSICALLY_BASED_SHADING",
  11378. "float dotProductGround = dot( normal, lVectorGround );",
  11379. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11380. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11381. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  11382. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  11383. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11384. "#else",
  11385. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  11386. "#endif",
  11387. "}",
  11388. "#endif",
  11389. // all lights contribution summation
  11390. "vec3 totalDiffuse = vec3( 0.0 );",
  11391. "vec3 totalSpecular = vec3( 0.0 );",
  11392. "#if MAX_DIR_LIGHTS > 0",
  11393. "totalDiffuse += dirDiffuse;",
  11394. "totalSpecular += dirSpecular;",
  11395. "#endif",
  11396. "#if MAX_HEMI_LIGHTS > 0",
  11397. "totalDiffuse += hemiDiffuse;",
  11398. "totalSpecular += hemiSpecular;",
  11399. "#endif",
  11400. "#if MAX_POINT_LIGHTS > 0",
  11401. "totalDiffuse += pointDiffuse;",
  11402. "totalSpecular += pointSpecular;",
  11403. "#endif",
  11404. "#if MAX_SPOT_LIGHTS > 0",
  11405. "totalDiffuse += spotDiffuse;",
  11406. "totalSpecular += spotSpecular;",
  11407. "#endif",
  11408. "#ifdef METAL",
  11409. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  11410. "#else",
  11411. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  11412. "#endif",
  11413. "if ( enableReflection ) {",
  11414. "vec3 vReflect;",
  11415. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  11416. "if ( useRefract ) {",
  11417. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  11418. "} else {",
  11419. "vReflect = reflect( cameraToVertex, normal );",
  11420. "}",
  11421. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11422. "#ifdef GAMMA_INPUT",
  11423. "cubeColor.xyz *= cubeColor.xyz;",
  11424. "#endif",
  11425. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  11426. "}",
  11427. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11428. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11429. THREE.ShaderChunk[ "fog_fragment" ],
  11430. "}"
  11431. ].join("\n"),
  11432. vertexShader: [
  11433. "attribute vec4 tangent;",
  11434. "uniform vec2 uOffset;",
  11435. "uniform vec2 uRepeat;",
  11436. "uniform bool enableDisplacement;",
  11437. "#ifdef VERTEX_TEXTURES",
  11438. "uniform sampler2D tDisplacement;",
  11439. "uniform float uDisplacementScale;",
  11440. "uniform float uDisplacementBias;",
  11441. "#endif",
  11442. "varying vec3 vTangent;",
  11443. "varying vec3 vBinormal;",
  11444. "varying vec3 vNormal;",
  11445. "varying vec2 vUv;",
  11446. "varying vec3 vWorldPosition;",
  11447. "varying vec3 vViewPosition;",
  11448. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11449. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11450. "void main() {",
  11451. THREE.ShaderChunk[ "skinbase_vertex" ],
  11452. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11453. // normal, tangent and binormal vectors
  11454. "#ifdef USE_SKINNING",
  11455. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  11456. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  11457. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  11458. "#else",
  11459. "vNormal = normalize( normalMatrix * normal );",
  11460. "vTangent = normalize( normalMatrix * tangent.xyz );",
  11461. "#endif",
  11462. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  11463. "vUv = uv * uRepeat + uOffset;",
  11464. // displacement mapping
  11465. "vec3 displacedPosition;",
  11466. "#ifdef VERTEX_TEXTURES",
  11467. "if ( enableDisplacement ) {",
  11468. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11469. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11470. "displacedPosition = position + normalize( normal ) * df;",
  11471. "} else {",
  11472. "#ifdef USE_SKINNING",
  11473. "vec4 skinVertex = vec4( position, 1.0 );",
  11474. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11475. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11476. "displacedPosition = skinned.xyz;",
  11477. "#else",
  11478. "displacedPosition = position;",
  11479. "#endif",
  11480. "}",
  11481. "#else",
  11482. "#ifdef USE_SKINNING",
  11483. "vec4 skinVertex = vec4( position, 1.0 );",
  11484. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11485. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11486. "displacedPosition = skinned.xyz;",
  11487. "#else",
  11488. "displacedPosition = position;",
  11489. "#endif",
  11490. "#endif",
  11491. //
  11492. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  11493. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  11494. "gl_Position = projectionMatrix * mvPosition;",
  11495. //
  11496. "vWorldPosition = worldPosition.xyz;",
  11497. "vViewPosition = -mvPosition.xyz;",
  11498. // shadows
  11499. "#ifdef USE_SHADOWMAP",
  11500. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11501. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11502. "}",
  11503. "#endif",
  11504. "}"
  11505. ].join("\n")
  11506. },
  11507. /* -------------------------------------------------------------------------
  11508. // Cube map shader
  11509. ------------------------------------------------------------------------- */
  11510. 'cube': {
  11511. uniforms: { "tCube": { type: "t", value: null },
  11512. "tFlip": { type: "f", value: -1 } },
  11513. vertexShader: [
  11514. "varying vec3 vWorldPosition;",
  11515. "void main() {",
  11516. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  11517. "vWorldPosition = worldPosition.xyz;",
  11518. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11519. "}"
  11520. ].join("\n"),
  11521. fragmentShader: [
  11522. "uniform samplerCube tCube;",
  11523. "uniform float tFlip;",
  11524. "varying vec3 vWorldPosition;",
  11525. "void main() {",
  11526. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11527. "}"
  11528. ].join("\n")
  11529. },
  11530. // Depth encoding into RGBA texture
  11531. // based on SpiderGL shadow map example
  11532. // http://spidergl.org/example.php?id=6
  11533. // originally from
  11534. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11535. // see also here:
  11536. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11537. 'depthRGBA': {
  11538. uniforms: {},
  11539. vertexShader: [
  11540. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11541. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11542. "void main() {",
  11543. THREE.ShaderChunk[ "skinbase_vertex" ],
  11544. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11545. THREE.ShaderChunk[ "skinning_vertex" ],
  11546. THREE.ShaderChunk[ "default_vertex" ],
  11547. "}"
  11548. ].join("\n"),
  11549. fragmentShader: [
  11550. "vec4 pack_depth( const in float depth ) {",
  11551. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11552. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11553. "vec4 res = fract( depth * bit_shift );",
  11554. "res -= res.xxyz * bit_mask;",
  11555. "return res;",
  11556. "}",
  11557. "void main() {",
  11558. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  11559. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  11560. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  11561. //"gl_FragData[ 0 ] = pack_depth( z );",
  11562. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  11563. "}"
  11564. ].join("\n")
  11565. }
  11566. };
  11567. /**
  11568. * @author supereggbert / http://www.paulbrunt.co.uk/
  11569. * @author mrdoob / http://mrdoob.com/
  11570. * @author alteredq / http://alteredqualia.com/
  11571. * @author szimek / https://github.com/szimek/
  11572. */
  11573. THREE.WebGLRenderer = function ( parameters ) {
  11574. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  11575. parameters = parameters || {};
  11576. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11577. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  11578. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  11579. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11580. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11581. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11582. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  11583. _clearColor = new THREE.Color( 0x000000 ),
  11584. _clearAlpha = 0;
  11585. // public properties
  11586. this.domElement = _canvas;
  11587. this.context = null;
  11588. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  11589. ? parameters.devicePixelRatio
  11590. : self.devicePixelRatio !== undefined
  11591. ? self.devicePixelRatio
  11592. : 1;
  11593. // clearing
  11594. this.autoClear = true;
  11595. this.autoClearColor = true;
  11596. this.autoClearDepth = true;
  11597. this.autoClearStencil = true;
  11598. // scene graph
  11599. this.sortObjects = true;
  11600. this.autoUpdateObjects = true;
  11601. // physically based shading
  11602. this.gammaInput = false;
  11603. this.gammaOutput = false;
  11604. this.physicallyBasedShading = false;
  11605. // shadow map
  11606. this.shadowMapEnabled = false;
  11607. this.shadowMapAutoUpdate = true;
  11608. this.shadowMapType = THREE.PCFShadowMap;
  11609. this.shadowMapCullFace = THREE.CullFaceFront;
  11610. this.shadowMapDebug = false;
  11611. this.shadowMapCascade = false;
  11612. // morphs
  11613. this.maxMorphTargets = 8;
  11614. this.maxMorphNormals = 4;
  11615. // flags
  11616. this.autoScaleCubemaps = true;
  11617. // custom render plugins
  11618. this.renderPluginsPre = [];
  11619. this.renderPluginsPost = [];
  11620. // info
  11621. this.info = {
  11622. memory: {
  11623. programs: 0,
  11624. geometries: 0,
  11625. textures: 0
  11626. },
  11627. render: {
  11628. calls: 0,
  11629. vertices: 0,
  11630. faces: 0,
  11631. points: 0
  11632. }
  11633. };
  11634. // internal properties
  11635. var _this = this,
  11636. _programs = [],
  11637. _programs_counter = 0,
  11638. // internal state cache
  11639. _currentProgram = null,
  11640. _currentFramebuffer = null,
  11641. _currentMaterialId = -1,
  11642. _currentGeometryGroupHash = null,
  11643. _currentCamera = null,
  11644. _geometryGroupCounter = 0,
  11645. _usedTextureUnits = 0,
  11646. // GL state cache
  11647. _oldDoubleSided = -1,
  11648. _oldFlipSided = -1,
  11649. _oldBlending = -1,
  11650. _oldBlendEquation = -1,
  11651. _oldBlendSrc = -1,
  11652. _oldBlendDst = -1,
  11653. _oldDepthTest = -1,
  11654. _oldDepthWrite = -1,
  11655. _oldPolygonOffset = null,
  11656. _oldPolygonOffsetFactor = null,
  11657. _oldPolygonOffsetUnits = null,
  11658. _oldLineWidth = null,
  11659. _viewportX = 0,
  11660. _viewportY = 0,
  11661. _viewportWidth = _canvas.width,
  11662. _viewportHeight = _canvas.height,
  11663. _currentWidth = 0,
  11664. _currentHeight = 0,
  11665. _enabledAttributes = {},
  11666. // frustum
  11667. _frustum = new THREE.Frustum(),
  11668. // camera matrices cache
  11669. _projScreenMatrix = new THREE.Matrix4(),
  11670. _projScreenMatrixPS = new THREE.Matrix4(),
  11671. _vector3 = new THREE.Vector3(),
  11672. // light arrays cache
  11673. _direction = new THREE.Vector3(),
  11674. _lightsNeedUpdate = true,
  11675. _lights = {
  11676. ambient: [ 0, 0, 0 ],
  11677. directional: { length: 0, colors: new Array(), positions: new Array() },
  11678. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  11679. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  11680. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  11681. };
  11682. // initialize
  11683. var _gl;
  11684. var _glExtensionTextureFloat;
  11685. var _glExtensionTextureFloatLinear;
  11686. var _glExtensionStandardDerivatives;
  11687. var _glExtensionTextureFilterAnisotropic;
  11688. var _glExtensionCompressedTextureS3TC;
  11689. initGL();
  11690. setDefaultGLState();
  11691. this.context = _gl;
  11692. // GPU capabilities
  11693. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  11694. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11695. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  11696. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11697. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  11698. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  11699. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  11700. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  11701. //
  11702. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  11703. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  11704. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  11705. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  11706. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  11707. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  11708. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  11709. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  11710. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  11711. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  11712. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  11713. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  11714. // clamp precision to maximum available
  11715. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  11716. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  11717. if ( _precision === "highp" && ! highpAvailable ) {
  11718. if ( mediumpAvailable ) {
  11719. _precision = "mediump";
  11720. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  11721. } else {
  11722. _precision = "lowp";
  11723. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  11724. }
  11725. }
  11726. if ( _precision === "mediump" && ! mediumpAvailable ) {
  11727. _precision = "lowp";
  11728. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  11729. }
  11730. // API
  11731. this.getContext = function () {
  11732. return _gl;
  11733. };
  11734. this.supportsVertexTextures = function () {
  11735. return _supportsVertexTextures;
  11736. };
  11737. this.supportsFloatTextures = function () {
  11738. return _glExtensionTextureFloat;
  11739. };
  11740. this.supportsStandardDerivatives = function () {
  11741. return _glExtensionStandardDerivatives;
  11742. };
  11743. this.supportsCompressedTextureS3TC = function () {
  11744. return _glExtensionCompressedTextureS3TC;
  11745. };
  11746. this.getMaxAnisotropy = function () {
  11747. return _maxAnisotropy;
  11748. };
  11749. this.getPrecision = function () {
  11750. return _precision;
  11751. };
  11752. this.setSize = function ( width, height, updateStyle ) {
  11753. _canvas.width = width * this.devicePixelRatio;
  11754. _canvas.height = height * this.devicePixelRatio;
  11755. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  11756. _canvas.style.width = width + 'px';
  11757. _canvas.style.height = height + 'px';
  11758. }
  11759. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  11760. };
  11761. this.setViewport = function ( x, y, width, height ) {
  11762. _viewportX = x !== undefined ? x : 0;
  11763. _viewportY = y !== undefined ? y : 0;
  11764. _viewportWidth = width !== undefined ? width : _canvas.width;
  11765. _viewportHeight = height !== undefined ? height : _canvas.height;
  11766. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11767. };
  11768. this.setScissor = function ( x, y, width, height ) {
  11769. _gl.scissor( x, y, width, height );
  11770. };
  11771. this.enableScissorTest = function ( enable ) {
  11772. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  11773. };
  11774. // Clearing
  11775. this.setClearColor = function ( color, alpha ) {
  11776. _clearColor.set( color );
  11777. _clearAlpha = alpha !== undefined ? alpha : 1;
  11778. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11779. };
  11780. this.setClearColorHex = function ( hex, alpha ) {
  11781. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  11782. this.setClearColor( hex, alpha );
  11783. };
  11784. this.getClearColor = function () {
  11785. return _clearColor;
  11786. };
  11787. this.getClearAlpha = function () {
  11788. return _clearAlpha;
  11789. };
  11790. this.clear = function ( color, depth, stencil ) {
  11791. var bits = 0;
  11792. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11793. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11794. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11795. _gl.clear( bits );
  11796. };
  11797. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11798. this.setRenderTarget( renderTarget );
  11799. this.clear( color, depth, stencil );
  11800. };
  11801. // Plugins
  11802. this.addPostPlugin = function ( plugin ) {
  11803. plugin.init( this );
  11804. this.renderPluginsPost.push( plugin );
  11805. };
  11806. this.addPrePlugin = function ( plugin ) {
  11807. plugin.init( this );
  11808. this.renderPluginsPre.push( plugin );
  11809. };
  11810. // Rendering
  11811. this.updateShadowMap = function ( scene, camera ) {
  11812. _currentProgram = null;
  11813. _oldBlending = -1;
  11814. _oldDepthTest = -1;
  11815. _oldDepthWrite = -1;
  11816. _currentGeometryGroupHash = -1;
  11817. _currentMaterialId = -1;
  11818. _lightsNeedUpdate = true;
  11819. _oldDoubleSided = -1;
  11820. _oldFlipSided = -1;
  11821. this.shadowMapPlugin.update( scene, camera );
  11822. };
  11823. // Internal functions
  11824. // Buffer allocation
  11825. function createParticleBuffers ( geometry ) {
  11826. geometry.__webglVertexBuffer = _gl.createBuffer();
  11827. geometry.__webglColorBuffer = _gl.createBuffer();
  11828. _this.info.memory.geometries ++;
  11829. };
  11830. function createLineBuffers ( geometry ) {
  11831. geometry.__webglVertexBuffer = _gl.createBuffer();
  11832. geometry.__webglColorBuffer = _gl.createBuffer();
  11833. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  11834. _this.info.memory.geometries ++;
  11835. };
  11836. function createMeshBuffers ( geometryGroup ) {
  11837. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  11838. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  11839. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  11840. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  11841. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  11842. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  11843. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  11844. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  11845. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  11846. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  11847. var m, ml;
  11848. if ( geometryGroup.numMorphTargets ) {
  11849. geometryGroup.__webglMorphTargetsBuffers = [];
  11850. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11851. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  11852. }
  11853. }
  11854. if ( geometryGroup.numMorphNormals ) {
  11855. geometryGroup.__webglMorphNormalsBuffers = [];
  11856. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11857. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  11858. }
  11859. }
  11860. _this.info.memory.geometries ++;
  11861. };
  11862. // Events
  11863. var onGeometryDispose = function ( event ) {
  11864. var geometry = event.target;
  11865. geometry.removeEventListener( 'dispose', onGeometryDispose );
  11866. deallocateGeometry( geometry );
  11867. };
  11868. var onTextureDispose = function ( event ) {
  11869. var texture = event.target;
  11870. texture.removeEventListener( 'dispose', onTextureDispose );
  11871. deallocateTexture( texture );
  11872. _this.info.memory.textures --;
  11873. };
  11874. var onRenderTargetDispose = function ( event ) {
  11875. var renderTarget = event.target;
  11876. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11877. deallocateRenderTarget( renderTarget );
  11878. _this.info.memory.textures --;
  11879. };
  11880. var onMaterialDispose = function ( event ) {
  11881. var material = event.target;
  11882. material.removeEventListener( 'dispose', onMaterialDispose );
  11883. deallocateMaterial( material );
  11884. };
  11885. // Buffer deallocation
  11886. var deleteBuffers = function ( geometry ) {
  11887. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11888. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  11889. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  11890. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  11891. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  11892. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  11893. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  11894. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  11895. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  11896. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  11897. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  11898. // custom attributes
  11899. if ( geometry.__webglCustomAttributesList !== undefined ) {
  11900. for ( var id in geometry.__webglCustomAttributesList ) {
  11901. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  11902. }
  11903. }
  11904. _this.info.memory.geometries --;
  11905. };
  11906. var deallocateGeometry = function ( geometry ) {
  11907. geometry.__webglInit = undefined;
  11908. if ( geometry instanceof THREE.BufferGeometry ) {
  11909. var attributes = geometry.attributes;
  11910. for ( var key in attributes ) {
  11911. if ( attributes[ key ].buffer !== undefined ) {
  11912. _gl.deleteBuffer( attributes[ key ].buffer );
  11913. }
  11914. }
  11915. _this.info.memory.geometries --;
  11916. } else {
  11917. if ( geometry.geometryGroups !== undefined ) {
  11918. for ( var g in geometry.geometryGroups ) {
  11919. var geometryGroup = geometry.geometryGroups[ g ];
  11920. if ( geometryGroup.numMorphTargets !== undefined ) {
  11921. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11922. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11923. }
  11924. }
  11925. if ( geometryGroup.numMorphNormals !== undefined ) {
  11926. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11927. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11928. }
  11929. }
  11930. deleteBuffers( geometryGroup );
  11931. }
  11932. } else {
  11933. deleteBuffers( geometry );
  11934. }
  11935. }
  11936. };
  11937. var deallocateTexture = function ( texture ) {
  11938. if ( texture.image && texture.image.__webglTextureCube ) {
  11939. // cube texture
  11940. _gl.deleteTexture( texture.image.__webglTextureCube );
  11941. } else {
  11942. // 2D texture
  11943. if ( ! texture.__webglInit ) return;
  11944. texture.__webglInit = false;
  11945. _gl.deleteTexture( texture.__webglTexture );
  11946. }
  11947. };
  11948. var deallocateRenderTarget = function ( renderTarget ) {
  11949. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  11950. _gl.deleteTexture( renderTarget.__webglTexture );
  11951. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  11952. for ( var i = 0; i < 6; i ++ ) {
  11953. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  11954. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  11955. }
  11956. } else {
  11957. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  11958. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  11959. }
  11960. };
  11961. var deallocateMaterial = function ( material ) {
  11962. var program = material.program;
  11963. if ( program === undefined ) return;
  11964. material.program = undefined;
  11965. // only deallocate GL program if this was the last use of shared program
  11966. // assumed there is only single copy of any program in the _programs list
  11967. // (that's how it's constructed)
  11968. var i, il, programInfo;
  11969. var deleteProgram = false;
  11970. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11971. programInfo = _programs[ i ];
  11972. if ( programInfo.program === program ) {
  11973. programInfo.usedTimes --;
  11974. if ( programInfo.usedTimes === 0 ) {
  11975. deleteProgram = true;
  11976. }
  11977. break;
  11978. }
  11979. }
  11980. if ( deleteProgram === true ) {
  11981. // avoid using array.splice, this is costlier than creating new array from scratch
  11982. var newPrograms = [];
  11983. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11984. programInfo = _programs[ i ];
  11985. if ( programInfo.program !== program ) {
  11986. newPrograms.push( programInfo );
  11987. }
  11988. }
  11989. _programs = newPrograms;
  11990. _gl.deleteProgram( program );
  11991. _this.info.memory.programs --;
  11992. }
  11993. };
  11994. // Buffer initialization
  11995. function initCustomAttributes ( geometry, object ) {
  11996. var nvertices = geometry.vertices.length;
  11997. var material = object.material;
  11998. if ( material.attributes ) {
  11999. if ( geometry.__webglCustomAttributesList === undefined ) {
  12000. geometry.__webglCustomAttributesList = [];
  12001. }
  12002. for ( var a in material.attributes ) {
  12003. var attribute = material.attributes[ a ];
  12004. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12005. attribute.__webglInitialized = true;
  12006. var size = 1; // "f" and "i"
  12007. if ( attribute.type === "v2" ) size = 2;
  12008. else if ( attribute.type === "v3" ) size = 3;
  12009. else if ( attribute.type === "v4" ) size = 4;
  12010. else if ( attribute.type === "c" ) size = 3;
  12011. attribute.size = size;
  12012. attribute.array = new Float32Array( nvertices * size );
  12013. attribute.buffer = _gl.createBuffer();
  12014. attribute.buffer.belongsToAttribute = a;
  12015. attribute.needsUpdate = true;
  12016. }
  12017. geometry.__webglCustomAttributesList.push( attribute );
  12018. }
  12019. }
  12020. };
  12021. function initParticleBuffers ( geometry, object ) {
  12022. var nvertices = geometry.vertices.length;
  12023. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12024. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12025. geometry.__sortArray = [];
  12026. geometry.__webglParticleCount = nvertices;
  12027. initCustomAttributes ( geometry, object );
  12028. };
  12029. function initLineBuffers ( geometry, object ) {
  12030. var nvertices = geometry.vertices.length;
  12031. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12032. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12033. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  12034. geometry.__webglLineCount = nvertices;
  12035. initCustomAttributes ( geometry, object );
  12036. };
  12037. function initMeshBuffers ( geometryGroup, object ) {
  12038. var geometry = object.geometry,
  12039. faces3 = geometryGroup.faces3,
  12040. nvertices = faces3.length * 3,
  12041. ntris = faces3.length * 1,
  12042. nlines = faces3.length * 3,
  12043. material = getBufferMaterial( object, geometryGroup ),
  12044. uvType = bufferGuessUVType( material ),
  12045. normalType = bufferGuessNormalType( material ),
  12046. vertexColorType = bufferGuessVertexColorType( material );
  12047. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  12048. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  12049. if ( normalType ) {
  12050. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  12051. }
  12052. if ( geometry.hasTangents ) {
  12053. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  12054. }
  12055. if ( vertexColorType ) {
  12056. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  12057. }
  12058. if ( uvType ) {
  12059. if ( geometry.faceVertexUvs.length > 0 ) {
  12060. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  12061. }
  12062. if ( geometry.faceVertexUvs.length > 1 ) {
  12063. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  12064. }
  12065. }
  12066. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  12067. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  12068. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  12069. }
  12070. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  12071. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  12072. var m, ml;
  12073. if ( geometryGroup.numMorphTargets ) {
  12074. geometryGroup.__morphTargetsArrays = [];
  12075. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12076. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  12077. }
  12078. }
  12079. if ( geometryGroup.numMorphNormals ) {
  12080. geometryGroup.__morphNormalsArrays = [];
  12081. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12082. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  12083. }
  12084. }
  12085. geometryGroup.__webglFaceCount = ntris * 3;
  12086. geometryGroup.__webglLineCount = nlines * 2;
  12087. // custom attributes
  12088. if ( material.attributes ) {
  12089. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  12090. geometryGroup.__webglCustomAttributesList = [];
  12091. }
  12092. for ( var a in material.attributes ) {
  12093. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  12094. // attribute buffers which are correctly indexed in the setMeshBuffers function
  12095. var originalAttribute = material.attributes[ a ];
  12096. var attribute = {};
  12097. for ( var property in originalAttribute ) {
  12098. attribute[ property ] = originalAttribute[ property ];
  12099. }
  12100. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12101. attribute.__webglInitialized = true;
  12102. var size = 1; // "f" and "i"
  12103. if( attribute.type === "v2" ) size = 2;
  12104. else if( attribute.type === "v3" ) size = 3;
  12105. else if( attribute.type === "v4" ) size = 4;
  12106. else if( attribute.type === "c" ) size = 3;
  12107. attribute.size = size;
  12108. attribute.array = new Float32Array( nvertices * size );
  12109. attribute.buffer = _gl.createBuffer();
  12110. attribute.buffer.belongsToAttribute = a;
  12111. originalAttribute.needsUpdate = true;
  12112. attribute.__original = originalAttribute;
  12113. }
  12114. geometryGroup.__webglCustomAttributesList.push( attribute );
  12115. }
  12116. }
  12117. geometryGroup.__inittedArrays = true;
  12118. };
  12119. function getBufferMaterial( object, geometryGroup ) {
  12120. return object.material instanceof THREE.MeshFaceMaterial
  12121. ? object.material.materials[ geometryGroup.materialIndex ]
  12122. : object.material;
  12123. };
  12124. function materialNeedsSmoothNormals ( material ) {
  12125. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  12126. };
  12127. function bufferGuessNormalType ( material ) {
  12128. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  12129. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  12130. return false;
  12131. }
  12132. if ( materialNeedsSmoothNormals( material ) ) {
  12133. return THREE.SmoothShading;
  12134. } else {
  12135. return THREE.FlatShading;
  12136. }
  12137. };
  12138. function bufferGuessVertexColorType( material ) {
  12139. if ( material.vertexColors ) {
  12140. return material.vertexColors;
  12141. }
  12142. return false;
  12143. };
  12144. function bufferGuessUVType( material ) {
  12145. // material must use some texture to require uvs
  12146. if ( material.map ||
  12147. material.lightMap ||
  12148. material.bumpMap ||
  12149. material.normalMap ||
  12150. material.specularMap ||
  12151. material instanceof THREE.ShaderMaterial ) {
  12152. return true;
  12153. }
  12154. return false;
  12155. };
  12156. //
  12157. function initDirectBuffers( geometry ) {
  12158. var a, attribute, type;
  12159. for ( a in geometry.attributes ) {
  12160. if ( a === "index" ) {
  12161. type = _gl.ELEMENT_ARRAY_BUFFER;
  12162. } else {
  12163. type = _gl.ARRAY_BUFFER;
  12164. }
  12165. attribute = geometry.attributes[ a ];
  12166. if ( attribute.numItems === undefined ) {
  12167. attribute.numItems = attribute.array.length;
  12168. }
  12169. attribute.buffer = _gl.createBuffer();
  12170. _gl.bindBuffer( type, attribute.buffer );
  12171. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  12172. }
  12173. };
  12174. // Buffer setting
  12175. function setParticleBuffers ( geometry, hint, object ) {
  12176. var v, c, vertex, offset, index, color,
  12177. vertices = geometry.vertices,
  12178. vl = vertices.length,
  12179. colors = geometry.colors,
  12180. cl = colors.length,
  12181. vertexArray = geometry.__vertexArray,
  12182. colorArray = geometry.__colorArray,
  12183. sortArray = geometry.__sortArray,
  12184. dirtyVertices = geometry.verticesNeedUpdate,
  12185. dirtyElements = geometry.elementsNeedUpdate,
  12186. dirtyColors = geometry.colorsNeedUpdate,
  12187. customAttributes = geometry.__webglCustomAttributesList,
  12188. i, il,
  12189. a, ca, cal, value,
  12190. customAttribute;
  12191. if ( object.sortParticles ) {
  12192. _projScreenMatrixPS.copy( _projScreenMatrix );
  12193. _projScreenMatrixPS.multiply( object.matrixWorld );
  12194. for ( v = 0; v < vl; v ++ ) {
  12195. vertex = vertices[ v ];
  12196. _vector3.copy( vertex );
  12197. _vector3.applyProjection( _projScreenMatrixPS );
  12198. sortArray[ v ] = [ _vector3.z, v ];
  12199. }
  12200. sortArray.sort( numericalSort );
  12201. for ( v = 0; v < vl; v ++ ) {
  12202. vertex = vertices[ sortArray[v][1] ];
  12203. offset = v * 3;
  12204. vertexArray[ offset ] = vertex.x;
  12205. vertexArray[ offset + 1 ] = vertex.y;
  12206. vertexArray[ offset + 2 ] = vertex.z;
  12207. }
  12208. for ( c = 0; c < cl; c ++ ) {
  12209. offset = c * 3;
  12210. color = colors[ sortArray[c][1] ];
  12211. colorArray[ offset ] = color.r;
  12212. colorArray[ offset + 1 ] = color.g;
  12213. colorArray[ offset + 2 ] = color.b;
  12214. }
  12215. if ( customAttributes ) {
  12216. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12217. customAttribute = customAttributes[ i ];
  12218. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  12219. offset = 0;
  12220. cal = customAttribute.value.length;
  12221. if ( customAttribute.size === 1 ) {
  12222. for ( ca = 0; ca < cal; ca ++ ) {
  12223. index = sortArray[ ca ][ 1 ];
  12224. customAttribute.array[ ca ] = customAttribute.value[ index ];
  12225. }
  12226. } else if ( customAttribute.size === 2 ) {
  12227. for ( ca = 0; ca < cal; ca ++ ) {
  12228. index = sortArray[ ca ][ 1 ];
  12229. value = customAttribute.value[ index ];
  12230. customAttribute.array[ offset ] = value.x;
  12231. customAttribute.array[ offset + 1 ] = value.y;
  12232. offset += 2;
  12233. }
  12234. } else if ( customAttribute.size === 3 ) {
  12235. if ( customAttribute.type === "c" ) {
  12236. for ( ca = 0; ca < cal; ca ++ ) {
  12237. index = sortArray[ ca ][ 1 ];
  12238. value = customAttribute.value[ index ];
  12239. customAttribute.array[ offset ] = value.r;
  12240. customAttribute.array[ offset + 1 ] = value.g;
  12241. customAttribute.array[ offset + 2 ] = value.b;
  12242. offset += 3;
  12243. }
  12244. } else {
  12245. for ( ca = 0; ca < cal; ca ++ ) {
  12246. index = sortArray[ ca ][ 1 ];
  12247. value = customAttribute.value[ index ];
  12248. customAttribute.array[ offset ] = value.x;
  12249. customAttribute.array[ offset + 1 ] = value.y;
  12250. customAttribute.array[ offset + 2 ] = value.z;
  12251. offset += 3;
  12252. }
  12253. }
  12254. } else if ( customAttribute.size === 4 ) {
  12255. for ( ca = 0; ca < cal; ca ++ ) {
  12256. index = sortArray[ ca ][ 1 ];
  12257. value = customAttribute.value[ index ];
  12258. customAttribute.array[ offset ] = value.x;
  12259. customAttribute.array[ offset + 1 ] = value.y;
  12260. customAttribute.array[ offset + 2 ] = value.z;
  12261. customAttribute.array[ offset + 3 ] = value.w;
  12262. offset += 4;
  12263. }
  12264. }
  12265. }
  12266. }
  12267. } else {
  12268. if ( dirtyVertices ) {
  12269. for ( v = 0; v < vl; v ++ ) {
  12270. vertex = vertices[ v ];
  12271. offset = v * 3;
  12272. vertexArray[ offset ] = vertex.x;
  12273. vertexArray[ offset + 1 ] = vertex.y;
  12274. vertexArray[ offset + 2 ] = vertex.z;
  12275. }
  12276. }
  12277. if ( dirtyColors ) {
  12278. for ( c = 0; c < cl; c ++ ) {
  12279. color = colors[ c ];
  12280. offset = c * 3;
  12281. colorArray[ offset ] = color.r;
  12282. colorArray[ offset + 1 ] = color.g;
  12283. colorArray[ offset + 2 ] = color.b;
  12284. }
  12285. }
  12286. if ( customAttributes ) {
  12287. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12288. customAttribute = customAttributes[ i ];
  12289. if ( customAttribute.needsUpdate &&
  12290. ( customAttribute.boundTo === undefined ||
  12291. customAttribute.boundTo === "vertices") ) {
  12292. cal = customAttribute.value.length;
  12293. offset = 0;
  12294. if ( customAttribute.size === 1 ) {
  12295. for ( ca = 0; ca < cal; ca ++ ) {
  12296. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12297. }
  12298. } else if ( customAttribute.size === 2 ) {
  12299. for ( ca = 0; ca < cal; ca ++ ) {
  12300. value = customAttribute.value[ ca ];
  12301. customAttribute.array[ offset ] = value.x;
  12302. customAttribute.array[ offset + 1 ] = value.y;
  12303. offset += 2;
  12304. }
  12305. } else if ( customAttribute.size === 3 ) {
  12306. if ( customAttribute.type === "c" ) {
  12307. for ( ca = 0; ca < cal; ca ++ ) {
  12308. value = customAttribute.value[ ca ];
  12309. customAttribute.array[ offset ] = value.r;
  12310. customAttribute.array[ offset + 1 ] = value.g;
  12311. customAttribute.array[ offset + 2 ] = value.b;
  12312. offset += 3;
  12313. }
  12314. } else {
  12315. for ( ca = 0; ca < cal; ca ++ ) {
  12316. value = customAttribute.value[ ca ];
  12317. customAttribute.array[ offset ] = value.x;
  12318. customAttribute.array[ offset + 1 ] = value.y;
  12319. customAttribute.array[ offset + 2 ] = value.z;
  12320. offset += 3;
  12321. }
  12322. }
  12323. } else if ( customAttribute.size === 4 ) {
  12324. for ( ca = 0; ca < cal; ca ++ ) {
  12325. value = customAttribute.value[ ca ];
  12326. customAttribute.array[ offset ] = value.x;
  12327. customAttribute.array[ offset + 1 ] = value.y;
  12328. customAttribute.array[ offset + 2 ] = value.z;
  12329. customAttribute.array[ offset + 3 ] = value.w;
  12330. offset += 4;
  12331. }
  12332. }
  12333. }
  12334. }
  12335. }
  12336. }
  12337. if ( dirtyVertices || object.sortParticles ) {
  12338. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12339. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12340. }
  12341. if ( dirtyColors || object.sortParticles ) {
  12342. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12343. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12344. }
  12345. if ( customAttributes ) {
  12346. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12347. customAttribute = customAttributes[ i ];
  12348. if ( customAttribute.needsUpdate || object.sortParticles ) {
  12349. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12350. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12351. }
  12352. }
  12353. }
  12354. };
  12355. function setLineBuffers ( geometry, hint ) {
  12356. var v, c, d, vertex, offset, color,
  12357. vertices = geometry.vertices,
  12358. colors = geometry.colors,
  12359. lineDistances = geometry.lineDistances,
  12360. vl = vertices.length,
  12361. cl = colors.length,
  12362. dl = lineDistances.length,
  12363. vertexArray = geometry.__vertexArray,
  12364. colorArray = geometry.__colorArray,
  12365. lineDistanceArray = geometry.__lineDistanceArray,
  12366. dirtyVertices = geometry.verticesNeedUpdate,
  12367. dirtyColors = geometry.colorsNeedUpdate,
  12368. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  12369. customAttributes = geometry.__webglCustomAttributesList,
  12370. i, il,
  12371. a, ca, cal, value,
  12372. customAttribute;
  12373. if ( dirtyVertices ) {
  12374. for ( v = 0; v < vl; v ++ ) {
  12375. vertex = vertices[ v ];
  12376. offset = v * 3;
  12377. vertexArray[ offset ] = vertex.x;
  12378. vertexArray[ offset + 1 ] = vertex.y;
  12379. vertexArray[ offset + 2 ] = vertex.z;
  12380. }
  12381. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12382. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12383. }
  12384. if ( dirtyColors ) {
  12385. for ( c = 0; c < cl; c ++ ) {
  12386. color = colors[ c ];
  12387. offset = c * 3;
  12388. colorArray[ offset ] = color.r;
  12389. colorArray[ offset + 1 ] = color.g;
  12390. colorArray[ offset + 2 ] = color.b;
  12391. }
  12392. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12393. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12394. }
  12395. if ( dirtyLineDistances ) {
  12396. for ( d = 0; d < dl; d ++ ) {
  12397. lineDistanceArray[ d ] = lineDistances[ d ];
  12398. }
  12399. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  12400. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  12401. }
  12402. if ( customAttributes ) {
  12403. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12404. customAttribute = customAttributes[ i ];
  12405. if ( customAttribute.needsUpdate &&
  12406. ( customAttribute.boundTo === undefined ||
  12407. customAttribute.boundTo === "vertices" ) ) {
  12408. offset = 0;
  12409. cal = customAttribute.value.length;
  12410. if ( customAttribute.size === 1 ) {
  12411. for ( ca = 0; ca < cal; ca ++ ) {
  12412. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12413. }
  12414. } else if ( customAttribute.size === 2 ) {
  12415. for ( ca = 0; ca < cal; ca ++ ) {
  12416. value = customAttribute.value[ ca ];
  12417. customAttribute.array[ offset ] = value.x;
  12418. customAttribute.array[ offset + 1 ] = value.y;
  12419. offset += 2;
  12420. }
  12421. } else if ( customAttribute.size === 3 ) {
  12422. if ( customAttribute.type === "c" ) {
  12423. for ( ca = 0; ca < cal; ca ++ ) {
  12424. value = customAttribute.value[ ca ];
  12425. customAttribute.array[ offset ] = value.r;
  12426. customAttribute.array[ offset + 1 ] = value.g;
  12427. customAttribute.array[ offset + 2 ] = value.b;
  12428. offset += 3;
  12429. }
  12430. } else {
  12431. for ( ca = 0; ca < cal; ca ++ ) {
  12432. value = customAttribute.value[ ca ];
  12433. customAttribute.array[ offset ] = value.x;
  12434. customAttribute.array[ offset + 1 ] = value.y;
  12435. customAttribute.array[ offset + 2 ] = value.z;
  12436. offset += 3;
  12437. }
  12438. }
  12439. } else if ( customAttribute.size === 4 ) {
  12440. for ( ca = 0; ca < cal; ca ++ ) {
  12441. value = customAttribute.value[ ca ];
  12442. customAttribute.array[ offset ] = value.x;
  12443. customAttribute.array[ offset + 1 ] = value.y;
  12444. customAttribute.array[ offset + 2 ] = value.z;
  12445. customAttribute.array[ offset + 3 ] = value.w;
  12446. offset += 4;
  12447. }
  12448. }
  12449. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12450. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12451. }
  12452. }
  12453. }
  12454. };
  12455. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12456. if ( ! geometryGroup.__inittedArrays ) {
  12457. return;
  12458. }
  12459. var normalType = bufferGuessNormalType( material ),
  12460. vertexColorType = bufferGuessVertexColorType( material ),
  12461. uvType = bufferGuessUVType( material ),
  12462. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12463. var f, fl, fi, face,
  12464. vertexNormals, faceNormal, normal,
  12465. vertexColors, faceColor,
  12466. vertexTangents,
  12467. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12468. c1, c2, c3, c4,
  12469. sw1, sw2, sw3, sw4,
  12470. si1, si2, si3, si4,
  12471. sa1, sa2, sa3, sa4,
  12472. sb1, sb2, sb3, sb4,
  12473. m, ml, i, il,
  12474. vn, uvi, uv2i,
  12475. vk, vkl, vka,
  12476. nka, chf, faceVertexNormals,
  12477. a,
  12478. vertexIndex = 0,
  12479. offset = 0,
  12480. offset_uv = 0,
  12481. offset_uv2 = 0,
  12482. offset_face = 0,
  12483. offset_normal = 0,
  12484. offset_tangent = 0,
  12485. offset_line = 0,
  12486. offset_color = 0,
  12487. offset_skin = 0,
  12488. offset_morphTarget = 0,
  12489. offset_custom = 0,
  12490. offset_customSrc = 0,
  12491. value,
  12492. vertexArray = geometryGroup.__vertexArray,
  12493. uvArray = geometryGroup.__uvArray,
  12494. uv2Array = geometryGroup.__uv2Array,
  12495. normalArray = geometryGroup.__normalArray,
  12496. tangentArray = geometryGroup.__tangentArray,
  12497. colorArray = geometryGroup.__colorArray,
  12498. skinIndexArray = geometryGroup.__skinIndexArray,
  12499. skinWeightArray = geometryGroup.__skinWeightArray,
  12500. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12501. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12502. customAttributes = geometryGroup.__webglCustomAttributesList,
  12503. customAttribute,
  12504. faceArray = geometryGroup.__faceArray,
  12505. lineArray = geometryGroup.__lineArray,
  12506. geometry = object.geometry, // this is shared for all chunks
  12507. dirtyVertices = geometry.verticesNeedUpdate,
  12508. dirtyElements = geometry.elementsNeedUpdate,
  12509. dirtyUvs = geometry.uvsNeedUpdate,
  12510. dirtyNormals = geometry.normalsNeedUpdate,
  12511. dirtyTangents = geometry.tangentsNeedUpdate,
  12512. dirtyColors = geometry.colorsNeedUpdate,
  12513. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12514. vertices = geometry.vertices,
  12515. chunk_faces3 = geometryGroup.faces3,
  12516. obj_faces = geometry.faces,
  12517. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12518. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12519. obj_colors = geometry.colors,
  12520. obj_skinIndices = geometry.skinIndices,
  12521. obj_skinWeights = geometry.skinWeights,
  12522. morphTargets = geometry.morphTargets,
  12523. morphNormals = geometry.morphNormals;
  12524. if ( dirtyVertices ) {
  12525. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12526. face = obj_faces[ chunk_faces3[ f ] ];
  12527. v1 = vertices[ face.a ];
  12528. v2 = vertices[ face.b ];
  12529. v3 = vertices[ face.c ];
  12530. vertexArray[ offset ] = v1.x;
  12531. vertexArray[ offset + 1 ] = v1.y;
  12532. vertexArray[ offset + 2 ] = v1.z;
  12533. vertexArray[ offset + 3 ] = v2.x;
  12534. vertexArray[ offset + 4 ] = v2.y;
  12535. vertexArray[ offset + 5 ] = v2.z;
  12536. vertexArray[ offset + 6 ] = v3.x;
  12537. vertexArray[ offset + 7 ] = v3.y;
  12538. vertexArray[ offset + 8 ] = v3.z;
  12539. offset += 9;
  12540. }
  12541. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12542. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12543. }
  12544. if ( dirtyMorphTargets ) {
  12545. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  12546. offset_morphTarget = 0;
  12547. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12548. chf = chunk_faces3[ f ];
  12549. face = obj_faces[ chf ];
  12550. // morph positions
  12551. v1 = morphTargets[ vk ].vertices[ face.a ];
  12552. v2 = morphTargets[ vk ].vertices[ face.b ];
  12553. v3 = morphTargets[ vk ].vertices[ face.c ];
  12554. vka = morphTargetsArrays[ vk ];
  12555. vka[ offset_morphTarget ] = v1.x;
  12556. vka[ offset_morphTarget + 1 ] = v1.y;
  12557. vka[ offset_morphTarget + 2 ] = v1.z;
  12558. vka[ offset_morphTarget + 3 ] = v2.x;
  12559. vka[ offset_morphTarget + 4 ] = v2.y;
  12560. vka[ offset_morphTarget + 5 ] = v2.z;
  12561. vka[ offset_morphTarget + 6 ] = v3.x;
  12562. vka[ offset_morphTarget + 7 ] = v3.y;
  12563. vka[ offset_morphTarget + 8 ] = v3.z;
  12564. // morph normals
  12565. if ( material.morphNormals ) {
  12566. if ( needsSmoothNormals ) {
  12567. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12568. n1 = faceVertexNormals.a;
  12569. n2 = faceVertexNormals.b;
  12570. n3 = faceVertexNormals.c;
  12571. } else {
  12572. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12573. n2 = n1;
  12574. n3 = n1;
  12575. }
  12576. nka = morphNormalsArrays[ vk ];
  12577. nka[ offset_morphTarget ] = n1.x;
  12578. nka[ offset_morphTarget + 1 ] = n1.y;
  12579. nka[ offset_morphTarget + 2 ] = n1.z;
  12580. nka[ offset_morphTarget + 3 ] = n2.x;
  12581. nka[ offset_morphTarget + 4 ] = n2.y;
  12582. nka[ offset_morphTarget + 5 ] = n2.z;
  12583. nka[ offset_morphTarget + 6 ] = n3.x;
  12584. nka[ offset_morphTarget + 7 ] = n3.y;
  12585. nka[ offset_morphTarget + 8 ] = n3.z;
  12586. }
  12587. //
  12588. offset_morphTarget += 9;
  12589. }
  12590. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  12591. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  12592. if ( material.morphNormals ) {
  12593. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  12594. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  12595. }
  12596. }
  12597. }
  12598. if ( obj_skinWeights.length ) {
  12599. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12600. face = obj_faces[ chunk_faces3[ f ] ];
  12601. // weights
  12602. sw1 = obj_skinWeights[ face.a ];
  12603. sw2 = obj_skinWeights[ face.b ];
  12604. sw3 = obj_skinWeights[ face.c ];
  12605. skinWeightArray[ offset_skin ] = sw1.x;
  12606. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12607. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12608. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12609. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12610. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12611. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12612. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12613. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12614. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12615. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12616. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12617. // indices
  12618. si1 = obj_skinIndices[ face.a ];
  12619. si2 = obj_skinIndices[ face.b ];
  12620. si3 = obj_skinIndices[ face.c ];
  12621. skinIndexArray[ offset_skin ] = si1.x;
  12622. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12623. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12624. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12625. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12626. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12627. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12628. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12629. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12630. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12631. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12632. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12633. offset_skin += 12;
  12634. }
  12635. if ( offset_skin > 0 ) {
  12636. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12637. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  12638. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12639. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  12640. }
  12641. }
  12642. if ( dirtyColors && vertexColorType ) {
  12643. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12644. face = obj_faces[ chunk_faces3[ f ] ];
  12645. vertexColors = face.vertexColors;
  12646. faceColor = face.color;
  12647. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  12648. c1 = vertexColors[ 0 ];
  12649. c2 = vertexColors[ 1 ];
  12650. c3 = vertexColors[ 2 ];
  12651. } else {
  12652. c1 = faceColor;
  12653. c2 = faceColor;
  12654. c3 = faceColor;
  12655. }
  12656. colorArray[ offset_color ] = c1.r;
  12657. colorArray[ offset_color + 1 ] = c1.g;
  12658. colorArray[ offset_color + 2 ] = c1.b;
  12659. colorArray[ offset_color + 3 ] = c2.r;
  12660. colorArray[ offset_color + 4 ] = c2.g;
  12661. colorArray[ offset_color + 5 ] = c2.b;
  12662. colorArray[ offset_color + 6 ] = c3.r;
  12663. colorArray[ offset_color + 7 ] = c3.g;
  12664. colorArray[ offset_color + 8 ] = c3.b;
  12665. offset_color += 9;
  12666. }
  12667. if ( offset_color > 0 ) {
  12668. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12669. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12670. }
  12671. }
  12672. if ( dirtyTangents && geometry.hasTangents ) {
  12673. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12674. face = obj_faces[ chunk_faces3[ f ] ];
  12675. vertexTangents = face.vertexTangents;
  12676. t1 = vertexTangents[ 0 ];
  12677. t2 = vertexTangents[ 1 ];
  12678. t3 = vertexTangents[ 2 ];
  12679. tangentArray[ offset_tangent ] = t1.x;
  12680. tangentArray[ offset_tangent + 1 ] = t1.y;
  12681. tangentArray[ offset_tangent + 2 ] = t1.z;
  12682. tangentArray[ offset_tangent + 3 ] = t1.w;
  12683. tangentArray[ offset_tangent + 4 ] = t2.x;
  12684. tangentArray[ offset_tangent + 5 ] = t2.y;
  12685. tangentArray[ offset_tangent + 6 ] = t2.z;
  12686. tangentArray[ offset_tangent + 7 ] = t2.w;
  12687. tangentArray[ offset_tangent + 8 ] = t3.x;
  12688. tangentArray[ offset_tangent + 9 ] = t3.y;
  12689. tangentArray[ offset_tangent + 10 ] = t3.z;
  12690. tangentArray[ offset_tangent + 11 ] = t3.w;
  12691. offset_tangent += 12;
  12692. }
  12693. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12694. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  12695. }
  12696. if ( dirtyNormals && normalType ) {
  12697. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12698. face = obj_faces[ chunk_faces3[ f ] ];
  12699. vertexNormals = face.vertexNormals;
  12700. faceNormal = face.normal;
  12701. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  12702. for ( i = 0; i < 3; i ++ ) {
  12703. vn = vertexNormals[ i ];
  12704. normalArray[ offset_normal ] = vn.x;
  12705. normalArray[ offset_normal + 1 ] = vn.y;
  12706. normalArray[ offset_normal + 2 ] = vn.z;
  12707. offset_normal += 3;
  12708. }
  12709. } else {
  12710. for ( i = 0; i < 3; i ++ ) {
  12711. normalArray[ offset_normal ] = faceNormal.x;
  12712. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12713. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12714. offset_normal += 3;
  12715. }
  12716. }
  12717. }
  12718. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12719. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12720. }
  12721. if ( dirtyUvs && obj_uvs && uvType ) {
  12722. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12723. fi = chunk_faces3[ f ];
  12724. uv = obj_uvs[ fi ];
  12725. if ( uv === undefined ) continue;
  12726. for ( i = 0; i < 3; i ++ ) {
  12727. uvi = uv[ i ];
  12728. uvArray[ offset_uv ] = uvi.x;
  12729. uvArray[ offset_uv + 1 ] = uvi.y;
  12730. offset_uv += 2;
  12731. }
  12732. }
  12733. if ( offset_uv > 0 ) {
  12734. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12735. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  12736. }
  12737. }
  12738. if ( dirtyUvs && obj_uvs2 && uvType ) {
  12739. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12740. fi = chunk_faces3[ f ];
  12741. uv2 = obj_uvs2[ fi ];
  12742. if ( uv2 === undefined ) continue;
  12743. for ( i = 0; i < 3; i ++ ) {
  12744. uv2i = uv2[ i ];
  12745. uv2Array[ offset_uv2 ] = uv2i.x;
  12746. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12747. offset_uv2 += 2;
  12748. }
  12749. }
  12750. if ( offset_uv2 > 0 ) {
  12751. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12752. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  12753. }
  12754. }
  12755. if ( dirtyElements ) {
  12756. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12757. faceArray[ offset_face ] = vertexIndex;
  12758. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12759. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  12760. offset_face += 3;
  12761. lineArray[ offset_line ] = vertexIndex;
  12762. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12763. lineArray[ offset_line + 2 ] = vertexIndex;
  12764. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  12765. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12766. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12767. offset_line += 6;
  12768. vertexIndex += 3;
  12769. }
  12770. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12771. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  12772. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12773. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  12774. }
  12775. if ( customAttributes ) {
  12776. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12777. customAttribute = customAttributes[ i ];
  12778. if ( ! customAttribute.__original.needsUpdate ) continue;
  12779. offset_custom = 0;
  12780. offset_customSrc = 0;
  12781. if ( customAttribute.size === 1 ) {
  12782. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12783. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12784. face = obj_faces[ chunk_faces3[ f ] ];
  12785. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12786. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12787. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12788. offset_custom += 3;
  12789. }
  12790. } else if ( customAttribute.boundTo === "faces" ) {
  12791. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12792. value = customAttribute.value[ chunk_faces3[ f ] ];
  12793. customAttribute.array[ offset_custom ] = value;
  12794. customAttribute.array[ offset_custom + 1 ] = value;
  12795. customAttribute.array[ offset_custom + 2 ] = value;
  12796. offset_custom += 3;
  12797. }
  12798. }
  12799. } else if ( customAttribute.size === 2 ) {
  12800. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12801. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12802. face = obj_faces[ chunk_faces3[ f ] ];
  12803. v1 = customAttribute.value[ face.a ];
  12804. v2 = customAttribute.value[ face.b ];
  12805. v3 = customAttribute.value[ face.c ];
  12806. customAttribute.array[ offset_custom ] = v1.x;
  12807. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12808. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12809. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12810. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12811. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12812. offset_custom += 6;
  12813. }
  12814. } else if ( customAttribute.boundTo === "faces" ) {
  12815. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12816. value = customAttribute.value[ chunk_faces3[ f ] ];
  12817. v1 = value;
  12818. v2 = value;
  12819. v3 = value;
  12820. customAttribute.array[ offset_custom ] = v1.x;
  12821. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12822. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12823. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12824. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12825. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12826. offset_custom += 6;
  12827. }
  12828. }
  12829. } else if ( customAttribute.size === 3 ) {
  12830. var pp;
  12831. if ( customAttribute.type === "c" ) {
  12832. pp = [ "r", "g", "b" ];
  12833. } else {
  12834. pp = [ "x", "y", "z" ];
  12835. }
  12836. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12837. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12838. face = obj_faces[ chunk_faces3[ f ] ];
  12839. v1 = customAttribute.value[ face.a ];
  12840. v2 = customAttribute.value[ face.b ];
  12841. v3 = customAttribute.value[ face.c ];
  12842. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12843. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12844. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12845. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12846. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12847. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12848. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12849. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12850. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12851. offset_custom += 9;
  12852. }
  12853. } else if ( customAttribute.boundTo === "faces" ) {
  12854. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12855. value = customAttribute.value[ chunk_faces3[ f ] ];
  12856. v1 = value;
  12857. v2 = value;
  12858. v3 = value;
  12859. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12860. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12861. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12862. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12863. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12864. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12865. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12866. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12867. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12868. offset_custom += 9;
  12869. }
  12870. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12871. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12872. value = customAttribute.value[ chunk_faces3[ f ] ];
  12873. v1 = value[ 0 ];
  12874. v2 = value[ 1 ];
  12875. v3 = value[ 2 ];
  12876. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12877. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12878. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12879. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12880. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12881. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12882. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12883. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12884. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12885. offset_custom += 9;
  12886. }
  12887. }
  12888. } else if ( customAttribute.size === 4 ) {
  12889. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12890. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12891. face = obj_faces[ chunk_faces3[ f ] ];
  12892. v1 = customAttribute.value[ face.a ];
  12893. v2 = customAttribute.value[ face.b ];
  12894. v3 = customAttribute.value[ face.c ];
  12895. customAttribute.array[ offset_custom ] = v1.x;
  12896. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12897. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12898. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12899. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12900. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12901. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12902. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12903. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12904. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12905. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12906. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12907. offset_custom += 12;
  12908. }
  12909. } else if ( customAttribute.boundTo === "faces" ) {
  12910. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12911. value = customAttribute.value[ chunk_faces3[ f ] ];
  12912. v1 = value;
  12913. v2 = value;
  12914. v3 = value;
  12915. customAttribute.array[ offset_custom ] = v1.x;
  12916. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12917. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12918. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12919. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12920. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12921. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12922. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12923. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12924. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12925. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12926. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12927. offset_custom += 12;
  12928. }
  12929. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12930. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12931. value = customAttribute.value[ chunk_faces3[ f ] ];
  12932. v1 = value[ 0 ];
  12933. v2 = value[ 1 ];
  12934. v3 = value[ 2 ];
  12935. customAttribute.array[ offset_custom ] = v1.x;
  12936. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12937. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12938. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12939. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12940. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12941. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12942. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12943. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12944. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12945. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12946. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12947. offset_custom += 12;
  12948. }
  12949. }
  12950. }
  12951. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12952. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12953. }
  12954. }
  12955. if ( dispose ) {
  12956. delete geometryGroup.__inittedArrays;
  12957. delete geometryGroup.__colorArray;
  12958. delete geometryGroup.__normalArray;
  12959. delete geometryGroup.__tangentArray;
  12960. delete geometryGroup.__uvArray;
  12961. delete geometryGroup.__uv2Array;
  12962. delete geometryGroup.__faceArray;
  12963. delete geometryGroup.__vertexArray;
  12964. delete geometryGroup.__lineArray;
  12965. delete geometryGroup.__skinIndexArray;
  12966. delete geometryGroup.__skinWeightArray;
  12967. }
  12968. };
  12969. function setDirectBuffers ( geometry, hint, dispose ) {
  12970. var attributes = geometry.attributes;
  12971. var attributeName, attributeItem;
  12972. for ( attributeName in attributes ) {
  12973. attributeItem = attributes[ attributeName ];
  12974. if ( attributeItem.needsUpdate ) {
  12975. if ( attributeName === 'index' ) {
  12976. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  12977. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  12978. } else {
  12979. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  12980. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  12981. }
  12982. attributeItem.needsUpdate = false;
  12983. }
  12984. if ( dispose && ! attributeItem.dynamic ) {
  12985. attributeItem.array = null;
  12986. }
  12987. }
  12988. };
  12989. // Buffer rendering
  12990. this.renderBufferImmediate = function ( object, program, material ) {
  12991. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  12992. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  12993. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  12994. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  12995. if ( object.hasPositions ) {
  12996. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  12997. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12998. _gl.enableVertexAttribArray( program.attributes.position );
  12999. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13000. }
  13001. if ( object.hasNormals ) {
  13002. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  13003. if ( material.shading === THREE.FlatShading ) {
  13004. var nx, ny, nz,
  13005. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  13006. normalArray,
  13007. i, il = object.count * 3;
  13008. for( i = 0; i < il; i += 9 ) {
  13009. normalArray = object.normalArray;
  13010. nax = normalArray[ i ];
  13011. nay = normalArray[ i + 1 ];
  13012. naz = normalArray[ i + 2 ];
  13013. nbx = normalArray[ i + 3 ];
  13014. nby = normalArray[ i + 4 ];
  13015. nbz = normalArray[ i + 5 ];
  13016. ncx = normalArray[ i + 6 ];
  13017. ncy = normalArray[ i + 7 ];
  13018. ncz = normalArray[ i + 8 ];
  13019. nx = ( nax + nbx + ncx ) / 3;
  13020. ny = ( nay + nby + ncy ) / 3;
  13021. nz = ( naz + nbz + ncz ) / 3;
  13022. normalArray[ i ] = nx;
  13023. normalArray[ i + 1 ] = ny;
  13024. normalArray[ i + 2 ] = nz;
  13025. normalArray[ i + 3 ] = nx;
  13026. normalArray[ i + 4 ] = ny;
  13027. normalArray[ i + 5 ] = nz;
  13028. normalArray[ i + 6 ] = nx;
  13029. normalArray[ i + 7 ] = ny;
  13030. normalArray[ i + 8 ] = nz;
  13031. }
  13032. }
  13033. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13034. _gl.enableVertexAttribArray( program.attributes.normal );
  13035. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13036. }
  13037. if ( object.hasUvs && material.map ) {
  13038. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13039. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13040. _gl.enableVertexAttribArray( program.attributes.uv );
  13041. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13042. }
  13043. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13044. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13045. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13046. _gl.enableVertexAttribArray( program.attributes.color );
  13047. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13048. }
  13049. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13050. object.count = 0;
  13051. };
  13052. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13053. if ( material.visible === false ) return;
  13054. var linewidth, a, attribute;
  13055. var attributeItem, attributeName, attributePointer, attributeSize;
  13056. var program = setProgram( camera, lights, fog, material, object );
  13057. var programAttributes = program.attributes;
  13058. var geometryAttributes = geometry.attributes;
  13059. var updateBuffers = false,
  13060. wireframeBit = material.wireframe ? 1 : 0,
  13061. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13062. if ( geometryHash !== _currentGeometryGroupHash ) {
  13063. _currentGeometryGroupHash = geometryHash;
  13064. updateBuffers = true;
  13065. }
  13066. if ( updateBuffers ) {
  13067. disableAttributes();
  13068. }
  13069. // render mesh
  13070. if ( object instanceof THREE.Mesh ) {
  13071. var index = geometryAttributes[ "index" ];
  13072. // indexed triangles
  13073. if ( index ) {
  13074. var offsets = geometry.offsets;
  13075. // if there is more than 1 chunk
  13076. // must set attribute pointers to use new offsets for each chunk
  13077. // even if geometry and materials didn't change
  13078. if ( offsets.length > 1 ) updateBuffers = true;
  13079. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13080. var startIndex = offsets[ i ].index;
  13081. if ( updateBuffers ) {
  13082. for ( attributeName in programAttributes ) {
  13083. attributePointer = programAttributes[ attributeName ];
  13084. attributeItem = geometryAttributes[ attributeName ];
  13085. if ( attributePointer >= 0 ) {
  13086. if ( attributeItem ) {
  13087. attributeSize = attributeItem.itemSize;
  13088. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13089. enableAttribute( attributePointer );
  13090. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13091. } else if ( material.defaultAttributeValues ) {
  13092. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13093. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13094. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13095. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13096. }
  13097. }
  13098. }
  13099. }
  13100. // indices
  13101. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13102. }
  13103. // render indexed triangles
  13104. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  13105. _this.info.render.calls ++;
  13106. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13107. _this.info.render.faces += offsets[ i ].count / 3;
  13108. }
  13109. // non-indexed triangles
  13110. } else {
  13111. if ( updateBuffers ) {
  13112. for ( attributeName in programAttributes ) {
  13113. if ( attributeName === 'index') continue;
  13114. attributePointer = programAttributes[ attributeName ];
  13115. attributeItem = geometryAttributes[ attributeName ];
  13116. if ( attributePointer >= 0 ) {
  13117. if ( attributeItem ) {
  13118. attributeSize = attributeItem.itemSize;
  13119. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13120. enableAttribute( attributePointer );
  13121. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13122. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13123. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13124. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13125. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13126. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13127. }
  13128. }
  13129. }
  13130. }
  13131. }
  13132. var position = geometry.attributes[ "position" ];
  13133. // render non-indexed triangles
  13134. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  13135. _this.info.render.calls ++;
  13136. _this.info.render.vertices += position.numItems / 3;
  13137. _this.info.render.faces += position.numItems / 3 / 3;
  13138. }
  13139. // render particles
  13140. } else if ( object instanceof THREE.ParticleSystem ) {
  13141. if ( updateBuffers ) {
  13142. for ( attributeName in programAttributes ) {
  13143. attributePointer = programAttributes[ attributeName ];
  13144. attributeItem = geometryAttributes[ attributeName ];
  13145. if ( attributePointer >= 0 ) {
  13146. if ( attributeItem ) {
  13147. attributeSize = attributeItem.itemSize;
  13148. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13149. enableAttribute( attributePointer );
  13150. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13151. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13152. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13153. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13154. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13155. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13156. }
  13157. }
  13158. }
  13159. }
  13160. var position = geometryAttributes[ "position" ];
  13161. // render particles
  13162. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  13163. _this.info.render.calls ++;
  13164. _this.info.render.points += position.numItems / 3;
  13165. }
  13166. } else if ( object instanceof THREE.Line ) {
  13167. if ( updateBuffers ) {
  13168. for ( attributeName in programAttributes ) {
  13169. attributePointer = programAttributes[ attributeName ];
  13170. attributeItem = geometryAttributes[ attributeName ];
  13171. if ( attributePointer >= 0 ) {
  13172. if ( attributeItem ) {
  13173. attributeSize = attributeItem.itemSize;
  13174. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13175. enableAttribute( attributePointer );
  13176. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13177. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13178. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13179. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13180. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13181. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13182. }
  13183. }
  13184. }
  13185. }
  13186. // render lines
  13187. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13188. setLineWidth( material.linewidth );
  13189. var position = geometryAttributes[ "position" ];
  13190. _gl.drawArrays( primitives, 0, position.numItems / 3 );
  13191. _this.info.render.calls ++;
  13192. _this.info.render.points += position.numItems;
  13193. }
  13194. }
  13195. };
  13196. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13197. if ( material.visible === false ) return;
  13198. var linewidth, a, attribute, i, il;
  13199. var program = setProgram( camera, lights, fog, material, object );
  13200. var attributes = program.attributes;
  13201. var updateBuffers = false,
  13202. wireframeBit = material.wireframe ? 1 : 0,
  13203. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13204. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13205. _currentGeometryGroupHash = geometryGroupHash;
  13206. updateBuffers = true;
  13207. }
  13208. if ( updateBuffers ) {
  13209. disableAttributes();
  13210. }
  13211. // vertices
  13212. if ( !material.morphTargets && attributes.position >= 0 ) {
  13213. if ( updateBuffers ) {
  13214. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13215. enableAttribute( attributes.position );
  13216. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13217. }
  13218. } else {
  13219. if ( object.morphTargetBase ) {
  13220. setupMorphTargets( material, geometryGroup, object );
  13221. }
  13222. }
  13223. if ( updateBuffers ) {
  13224. // custom attributes
  13225. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13226. if ( geometryGroup.__webglCustomAttributesList ) {
  13227. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13228. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13229. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13230. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13231. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13232. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13233. }
  13234. }
  13235. }
  13236. // colors
  13237. if ( attributes.color >= 0 ) {
  13238. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  13239. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13240. enableAttribute( attributes.color );
  13241. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13242. } else if ( material.defaultAttributeValues ) {
  13243. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  13244. }
  13245. }
  13246. // normals
  13247. if ( attributes.normal >= 0 ) {
  13248. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13249. enableAttribute( attributes.normal );
  13250. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13251. }
  13252. // tangents
  13253. if ( attributes.tangent >= 0 ) {
  13254. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13255. enableAttribute( attributes.tangent );
  13256. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13257. }
  13258. // uvs
  13259. if ( attributes.uv >= 0 ) {
  13260. if ( object.geometry.faceVertexUvs[0] ) {
  13261. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13262. enableAttribute( attributes.uv );
  13263. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13264. } else if ( material.defaultAttributeValues ) {
  13265. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  13266. }
  13267. }
  13268. if ( attributes.uv2 >= 0 ) {
  13269. if ( object.geometry.faceVertexUvs[1] ) {
  13270. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13271. enableAttribute( attributes.uv2 );
  13272. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13273. } else if ( material.defaultAttributeValues ) {
  13274. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  13275. }
  13276. }
  13277. if ( material.skinning &&
  13278. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13279. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13280. enableAttribute( attributes.skinIndex );
  13281. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13282. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13283. enableAttribute( attributes.skinWeight );
  13284. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13285. }
  13286. // line distances
  13287. if ( attributes.lineDistance >= 0 ) {
  13288. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13289. enableAttribute( attributes.lineDistance );
  13290. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13291. }
  13292. }
  13293. // render mesh
  13294. if ( object instanceof THREE.Mesh ) {
  13295. // wireframe
  13296. if ( material.wireframe ) {
  13297. setLineWidth( material.wireframeLinewidth );
  13298. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13299. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  13300. // triangles
  13301. } else {
  13302. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13303. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  13304. }
  13305. _this.info.render.calls ++;
  13306. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13307. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13308. // render lines
  13309. } else if ( object instanceof THREE.Line ) {
  13310. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13311. setLineWidth( material.linewidth );
  13312. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  13313. _this.info.render.calls ++;
  13314. // render particles
  13315. } else if ( object instanceof THREE.ParticleSystem ) {
  13316. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13317. _this.info.render.calls ++;
  13318. _this.info.render.points += geometryGroup.__webglParticleCount;
  13319. }
  13320. };
  13321. function enableAttribute( attribute ) {
  13322. if ( ! _enabledAttributes[ attribute ] ) {
  13323. _gl.enableVertexAttribArray( attribute );
  13324. _enabledAttributes[ attribute ] = true;
  13325. }
  13326. };
  13327. function disableAttributes() {
  13328. for ( var attribute in _enabledAttributes ) {
  13329. if ( _enabledAttributes[ attribute ] ) {
  13330. _gl.disableVertexAttribArray( attribute );
  13331. _enabledAttributes[ attribute ] = false;
  13332. }
  13333. }
  13334. };
  13335. function setupMorphTargets ( material, geometryGroup, object ) {
  13336. // set base
  13337. var attributes = material.program.attributes;
  13338. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13339. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13340. enableAttribute( attributes.position );
  13341. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13342. } else if ( attributes.position >= 0 ) {
  13343. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13344. enableAttribute( attributes.position );
  13345. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13346. }
  13347. if ( object.morphTargetForcedOrder.length ) {
  13348. // set forced order
  13349. var m = 0;
  13350. var order = object.morphTargetForcedOrder;
  13351. var influences = object.morphTargetInfluences;
  13352. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13353. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13354. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13355. enableAttribute( attributes[ "morphTarget" + m ] );
  13356. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13357. }
  13358. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13359. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13360. enableAttribute( attributes[ "morphNormal" + m ] );
  13361. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13362. }
  13363. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13364. m ++;
  13365. }
  13366. } else {
  13367. // find the most influencing
  13368. var influence, activeInfluenceIndices = [];
  13369. var influences = object.morphTargetInfluences;
  13370. var i, il = influences.length;
  13371. for ( i = 0; i < il; i ++ ) {
  13372. influence = influences[ i ];
  13373. if ( influence > 0 ) {
  13374. activeInfluenceIndices.push( [ influence, i ] );
  13375. }
  13376. }
  13377. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13378. activeInfluenceIndices.sort( numericalSort );
  13379. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13380. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13381. activeInfluenceIndices.sort( numericalSort );
  13382. } else if ( activeInfluenceIndices.length === 0 ) {
  13383. activeInfluenceIndices.push( [ 0, 0 ] );
  13384. };
  13385. var influenceIndex, m = 0;
  13386. while ( m < material.numSupportedMorphTargets ) {
  13387. if ( activeInfluenceIndices[ m ] ) {
  13388. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13389. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13390. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13391. enableAttribute( attributes[ "morphTarget" + m ] );
  13392. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13393. }
  13394. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13395. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13396. enableAttribute( attributes[ "morphNormal" + m ] );
  13397. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13398. }
  13399. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13400. } else {
  13401. /*
  13402. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13403. if ( material.morphNormals ) {
  13404. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13405. }
  13406. */
  13407. object.__webglMorphTargetInfluences[ m ] = 0;
  13408. }
  13409. m ++;
  13410. }
  13411. }
  13412. // load updated influences uniform
  13413. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13414. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13415. }
  13416. };
  13417. // Sorting
  13418. function painterSortStable ( a, b ) {
  13419. if ( a.z !== b.z ) {
  13420. return b.z - a.z;
  13421. } else {
  13422. return a.id - b.id;
  13423. }
  13424. };
  13425. function numericalSort ( a, b ) {
  13426. return b[ 0 ] - a[ 0 ];
  13427. };
  13428. // Rendering
  13429. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13430. if ( camera instanceof THREE.Camera === false ) {
  13431. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13432. return;
  13433. }
  13434. var i, il,
  13435. webglObject, object,
  13436. renderList,
  13437. lights = scene.__lights,
  13438. fog = scene.fog;
  13439. // reset caching for this frame
  13440. _currentMaterialId = -1;
  13441. _lightsNeedUpdate = true;
  13442. // update scene graph
  13443. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13444. // update camera matrices and frustum
  13445. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13446. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13447. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13448. _frustum.setFromMatrix( _projScreenMatrix );
  13449. // update WebGL objects
  13450. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13451. // custom render plugins (pre pass)
  13452. renderPlugins( this.renderPluginsPre, scene, camera );
  13453. //
  13454. _this.info.render.calls = 0;
  13455. _this.info.render.vertices = 0;
  13456. _this.info.render.faces = 0;
  13457. _this.info.render.points = 0;
  13458. this.setRenderTarget( renderTarget );
  13459. if ( this.autoClear || forceClear ) {
  13460. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13461. }
  13462. // set matrices for regular objects (frustum culled)
  13463. renderList = scene.__webglObjects;
  13464. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13465. webglObject = renderList[ i ];
  13466. object = webglObject.object;
  13467. webglObject.id = i;
  13468. webglObject.render = false;
  13469. if ( object.visible ) {
  13470. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  13471. setupMatrices( object, camera );
  13472. unrollBufferMaterial( webglObject );
  13473. webglObject.render = true;
  13474. if ( this.sortObjects === true ) {
  13475. if ( object.renderDepth !== null ) {
  13476. webglObject.z = object.renderDepth;
  13477. } else {
  13478. _vector3.getPositionFromMatrix( object.matrixWorld );
  13479. _vector3.applyProjection( _projScreenMatrix );
  13480. webglObject.z = _vector3.z;
  13481. }
  13482. }
  13483. }
  13484. }
  13485. }
  13486. if ( this.sortObjects ) {
  13487. renderList.sort( painterSortStable );
  13488. }
  13489. // set matrices for immediate objects
  13490. renderList = scene.__webglObjectsImmediate;
  13491. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13492. webglObject = renderList[ i ];
  13493. object = webglObject.object;
  13494. if ( object.visible ) {
  13495. setupMatrices( object, camera );
  13496. unrollImmediateBufferMaterial( webglObject );
  13497. }
  13498. }
  13499. if ( scene.overrideMaterial ) {
  13500. var material = scene.overrideMaterial;
  13501. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13502. this.setDepthTest( material.depthTest );
  13503. this.setDepthWrite( material.depthWrite );
  13504. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13505. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13506. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13507. } else {
  13508. var material = null;
  13509. // opaque pass (front-to-back order)
  13510. this.setBlending( THREE.NoBlending );
  13511. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13512. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13513. // transparent pass (back-to-front order)
  13514. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13515. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13516. }
  13517. // custom render plugins (post pass)
  13518. renderPlugins( this.renderPluginsPost, scene, camera );
  13519. // Generate mipmap if we're using any kind of mipmap filtering
  13520. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13521. updateRenderTargetMipmap( renderTarget );
  13522. }
  13523. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13524. this.setDepthTest( true );
  13525. this.setDepthWrite( true );
  13526. // _gl.finish();
  13527. };
  13528. function renderPlugins( plugins, scene, camera ) {
  13529. if ( ! plugins.length ) return;
  13530. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13531. // reset state for plugin (to start from clean slate)
  13532. _currentProgram = null;
  13533. _currentCamera = null;
  13534. _oldBlending = -1;
  13535. _oldDepthTest = -1;
  13536. _oldDepthWrite = -1;
  13537. _oldDoubleSided = -1;
  13538. _oldFlipSided = -1;
  13539. _currentGeometryGroupHash = -1;
  13540. _currentMaterialId = -1;
  13541. _lightsNeedUpdate = true;
  13542. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13543. // reset state after plugin (anything could have changed)
  13544. _currentProgram = null;
  13545. _currentCamera = null;
  13546. _oldBlending = -1;
  13547. _oldDepthTest = -1;
  13548. _oldDepthWrite = -1;
  13549. _oldDoubleSided = -1;
  13550. _oldFlipSided = -1;
  13551. _currentGeometryGroupHash = -1;
  13552. _currentMaterialId = -1;
  13553. _lightsNeedUpdate = true;
  13554. }
  13555. };
  13556. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13557. var webglObject, object, buffer, material, start, end, delta;
  13558. if ( reverse ) {
  13559. start = renderList.length - 1;
  13560. end = -1;
  13561. delta = -1;
  13562. } else {
  13563. start = 0;
  13564. end = renderList.length;
  13565. delta = 1;
  13566. }
  13567. for ( var i = start; i !== end; i += delta ) {
  13568. webglObject = renderList[ i ];
  13569. if ( webglObject.render ) {
  13570. object = webglObject.object;
  13571. buffer = webglObject.buffer;
  13572. if ( overrideMaterial ) {
  13573. material = overrideMaterial;
  13574. } else {
  13575. material = webglObject[ materialType ];
  13576. if ( ! material ) continue;
  13577. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13578. _this.setDepthTest( material.depthTest );
  13579. _this.setDepthWrite( material.depthWrite );
  13580. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13581. }
  13582. _this.setMaterialFaces( material );
  13583. if ( buffer instanceof THREE.BufferGeometry ) {
  13584. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  13585. } else {
  13586. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  13587. }
  13588. }
  13589. }
  13590. };
  13591. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13592. var webglObject, object, material, program;
  13593. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13594. webglObject = renderList[ i ];
  13595. object = webglObject.object;
  13596. if ( object.visible ) {
  13597. if ( overrideMaterial ) {
  13598. material = overrideMaterial;
  13599. } else {
  13600. material = webglObject[ materialType ];
  13601. if ( ! material ) continue;
  13602. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13603. _this.setDepthTest( material.depthTest );
  13604. _this.setDepthWrite( material.depthWrite );
  13605. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13606. }
  13607. _this.renderImmediateObject( camera, lights, fog, material, object );
  13608. }
  13609. }
  13610. };
  13611. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13612. var program = setProgram( camera, lights, fog, material, object );
  13613. _currentGeometryGroupHash = -1;
  13614. _this.setMaterialFaces( material );
  13615. if ( object.immediateRenderCallback ) {
  13616. object.immediateRenderCallback( program, _gl, _frustum );
  13617. } else {
  13618. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13619. }
  13620. };
  13621. function unrollImmediateBufferMaterial ( globject ) {
  13622. var object = globject.object,
  13623. material = object.material;
  13624. if ( material.transparent ) {
  13625. globject.transparent = material;
  13626. globject.opaque = null;
  13627. } else {
  13628. globject.opaque = material;
  13629. globject.transparent = null;
  13630. }
  13631. };
  13632. function unrollBufferMaterial ( globject ) {
  13633. var object = globject.object,
  13634. buffer = globject.buffer,
  13635. material, materialIndex, meshMaterial;
  13636. meshMaterial = object.material;
  13637. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  13638. materialIndex = buffer.materialIndex;
  13639. material = meshMaterial.materials[ materialIndex ];
  13640. if ( material.transparent ) {
  13641. globject.transparent = material;
  13642. globject.opaque = null;
  13643. } else {
  13644. globject.opaque = material;
  13645. globject.transparent = null;
  13646. }
  13647. } else {
  13648. material = meshMaterial;
  13649. if ( material ) {
  13650. if ( material.transparent ) {
  13651. globject.transparent = material;
  13652. globject.opaque = null;
  13653. } else {
  13654. globject.opaque = material;
  13655. globject.transparent = null;
  13656. }
  13657. }
  13658. }
  13659. };
  13660. // Geometry splitting
  13661. function sortFacesByMaterial ( geometry, material ) {
  13662. var f, fl, face, materialIndex, vertices,
  13663. groupHash, hash_map = {};
  13664. var numMorphTargets = geometry.morphTargets.length;
  13665. var numMorphNormals = geometry.morphNormals.length;
  13666. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  13667. geometry.geometryGroups = {};
  13668. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  13669. face = geometry.faces[ f ];
  13670. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  13671. if ( hash_map[ materialIndex ] === undefined ) {
  13672. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  13673. }
  13674. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13675. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13676. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13677. }
  13678. vertices = 3;
  13679. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  13680. hash_map[ materialIndex ].counter += 1;
  13681. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13682. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13683. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13684. }
  13685. }
  13686. geometry.geometryGroups[ groupHash ].faces3.push( f );
  13687. geometry.geometryGroups[ groupHash ].vertices += vertices;
  13688. }
  13689. geometry.geometryGroupsList = [];
  13690. for ( var g in geometry.geometryGroups ) {
  13691. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  13692. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  13693. }
  13694. };
  13695. // Objects refresh
  13696. this.initWebGLObjects = function ( scene ) {
  13697. if ( !scene.__webglObjects ) {
  13698. scene.__webglObjects = [];
  13699. scene.__webglObjectsImmediate = [];
  13700. scene.__webglSprites = [];
  13701. scene.__webglFlares = [];
  13702. }
  13703. while ( scene.__objectsAdded.length ) {
  13704. addObject( scene.__objectsAdded[ 0 ], scene );
  13705. scene.__objectsAdded.splice( 0, 1 );
  13706. }
  13707. while ( scene.__objectsRemoved.length ) {
  13708. removeObject( scene.__objectsRemoved[ 0 ], scene );
  13709. scene.__objectsRemoved.splice( 0, 1 );
  13710. }
  13711. // update must be called after objects adding / removal
  13712. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  13713. var object = scene.__webglObjects[ o ].object;
  13714. // TODO: Remove this hack (WebGLRenderer refactoring)
  13715. if ( object.__webglInit === undefined ) {
  13716. if ( object.__webglActive !== undefined ) {
  13717. removeObject( object, scene );
  13718. }
  13719. addObject( object, scene );
  13720. }
  13721. updateObject( object );
  13722. }
  13723. };
  13724. // Objects adding
  13725. function addObject( object, scene ) {
  13726. var g, geometry, material, geometryGroup;
  13727. if ( object.__webglInit === undefined ) {
  13728. object.__webglInit = true;
  13729. object._modelViewMatrix = new THREE.Matrix4();
  13730. object._normalMatrix = new THREE.Matrix3();
  13731. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  13732. object.geometry.__webglInit = true;
  13733. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  13734. }
  13735. geometry = object.geometry;
  13736. if ( geometry === undefined ) {
  13737. // fail silently for now
  13738. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13739. initDirectBuffers( geometry );
  13740. } else if ( object instanceof THREE.Mesh ) {
  13741. material = object.material;
  13742. if ( geometry.geometryGroups === undefined ) {
  13743. sortFacesByMaterial( geometry, material );
  13744. }
  13745. // create separate VBOs per geometry chunk
  13746. for ( g in geometry.geometryGroups ) {
  13747. geometryGroup = geometry.geometryGroups[ g ];
  13748. // initialise VBO on the first access
  13749. if ( ! geometryGroup.__webglVertexBuffer ) {
  13750. createMeshBuffers( geometryGroup );
  13751. initMeshBuffers( geometryGroup, object );
  13752. geometry.verticesNeedUpdate = true;
  13753. geometry.morphTargetsNeedUpdate = true;
  13754. geometry.elementsNeedUpdate = true;
  13755. geometry.uvsNeedUpdate = true;
  13756. geometry.normalsNeedUpdate = true;
  13757. geometry.tangentsNeedUpdate = true;
  13758. geometry.colorsNeedUpdate = true;
  13759. }
  13760. }
  13761. } else if ( object instanceof THREE.Line ) {
  13762. if ( ! geometry.__webglVertexBuffer ) {
  13763. createLineBuffers( geometry );
  13764. initLineBuffers( geometry, object );
  13765. geometry.verticesNeedUpdate = true;
  13766. geometry.colorsNeedUpdate = true;
  13767. geometry.lineDistancesNeedUpdate = true;
  13768. }
  13769. } else if ( object instanceof THREE.ParticleSystem ) {
  13770. if ( ! geometry.__webglVertexBuffer ) {
  13771. createParticleBuffers( geometry );
  13772. initParticleBuffers( geometry, object );
  13773. geometry.verticesNeedUpdate = true;
  13774. geometry.colorsNeedUpdate = true;
  13775. }
  13776. }
  13777. }
  13778. if ( object.__webglActive === undefined ) {
  13779. if ( object instanceof THREE.Mesh ) {
  13780. geometry = object.geometry;
  13781. if ( geometry instanceof THREE.BufferGeometry ) {
  13782. addBuffer( scene.__webglObjects, geometry, object );
  13783. } else if ( geometry instanceof THREE.Geometry ) {
  13784. for ( g in geometry.geometryGroups ) {
  13785. geometryGroup = geometry.geometryGroups[ g ];
  13786. addBuffer( scene.__webglObjects, geometryGroup, object );
  13787. }
  13788. }
  13789. } else if ( object instanceof THREE.Line ||
  13790. object instanceof THREE.ParticleSystem ) {
  13791. geometry = object.geometry;
  13792. addBuffer( scene.__webglObjects, geometry, object );
  13793. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13794. addBufferImmediate( scene.__webglObjectsImmediate, object );
  13795. } else if ( object instanceof THREE.Sprite ) {
  13796. scene.__webglSprites.push( object );
  13797. } else if ( object instanceof THREE.LensFlare ) {
  13798. scene.__webglFlares.push( object );
  13799. }
  13800. object.__webglActive = true;
  13801. }
  13802. };
  13803. function addBuffer( objlist, buffer, object ) {
  13804. objlist.push(
  13805. {
  13806. id: null,
  13807. buffer: buffer,
  13808. object: object,
  13809. opaque: null,
  13810. transparent: null,
  13811. z: 0
  13812. }
  13813. );
  13814. };
  13815. function addBufferImmediate( objlist, object ) {
  13816. objlist.push(
  13817. {
  13818. id: null,
  13819. object: object,
  13820. opaque: null,
  13821. transparent: null,
  13822. z: 0
  13823. }
  13824. );
  13825. };
  13826. // Objects updates
  13827. function updateObject( object ) {
  13828. var geometry = object.geometry,
  13829. geometryGroup, customAttributesDirty, material;
  13830. if ( geometry instanceof THREE.BufferGeometry ) {
  13831. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13832. } else if ( object instanceof THREE.Mesh ) {
  13833. // check all geometry groups
  13834. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  13835. geometryGroup = geometry.geometryGroupsList[ i ];
  13836. material = getBufferMaterial( object, geometryGroup );
  13837. if ( geometry.buffersNeedUpdate ) {
  13838. initMeshBuffers( geometryGroup, object );
  13839. }
  13840. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13841. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  13842. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13843. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  13844. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  13845. }
  13846. }
  13847. geometry.verticesNeedUpdate = false;
  13848. geometry.morphTargetsNeedUpdate = false;
  13849. geometry.elementsNeedUpdate = false;
  13850. geometry.uvsNeedUpdate = false;
  13851. geometry.normalsNeedUpdate = false;
  13852. geometry.colorsNeedUpdate = false;
  13853. geometry.tangentsNeedUpdate = false;
  13854. geometry.buffersNeedUpdate = false;
  13855. material.attributes && clearCustomAttributes( material );
  13856. } else if ( object instanceof THREE.Line ) {
  13857. material = getBufferMaterial( object, geometry );
  13858. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13859. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  13860. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  13861. }
  13862. geometry.verticesNeedUpdate = false;
  13863. geometry.colorsNeedUpdate = false;
  13864. geometry.lineDistancesNeedUpdate = false;
  13865. material.attributes && clearCustomAttributes( material );
  13866. } else if ( object instanceof THREE.ParticleSystem ) {
  13867. material = getBufferMaterial( object, geometry );
  13868. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13869. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  13870. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  13871. }
  13872. geometry.verticesNeedUpdate = false;
  13873. geometry.colorsNeedUpdate = false;
  13874. material.attributes && clearCustomAttributes( material );
  13875. }
  13876. };
  13877. // Objects updates - custom attributes check
  13878. function areCustomAttributesDirty( material ) {
  13879. for ( var a in material.attributes ) {
  13880. if ( material.attributes[ a ].needsUpdate ) return true;
  13881. }
  13882. return false;
  13883. };
  13884. function clearCustomAttributes( material ) {
  13885. for ( var a in material.attributes ) {
  13886. material.attributes[ a ].needsUpdate = false;
  13887. }
  13888. };
  13889. // Objects removal
  13890. function removeObject( object, scene ) {
  13891. if ( object instanceof THREE.Mesh ||
  13892. object instanceof THREE.ParticleSystem ||
  13893. object instanceof THREE.Line ) {
  13894. removeInstances( scene.__webglObjects, object );
  13895. } else if ( object instanceof THREE.Sprite ) {
  13896. removeInstancesDirect( scene.__webglSprites, object );
  13897. } else if ( object instanceof THREE.LensFlare ) {
  13898. removeInstancesDirect( scene.__webglFlares, object );
  13899. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13900. removeInstances( scene.__webglObjectsImmediate, object );
  13901. }
  13902. delete object.__webglActive;
  13903. };
  13904. function removeInstances( objlist, object ) {
  13905. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13906. if ( objlist[ o ].object === object ) {
  13907. objlist.splice( o, 1 );
  13908. }
  13909. }
  13910. };
  13911. function removeInstancesDirect( objlist, object ) {
  13912. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13913. if ( objlist[ o ] === object ) {
  13914. objlist.splice( o, 1 );
  13915. }
  13916. }
  13917. };
  13918. // Materials
  13919. this.initMaterial = function ( material, lights, fog, object ) {
  13920. material.addEventListener( 'dispose', onMaterialDispose );
  13921. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  13922. if ( material instanceof THREE.MeshDepthMaterial ) {
  13923. shaderID = 'depth';
  13924. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13925. shaderID = 'normal';
  13926. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  13927. shaderID = 'basic';
  13928. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13929. shaderID = 'lambert';
  13930. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13931. shaderID = 'phong';
  13932. } else if ( material instanceof THREE.LineBasicMaterial ) {
  13933. shaderID = 'basic';
  13934. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13935. shaderID = 'dashed';
  13936. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  13937. shaderID = 'particle_basic';
  13938. }
  13939. if ( shaderID ) {
  13940. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  13941. }
  13942. // heuristics to create shader parameters according to lights in the scene
  13943. // (not to blow over maxLights budget)
  13944. maxLightCount = allocateLights( lights );
  13945. maxShadows = allocateShadows( lights );
  13946. maxBones = allocateBones( object );
  13947. parameters = {
  13948. map: !!material.map,
  13949. envMap: !!material.envMap,
  13950. lightMap: !!material.lightMap,
  13951. bumpMap: !!material.bumpMap,
  13952. normalMap: !!material.normalMap,
  13953. specularMap: !!material.specularMap,
  13954. vertexColors: material.vertexColors,
  13955. fog: fog,
  13956. useFog: material.fog,
  13957. fogExp: fog instanceof THREE.FogExp2,
  13958. sizeAttenuation: material.sizeAttenuation,
  13959. skinning: material.skinning,
  13960. maxBones: maxBones,
  13961. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  13962. morphTargets: material.morphTargets,
  13963. morphNormals: material.morphNormals,
  13964. maxMorphTargets: this.maxMorphTargets,
  13965. maxMorphNormals: this.maxMorphNormals,
  13966. maxDirLights: maxLightCount.directional,
  13967. maxPointLights: maxLightCount.point,
  13968. maxSpotLights: maxLightCount.spot,
  13969. maxHemiLights: maxLightCount.hemi,
  13970. maxShadows: maxShadows,
  13971. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  13972. shadowMapType: this.shadowMapType,
  13973. shadowMapDebug: this.shadowMapDebug,
  13974. shadowMapCascade: this.shadowMapCascade,
  13975. alphaTest: material.alphaTest,
  13976. metal: material.metal,
  13977. perPixel: material.perPixel,
  13978. wrapAround: material.wrapAround,
  13979. doubleSided: material.side === THREE.DoubleSide,
  13980. flipSided: material.side === THREE.BackSide
  13981. };
  13982. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters, material.index0AttributeName );
  13983. var attributes = material.program.attributes;
  13984. if ( material.morphTargets ) {
  13985. material.numSupportedMorphTargets = 0;
  13986. var id, base = "morphTarget";
  13987. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  13988. id = base + i;
  13989. if ( attributes[ id ] >= 0 ) {
  13990. material.numSupportedMorphTargets ++;
  13991. }
  13992. }
  13993. }
  13994. if ( material.morphNormals ) {
  13995. material.numSupportedMorphNormals = 0;
  13996. var id, base = "morphNormal";
  13997. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  13998. id = base + i;
  13999. if ( attributes[ id ] >= 0 ) {
  14000. material.numSupportedMorphNormals ++;
  14001. }
  14002. }
  14003. }
  14004. material.uniformsList = [];
  14005. for ( u in material.uniforms ) {
  14006. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14007. }
  14008. };
  14009. function setMaterialShaders( material, shaders ) {
  14010. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14011. material.vertexShader = shaders.vertexShader;
  14012. material.fragmentShader = shaders.fragmentShader;
  14013. };
  14014. function setProgram( camera, lights, fog, material, object ) {
  14015. _usedTextureUnits = 0;
  14016. if ( material.needsUpdate ) {
  14017. if ( material.program ) deallocateMaterial( material );
  14018. _this.initMaterial( material, lights, fog, object );
  14019. material.needsUpdate = false;
  14020. }
  14021. if ( material.morphTargets ) {
  14022. if ( ! object.__webglMorphTargetInfluences ) {
  14023. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14024. }
  14025. }
  14026. var refreshMaterial = false;
  14027. var program = material.program,
  14028. p_uniforms = program.uniforms,
  14029. m_uniforms = material.uniforms;
  14030. if ( program !== _currentProgram ) {
  14031. _gl.useProgram( program );
  14032. _currentProgram = program;
  14033. refreshMaterial = true;
  14034. }
  14035. if ( material.id !== _currentMaterialId ) {
  14036. _currentMaterialId = material.id;
  14037. refreshMaterial = true;
  14038. }
  14039. if ( refreshMaterial || camera !== _currentCamera ) {
  14040. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14041. if ( camera !== _currentCamera ) _currentCamera = camera;
  14042. }
  14043. // skinning uniforms must be set even if material didn't change
  14044. // auto-setting of texture unit for bone texture must go before other textures
  14045. // not sure why, but otherwise weird things happen
  14046. if ( material.skinning ) {
  14047. if ( _supportsBoneTextures && object.useVertexTexture ) {
  14048. if ( p_uniforms.boneTexture !== null ) {
  14049. var textureUnit = getTextureUnit();
  14050. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14051. _this.setTexture( object.boneTexture, textureUnit );
  14052. }
  14053. if ( p_uniforms.boneTextureWidth !== null ) {
  14054. _gl.uniform1i( p_uniforms.boneTextureWidth, object.boneTextureWidth );
  14055. }
  14056. if ( p_uniforms.boneTextureHeight !== null ) {
  14057. _gl.uniform1i( p_uniforms.boneTextureHeight, object.boneTextureHeight );
  14058. }
  14059. } else {
  14060. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14061. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  14062. }
  14063. }
  14064. }
  14065. if ( refreshMaterial ) {
  14066. // refresh uniforms common to several materials
  14067. if ( fog && material.fog ) {
  14068. refreshUniformsFog( m_uniforms, fog );
  14069. }
  14070. if ( material instanceof THREE.MeshPhongMaterial ||
  14071. material instanceof THREE.MeshLambertMaterial ||
  14072. material.lights ) {
  14073. if ( _lightsNeedUpdate ) {
  14074. setupLights( program, lights );
  14075. _lightsNeedUpdate = false;
  14076. }
  14077. refreshUniformsLights( m_uniforms, _lights );
  14078. }
  14079. if ( material instanceof THREE.MeshBasicMaterial ||
  14080. material instanceof THREE.MeshLambertMaterial ||
  14081. material instanceof THREE.MeshPhongMaterial ) {
  14082. refreshUniformsCommon( m_uniforms, material );
  14083. }
  14084. // refresh single material specific uniforms
  14085. if ( material instanceof THREE.LineBasicMaterial ) {
  14086. refreshUniformsLine( m_uniforms, material );
  14087. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14088. refreshUniformsLine( m_uniforms, material );
  14089. refreshUniformsDash( m_uniforms, material );
  14090. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  14091. refreshUniformsParticle( m_uniforms, material );
  14092. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14093. refreshUniformsPhong( m_uniforms, material );
  14094. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14095. refreshUniformsLambert( m_uniforms, material );
  14096. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14097. m_uniforms.mNear.value = camera.near;
  14098. m_uniforms.mFar.value = camera.far;
  14099. m_uniforms.opacity.value = material.opacity;
  14100. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14101. m_uniforms.opacity.value = material.opacity;
  14102. }
  14103. if ( object.receiveShadow && ! material._shadowPass ) {
  14104. refreshUniformsShadow( m_uniforms, lights );
  14105. }
  14106. // load common uniforms
  14107. loadUniformsGeneric( program, material.uniformsList );
  14108. // load material specific uniforms
  14109. // (shader material also gets them for the sake of genericity)
  14110. if ( material instanceof THREE.ShaderMaterial ||
  14111. material instanceof THREE.MeshPhongMaterial ||
  14112. material.envMap ) {
  14113. if ( p_uniforms.cameraPosition !== null ) {
  14114. _vector3.getPositionFromMatrix( camera.matrixWorld );
  14115. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14116. }
  14117. }
  14118. if ( material instanceof THREE.MeshPhongMaterial ||
  14119. material instanceof THREE.MeshLambertMaterial ||
  14120. material instanceof THREE.ShaderMaterial ||
  14121. material.skinning ) {
  14122. if ( p_uniforms.viewMatrix !== null ) {
  14123. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14124. }
  14125. }
  14126. }
  14127. loadUniformsMatrices( p_uniforms, object );
  14128. if ( p_uniforms.modelMatrix !== null ) {
  14129. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14130. }
  14131. return program;
  14132. };
  14133. // Uniforms (refresh uniforms objects)
  14134. function refreshUniformsCommon ( uniforms, material ) {
  14135. uniforms.opacity.value = material.opacity;
  14136. if ( _this.gammaInput ) {
  14137. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14138. } else {
  14139. uniforms.diffuse.value = material.color;
  14140. }
  14141. uniforms.map.value = material.map;
  14142. uniforms.lightMap.value = material.lightMap;
  14143. uniforms.specularMap.value = material.specularMap;
  14144. if ( material.bumpMap ) {
  14145. uniforms.bumpMap.value = material.bumpMap;
  14146. uniforms.bumpScale.value = material.bumpScale;
  14147. }
  14148. if ( material.normalMap ) {
  14149. uniforms.normalMap.value = material.normalMap;
  14150. uniforms.normalScale.value.copy( material.normalScale );
  14151. }
  14152. // uv repeat and offset setting priorities
  14153. // 1. color map
  14154. // 2. specular map
  14155. // 3. normal map
  14156. // 4. bump map
  14157. var uvScaleMap;
  14158. if ( material.map ) {
  14159. uvScaleMap = material.map;
  14160. } else if ( material.specularMap ) {
  14161. uvScaleMap = material.specularMap;
  14162. } else if ( material.normalMap ) {
  14163. uvScaleMap = material.normalMap;
  14164. } else if ( material.bumpMap ) {
  14165. uvScaleMap = material.bumpMap;
  14166. }
  14167. if ( uvScaleMap !== undefined ) {
  14168. var offset = uvScaleMap.offset;
  14169. var repeat = uvScaleMap.repeat;
  14170. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14171. }
  14172. uniforms.envMap.value = material.envMap;
  14173. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14174. if ( _this.gammaInput ) {
  14175. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14176. uniforms.reflectivity.value = material.reflectivity;
  14177. } else {
  14178. uniforms.reflectivity.value = material.reflectivity;
  14179. }
  14180. uniforms.refractionRatio.value = material.refractionRatio;
  14181. uniforms.combine.value = material.combine;
  14182. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14183. };
  14184. function refreshUniformsLine ( uniforms, material ) {
  14185. uniforms.diffuse.value = material.color;
  14186. uniforms.opacity.value = material.opacity;
  14187. };
  14188. function refreshUniformsDash ( uniforms, material ) {
  14189. uniforms.dashSize.value = material.dashSize;
  14190. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14191. uniforms.scale.value = material.scale;
  14192. };
  14193. function refreshUniformsParticle ( uniforms, material ) {
  14194. uniforms.psColor.value = material.color;
  14195. uniforms.opacity.value = material.opacity;
  14196. uniforms.size.value = material.size;
  14197. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14198. uniforms.map.value = material.map;
  14199. };
  14200. function refreshUniformsFog ( uniforms, fog ) {
  14201. uniforms.fogColor.value = fog.color;
  14202. if ( fog instanceof THREE.Fog ) {
  14203. uniforms.fogNear.value = fog.near;
  14204. uniforms.fogFar.value = fog.far;
  14205. } else if ( fog instanceof THREE.FogExp2 ) {
  14206. uniforms.fogDensity.value = fog.density;
  14207. }
  14208. };
  14209. function refreshUniformsPhong ( uniforms, material ) {
  14210. uniforms.shininess.value = material.shininess;
  14211. if ( _this.gammaInput ) {
  14212. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14213. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14214. uniforms.specular.value.copyGammaToLinear( material.specular );
  14215. } else {
  14216. uniforms.ambient.value = material.ambient;
  14217. uniforms.emissive.value = material.emissive;
  14218. uniforms.specular.value = material.specular;
  14219. }
  14220. if ( material.wrapAround ) {
  14221. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14222. }
  14223. };
  14224. function refreshUniformsLambert ( uniforms, material ) {
  14225. if ( _this.gammaInput ) {
  14226. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14227. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14228. } else {
  14229. uniforms.ambient.value = material.ambient;
  14230. uniforms.emissive.value = material.emissive;
  14231. }
  14232. if ( material.wrapAround ) {
  14233. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14234. }
  14235. };
  14236. function refreshUniformsLights ( uniforms, lights ) {
  14237. uniforms.ambientLightColor.value = lights.ambient;
  14238. uniforms.directionalLightColor.value = lights.directional.colors;
  14239. uniforms.directionalLightDirection.value = lights.directional.positions;
  14240. uniforms.pointLightColor.value = lights.point.colors;
  14241. uniforms.pointLightPosition.value = lights.point.positions;
  14242. uniforms.pointLightDistance.value = lights.point.distances;
  14243. uniforms.spotLightColor.value = lights.spot.colors;
  14244. uniforms.spotLightPosition.value = lights.spot.positions;
  14245. uniforms.spotLightDistance.value = lights.spot.distances;
  14246. uniforms.spotLightDirection.value = lights.spot.directions;
  14247. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14248. uniforms.spotLightExponent.value = lights.spot.exponents;
  14249. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14250. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14251. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14252. };
  14253. function refreshUniformsShadow ( uniforms, lights ) {
  14254. if ( uniforms.shadowMatrix ) {
  14255. var j = 0;
  14256. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14257. var light = lights[ i ];
  14258. if ( ! light.castShadow ) continue;
  14259. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14260. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14261. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14262. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14263. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14264. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14265. j ++;
  14266. }
  14267. }
  14268. }
  14269. };
  14270. // Uniforms (load to GPU)
  14271. function loadUniformsMatrices ( uniforms, object ) {
  14272. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14273. if ( uniforms.normalMatrix ) {
  14274. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14275. }
  14276. };
  14277. function getTextureUnit() {
  14278. var textureUnit = _usedTextureUnits;
  14279. if ( textureUnit >= _maxTextures ) {
  14280. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14281. }
  14282. _usedTextureUnits += 1;
  14283. return textureUnit;
  14284. };
  14285. function loadUniformsGeneric ( program, uniforms ) {
  14286. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14287. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14288. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14289. if ( !location ) continue;
  14290. uniform = uniforms[ j ][ 0 ];
  14291. type = uniform.type;
  14292. value = uniform.value;
  14293. if ( type === "i" ) { // single integer
  14294. _gl.uniform1i( location, value );
  14295. } else if ( type === "f" ) { // single float
  14296. _gl.uniform1f( location, value );
  14297. } else if ( type === "v2" ) { // single THREE.Vector2
  14298. _gl.uniform2f( location, value.x, value.y );
  14299. } else if ( type === "v3" ) { // single THREE.Vector3
  14300. _gl.uniform3f( location, value.x, value.y, value.z );
  14301. } else if ( type === "v4" ) { // single THREE.Vector4
  14302. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14303. } else if ( type === "c" ) { // single THREE.Color
  14304. _gl.uniform3f( location, value.r, value.g, value.b );
  14305. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14306. _gl.uniform1iv( location, value );
  14307. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14308. _gl.uniform3iv( location, value );
  14309. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14310. _gl.uniform1fv( location, value );
  14311. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14312. _gl.uniform3fv( location, value );
  14313. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14314. if ( uniform._array === undefined ) {
  14315. uniform._array = new Float32Array( 2 * value.length );
  14316. }
  14317. for ( i = 0, il = value.length; i < il; i ++ ) {
  14318. offset = i * 2;
  14319. uniform._array[ offset ] = value[ i ].x;
  14320. uniform._array[ offset + 1 ] = value[ i ].y;
  14321. }
  14322. _gl.uniform2fv( location, uniform._array );
  14323. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14324. if ( uniform._array === undefined ) {
  14325. uniform._array = new Float32Array( 3 * value.length );
  14326. }
  14327. for ( i = 0, il = value.length; i < il; i ++ ) {
  14328. offset = i * 3;
  14329. uniform._array[ offset ] = value[ i ].x;
  14330. uniform._array[ offset + 1 ] = value[ i ].y;
  14331. uniform._array[ offset + 2 ] = value[ i ].z;
  14332. }
  14333. _gl.uniform3fv( location, uniform._array );
  14334. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14335. if ( uniform._array === undefined ) {
  14336. uniform._array = new Float32Array( 4 * value.length );
  14337. }
  14338. for ( i = 0, il = value.length; i < il; i ++ ) {
  14339. offset = i * 4;
  14340. uniform._array[ offset ] = value[ i ].x;
  14341. uniform._array[ offset + 1 ] = value[ i ].y;
  14342. uniform._array[ offset + 2 ] = value[ i ].z;
  14343. uniform._array[ offset + 3 ] = value[ i ].w;
  14344. }
  14345. _gl.uniform4fv( location, uniform._array );
  14346. } else if ( type === "m4") { // single THREE.Matrix4
  14347. if ( uniform._array === undefined ) {
  14348. uniform._array = new Float32Array( 16 );
  14349. }
  14350. value.flattenToArray( uniform._array );
  14351. _gl.uniformMatrix4fv( location, false, uniform._array );
  14352. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14353. if ( uniform._array === undefined ) {
  14354. uniform._array = new Float32Array( 16 * value.length );
  14355. }
  14356. for ( i = 0, il = value.length; i < il; i ++ ) {
  14357. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14358. }
  14359. _gl.uniformMatrix4fv( location, false, uniform._array );
  14360. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14361. texture = value;
  14362. textureUnit = getTextureUnit();
  14363. _gl.uniform1i( location, textureUnit );
  14364. if ( !texture ) continue;
  14365. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14366. setCubeTexture( texture, textureUnit );
  14367. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14368. setCubeTextureDynamic( texture, textureUnit );
  14369. } else {
  14370. _this.setTexture( texture, textureUnit );
  14371. }
  14372. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14373. if ( uniform._array === undefined ) {
  14374. uniform._array = [];
  14375. }
  14376. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14377. uniform._array[ i ] = getTextureUnit();
  14378. }
  14379. _gl.uniform1iv( location, uniform._array );
  14380. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14381. texture = uniform.value[ i ];
  14382. textureUnit = uniform._array[ i ];
  14383. if ( !texture ) continue;
  14384. _this.setTexture( texture, textureUnit );
  14385. }
  14386. } else {
  14387. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  14388. }
  14389. }
  14390. };
  14391. function setupMatrices ( object, camera ) {
  14392. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14393. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14394. };
  14395. //
  14396. function setColorGamma( array, offset, color, intensitySq ) {
  14397. array[ offset ] = color.r * color.r * intensitySq;
  14398. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14399. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14400. };
  14401. function setColorLinear( array, offset, color, intensity ) {
  14402. array[ offset ] = color.r * intensity;
  14403. array[ offset + 1 ] = color.g * intensity;
  14404. array[ offset + 2 ] = color.b * intensity;
  14405. };
  14406. function setupLights ( program, lights ) {
  14407. var l, ll, light, n,
  14408. r = 0, g = 0, b = 0,
  14409. color, skyColor, groundColor,
  14410. intensity, intensitySq,
  14411. position,
  14412. distance,
  14413. zlights = _lights,
  14414. dirColors = zlights.directional.colors,
  14415. dirPositions = zlights.directional.positions,
  14416. pointColors = zlights.point.colors,
  14417. pointPositions = zlights.point.positions,
  14418. pointDistances = zlights.point.distances,
  14419. spotColors = zlights.spot.colors,
  14420. spotPositions = zlights.spot.positions,
  14421. spotDistances = zlights.spot.distances,
  14422. spotDirections = zlights.spot.directions,
  14423. spotAnglesCos = zlights.spot.anglesCos,
  14424. spotExponents = zlights.spot.exponents,
  14425. hemiSkyColors = zlights.hemi.skyColors,
  14426. hemiGroundColors = zlights.hemi.groundColors,
  14427. hemiPositions = zlights.hemi.positions,
  14428. dirLength = 0,
  14429. pointLength = 0,
  14430. spotLength = 0,
  14431. hemiLength = 0,
  14432. dirCount = 0,
  14433. pointCount = 0,
  14434. spotCount = 0,
  14435. hemiCount = 0,
  14436. dirOffset = 0,
  14437. pointOffset = 0,
  14438. spotOffset = 0,
  14439. hemiOffset = 0;
  14440. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14441. light = lights[ l ];
  14442. if ( light.onlyShadow ) continue;
  14443. color = light.color;
  14444. intensity = light.intensity;
  14445. distance = light.distance;
  14446. if ( light instanceof THREE.AmbientLight ) {
  14447. if ( ! light.visible ) continue;
  14448. if ( _this.gammaInput ) {
  14449. r += color.r * color.r;
  14450. g += color.g * color.g;
  14451. b += color.b * color.b;
  14452. } else {
  14453. r += color.r;
  14454. g += color.g;
  14455. b += color.b;
  14456. }
  14457. } else if ( light instanceof THREE.DirectionalLight ) {
  14458. dirCount += 1;
  14459. if ( ! light.visible ) continue;
  14460. _direction.getPositionFromMatrix( light.matrixWorld );
  14461. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14462. _direction.sub( _vector3 );
  14463. _direction.normalize();
  14464. // skip lights with undefined direction
  14465. // these create troubles in OpenGL (making pixel black)
  14466. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14467. dirOffset = dirLength * 3;
  14468. dirPositions[ dirOffset ] = _direction.x;
  14469. dirPositions[ dirOffset + 1 ] = _direction.y;
  14470. dirPositions[ dirOffset + 2 ] = _direction.z;
  14471. if ( _this.gammaInput ) {
  14472. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14473. } else {
  14474. setColorLinear( dirColors, dirOffset, color, intensity );
  14475. }
  14476. dirLength += 1;
  14477. } else if ( light instanceof THREE.PointLight ) {
  14478. pointCount += 1;
  14479. if ( ! light.visible ) continue;
  14480. pointOffset = pointLength * 3;
  14481. if ( _this.gammaInput ) {
  14482. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14483. } else {
  14484. setColorLinear( pointColors, pointOffset, color, intensity );
  14485. }
  14486. _vector3.getPositionFromMatrix( light.matrixWorld );
  14487. pointPositions[ pointOffset ] = _vector3.x;
  14488. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14489. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14490. pointDistances[ pointLength ] = distance;
  14491. pointLength += 1;
  14492. } else if ( light instanceof THREE.SpotLight ) {
  14493. spotCount += 1;
  14494. if ( ! light.visible ) continue;
  14495. spotOffset = spotLength * 3;
  14496. if ( _this.gammaInput ) {
  14497. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14498. } else {
  14499. setColorLinear( spotColors, spotOffset, color, intensity );
  14500. }
  14501. _vector3.getPositionFromMatrix( light.matrixWorld );
  14502. spotPositions[ spotOffset ] = _vector3.x;
  14503. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14504. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14505. spotDistances[ spotLength ] = distance;
  14506. _direction.copy( _vector3 );
  14507. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14508. _direction.sub( _vector3 );
  14509. _direction.normalize();
  14510. spotDirections[ spotOffset ] = _direction.x;
  14511. spotDirections[ spotOffset + 1 ] = _direction.y;
  14512. spotDirections[ spotOffset + 2 ] = _direction.z;
  14513. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14514. spotExponents[ spotLength ] = light.exponent;
  14515. spotLength += 1;
  14516. } else if ( light instanceof THREE.HemisphereLight ) {
  14517. hemiCount += 1;
  14518. if ( ! light.visible ) continue;
  14519. _direction.getPositionFromMatrix( light.matrixWorld );
  14520. _direction.normalize();
  14521. // skip lights with undefined direction
  14522. // these create troubles in OpenGL (making pixel black)
  14523. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14524. hemiOffset = hemiLength * 3;
  14525. hemiPositions[ hemiOffset ] = _direction.x;
  14526. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14527. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14528. skyColor = light.color;
  14529. groundColor = light.groundColor;
  14530. if ( _this.gammaInput ) {
  14531. intensitySq = intensity * intensity;
  14532. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14533. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14534. } else {
  14535. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14536. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14537. }
  14538. hemiLength += 1;
  14539. }
  14540. }
  14541. // null eventual remains from removed lights
  14542. // (this is to avoid if in shader)
  14543. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14544. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14545. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14546. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14547. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14548. zlights.directional.length = dirLength;
  14549. zlights.point.length = pointLength;
  14550. zlights.spot.length = spotLength;
  14551. zlights.hemi.length = hemiLength;
  14552. zlights.ambient[ 0 ] = r;
  14553. zlights.ambient[ 1 ] = g;
  14554. zlights.ambient[ 2 ] = b;
  14555. };
  14556. // GL state setting
  14557. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14558. if ( cullFace === THREE.CullFaceNone ) {
  14559. _gl.disable( _gl.CULL_FACE );
  14560. } else {
  14561. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14562. _gl.frontFace( _gl.CW );
  14563. } else {
  14564. _gl.frontFace( _gl.CCW );
  14565. }
  14566. if ( cullFace === THREE.CullFaceBack ) {
  14567. _gl.cullFace( _gl.BACK );
  14568. } else if ( cullFace === THREE.CullFaceFront ) {
  14569. _gl.cullFace( _gl.FRONT );
  14570. } else {
  14571. _gl.cullFace( _gl.FRONT_AND_BACK );
  14572. }
  14573. _gl.enable( _gl.CULL_FACE );
  14574. }
  14575. };
  14576. this.setMaterialFaces = function ( material ) {
  14577. var doubleSided = material.side === THREE.DoubleSide;
  14578. var flipSided = material.side === THREE.BackSide;
  14579. if ( _oldDoubleSided !== doubleSided ) {
  14580. if ( doubleSided ) {
  14581. _gl.disable( _gl.CULL_FACE );
  14582. } else {
  14583. _gl.enable( _gl.CULL_FACE );
  14584. }
  14585. _oldDoubleSided = doubleSided;
  14586. }
  14587. if ( _oldFlipSided !== flipSided ) {
  14588. if ( flipSided ) {
  14589. _gl.frontFace( _gl.CW );
  14590. } else {
  14591. _gl.frontFace( _gl.CCW );
  14592. }
  14593. _oldFlipSided = flipSided;
  14594. }
  14595. };
  14596. this.setDepthTest = function ( depthTest ) {
  14597. if ( _oldDepthTest !== depthTest ) {
  14598. if ( depthTest ) {
  14599. _gl.enable( _gl.DEPTH_TEST );
  14600. } else {
  14601. _gl.disable( _gl.DEPTH_TEST );
  14602. }
  14603. _oldDepthTest = depthTest;
  14604. }
  14605. };
  14606. this.setDepthWrite = function ( depthWrite ) {
  14607. if ( _oldDepthWrite !== depthWrite ) {
  14608. _gl.depthMask( depthWrite );
  14609. _oldDepthWrite = depthWrite;
  14610. }
  14611. };
  14612. function setLineWidth ( width ) {
  14613. if ( width !== _oldLineWidth ) {
  14614. _gl.lineWidth( width );
  14615. _oldLineWidth = width;
  14616. }
  14617. };
  14618. function setPolygonOffset ( polygonoffset, factor, units ) {
  14619. if ( _oldPolygonOffset !== polygonoffset ) {
  14620. if ( polygonoffset ) {
  14621. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  14622. } else {
  14623. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  14624. }
  14625. _oldPolygonOffset = polygonoffset;
  14626. }
  14627. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  14628. _gl.polygonOffset( factor, units );
  14629. _oldPolygonOffsetFactor = factor;
  14630. _oldPolygonOffsetUnits = units;
  14631. }
  14632. };
  14633. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  14634. if ( blending !== _oldBlending ) {
  14635. if ( blending === THREE.NoBlending ) {
  14636. _gl.disable( _gl.BLEND );
  14637. } else if ( blending === THREE.AdditiveBlending ) {
  14638. _gl.enable( _gl.BLEND );
  14639. _gl.blendEquation( _gl.FUNC_ADD );
  14640. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  14641. } else if ( blending === THREE.SubtractiveBlending ) {
  14642. // TODO: Find blendFuncSeparate() combination
  14643. _gl.enable( _gl.BLEND );
  14644. _gl.blendEquation( _gl.FUNC_ADD );
  14645. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  14646. } else if ( blending === THREE.MultiplyBlending ) {
  14647. // TODO: Find blendFuncSeparate() combination
  14648. _gl.enable( _gl.BLEND );
  14649. _gl.blendEquation( _gl.FUNC_ADD );
  14650. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  14651. } else if ( blending === THREE.CustomBlending ) {
  14652. _gl.enable( _gl.BLEND );
  14653. } else {
  14654. _gl.enable( _gl.BLEND );
  14655. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  14656. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  14657. }
  14658. _oldBlending = blending;
  14659. }
  14660. if ( blending === THREE.CustomBlending ) {
  14661. if ( blendEquation !== _oldBlendEquation ) {
  14662. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  14663. _oldBlendEquation = blendEquation;
  14664. }
  14665. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  14666. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  14667. _oldBlendSrc = blendSrc;
  14668. _oldBlendDst = blendDst;
  14669. }
  14670. } else {
  14671. _oldBlendEquation = null;
  14672. _oldBlendSrc = null;
  14673. _oldBlendDst = null;
  14674. }
  14675. };
  14676. // Defines
  14677. function generateDefines ( defines ) {
  14678. var value, chunk, chunks = [];
  14679. for ( var d in defines ) {
  14680. value = defines[ d ];
  14681. if ( value === false ) continue;
  14682. chunk = "#define " + d + " " + value;
  14683. chunks.push( chunk );
  14684. }
  14685. return chunks.join( "\n" );
  14686. };
  14687. // Shaders
  14688. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters, index0AttributeName ) {
  14689. var p, pl, d, program, code;
  14690. var chunks = [];
  14691. // Generate code
  14692. if ( shaderID ) {
  14693. chunks.push( shaderID );
  14694. } else {
  14695. chunks.push( fragmentShader );
  14696. chunks.push( vertexShader );
  14697. }
  14698. for ( d in defines ) {
  14699. chunks.push( d );
  14700. chunks.push( defines[ d ] );
  14701. }
  14702. for ( p in parameters ) {
  14703. chunks.push( p );
  14704. chunks.push( parameters[ p ] );
  14705. }
  14706. code = chunks.join();
  14707. // Check if code has been already compiled
  14708. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  14709. var programInfo = _programs[ p ];
  14710. if ( programInfo.code === code ) {
  14711. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  14712. programInfo.usedTimes ++;
  14713. return programInfo.program;
  14714. }
  14715. }
  14716. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  14717. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  14718. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  14719. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  14720. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  14721. }
  14722. // console.log( "building new program " );
  14723. //
  14724. var customDefines = generateDefines( defines );
  14725. //
  14726. program = _gl.createProgram();
  14727. var prefix_vertex = [
  14728. "precision " + _precision + " float;",
  14729. "precision " + _precision + " int;",
  14730. customDefines,
  14731. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  14732. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14733. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14734. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14735. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14736. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14737. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14738. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14739. "#define MAX_SHADOWS " + parameters.maxShadows,
  14740. "#define MAX_BONES " + parameters.maxBones,
  14741. parameters.map ? "#define USE_MAP" : "",
  14742. parameters.envMap ? "#define USE_ENVMAP" : "",
  14743. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14744. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14745. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14746. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14747. parameters.vertexColors ? "#define USE_COLOR" : "",
  14748. parameters.skinning ? "#define USE_SKINNING" : "",
  14749. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  14750. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  14751. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  14752. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14753. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14754. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14755. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14756. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14757. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14758. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14759. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14760. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  14761. "uniform mat4 modelMatrix;",
  14762. "uniform mat4 modelViewMatrix;",
  14763. "uniform mat4 projectionMatrix;",
  14764. "uniform mat4 viewMatrix;",
  14765. "uniform mat3 normalMatrix;",
  14766. "uniform vec3 cameraPosition;",
  14767. "attribute vec3 position;",
  14768. "attribute vec3 normal;",
  14769. "attribute vec2 uv;",
  14770. "attribute vec2 uv2;",
  14771. "#ifdef USE_COLOR",
  14772. "attribute vec3 color;",
  14773. "#endif",
  14774. "#ifdef USE_MORPHTARGETS",
  14775. "attribute vec3 morphTarget0;",
  14776. "attribute vec3 morphTarget1;",
  14777. "attribute vec3 morphTarget2;",
  14778. "attribute vec3 morphTarget3;",
  14779. "#ifdef USE_MORPHNORMALS",
  14780. "attribute vec3 morphNormal0;",
  14781. "attribute vec3 morphNormal1;",
  14782. "attribute vec3 morphNormal2;",
  14783. "attribute vec3 morphNormal3;",
  14784. "#else",
  14785. "attribute vec3 morphTarget4;",
  14786. "attribute vec3 morphTarget5;",
  14787. "attribute vec3 morphTarget6;",
  14788. "attribute vec3 morphTarget7;",
  14789. "#endif",
  14790. "#endif",
  14791. "#ifdef USE_SKINNING",
  14792. "attribute vec4 skinIndex;",
  14793. "attribute vec4 skinWeight;",
  14794. "#endif",
  14795. ""
  14796. ].join("\n");
  14797. var prefix_fragment = [
  14798. "precision " + _precision + " float;",
  14799. "precision " + _precision + " int;",
  14800. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  14801. customDefines,
  14802. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14803. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14804. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14805. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14806. "#define MAX_SHADOWS " + parameters.maxShadows,
  14807. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  14808. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14809. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14810. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14811. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  14812. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  14813. parameters.map ? "#define USE_MAP" : "",
  14814. parameters.envMap ? "#define USE_ENVMAP" : "",
  14815. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14816. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14817. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14818. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14819. parameters.vertexColors ? "#define USE_COLOR" : "",
  14820. parameters.metal ? "#define METAL" : "",
  14821. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14822. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14823. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14824. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14825. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14826. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14827. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14828. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14829. "uniform mat4 viewMatrix;",
  14830. "uniform vec3 cameraPosition;",
  14831. ""
  14832. ].join("\n");
  14833. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  14834. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  14835. _gl.attachShader( program, glVertexShader );
  14836. _gl.attachShader( program, glFragmentShader );
  14837. //Force a particular attribute to index 0.
  14838. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  14839. //And, color, for example is often automatically bound to index 0 so disabling it
  14840. if ( index0AttributeName ) {
  14841. _gl.bindAttribLocation( program, 0, index0AttributeName );
  14842. }
  14843. _gl.linkProgram( program );
  14844. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  14845. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  14846. console.error( "Program Info Log: " + _gl.getProgramInfoLog( program ) );
  14847. }
  14848. // clean up
  14849. _gl.deleteShader( glFragmentShader );
  14850. _gl.deleteShader( glVertexShader );
  14851. // console.log( prefix_fragment + fragmentShader );
  14852. // console.log( prefix_vertex + vertexShader );
  14853. program.uniforms = {};
  14854. program.attributes = {};
  14855. var identifiers, u, a, i;
  14856. // cache uniform locations
  14857. identifiers = [
  14858. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  14859. 'morphTargetInfluences'
  14860. ];
  14861. if ( parameters.useVertexTexture ) {
  14862. identifiers.push( 'boneTexture' );
  14863. identifiers.push( 'boneTextureWidth' );
  14864. identifiers.push( 'boneTextureHeight' );
  14865. } else {
  14866. identifiers.push( 'boneGlobalMatrices' );
  14867. }
  14868. for ( u in uniforms ) {
  14869. identifiers.push( u );
  14870. }
  14871. cacheUniformLocations( program, identifiers );
  14872. // cache attributes locations
  14873. identifiers = [
  14874. "position", "normal", "uv", "uv2", "tangent", "color",
  14875. "skinIndex", "skinWeight", "lineDistance"
  14876. ];
  14877. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  14878. identifiers.push( "morphTarget" + i );
  14879. }
  14880. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  14881. identifiers.push( "morphNormal" + i );
  14882. }
  14883. for ( a in attributes ) {
  14884. identifiers.push( a );
  14885. }
  14886. cacheAttributeLocations( program, identifiers );
  14887. program.id = _programs_counter ++;
  14888. _programs.push( { program: program, code: code, usedTimes: 1 } );
  14889. _this.info.memory.programs = _programs.length;
  14890. return program;
  14891. };
  14892. // Shader parameters cache
  14893. function cacheUniformLocations ( program, identifiers ) {
  14894. var i, l, id;
  14895. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14896. id = identifiers[ i ];
  14897. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  14898. }
  14899. };
  14900. function cacheAttributeLocations ( program, identifiers ) {
  14901. var i, l, id;
  14902. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14903. id = identifiers[ i ];
  14904. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  14905. }
  14906. };
  14907. function addLineNumbers ( string ) {
  14908. var chunks = string.split( "\n" );
  14909. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  14910. // Chrome reports shader errors on lines
  14911. // starting counting from 1
  14912. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  14913. }
  14914. return chunks.join( "\n" );
  14915. };
  14916. function getShader ( type, string ) {
  14917. var shader;
  14918. if ( type === "fragment" ) {
  14919. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  14920. } else if ( type === "vertex" ) {
  14921. shader = _gl.createShader( _gl.VERTEX_SHADER );
  14922. }
  14923. _gl.shaderSource( shader, string );
  14924. _gl.compileShader( shader );
  14925. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  14926. console.error( _gl.getShaderInfoLog( shader ) );
  14927. console.error( addLineNumbers( string ) );
  14928. return null;
  14929. }
  14930. return shader;
  14931. };
  14932. // Textures
  14933. function isPowerOfTwo ( value ) {
  14934. return ( value & ( value - 1 ) ) === 0;
  14935. };
  14936. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14937. if ( isImagePowerOfTwo ) {
  14938. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14939. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14940. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14941. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14942. } else {
  14943. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14944. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14945. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14946. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14947. }
  14948. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  14949. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  14950. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  14951. texture.__oldAnisotropy = texture.anisotropy;
  14952. }
  14953. }
  14954. };
  14955. this.setTexture = function ( texture, slot ) {
  14956. if ( texture.needsUpdate ) {
  14957. if ( ! texture.__webglInit ) {
  14958. texture.__webglInit = true;
  14959. texture.addEventListener( 'dispose', onTextureDispose );
  14960. texture.__webglTexture = _gl.createTexture();
  14961. _this.info.memory.textures ++;
  14962. }
  14963. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14964. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14965. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14966. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14967. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14968. var image = texture.image,
  14969. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14970. glFormat = paramThreeToGL( texture.format ),
  14971. glType = paramThreeToGL( texture.type );
  14972. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  14973. var mipmap, mipmaps = texture.mipmaps;
  14974. if ( texture instanceof THREE.DataTexture ) {
  14975. // use manually created mipmaps if available
  14976. // if there are no manual mipmaps
  14977. // set 0 level mipmap and then use GL to generate other mipmap levels
  14978. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14979. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14980. mipmap = mipmaps[ i ];
  14981. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14982. }
  14983. texture.generateMipmaps = false;
  14984. } else {
  14985. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14986. }
  14987. } else if ( texture instanceof THREE.CompressedTexture ) {
  14988. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14989. mipmap = mipmaps[ i ];
  14990. if ( texture.format!==THREE.RGBAFormat ) {
  14991. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14992. } else {
  14993. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14994. }
  14995. }
  14996. } else { // regular Texture (image, video, canvas)
  14997. // use manually created mipmaps if available
  14998. // if there are no manual mipmaps
  14999. // set 0 level mipmap and then use GL to generate other mipmap levels
  15000. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15001. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15002. mipmap = mipmaps[ i ];
  15003. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15004. }
  15005. texture.generateMipmaps = false;
  15006. } else {
  15007. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  15008. }
  15009. }
  15010. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15011. texture.needsUpdate = false;
  15012. if ( texture.onUpdate ) texture.onUpdate();
  15013. } else {
  15014. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15015. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15016. }
  15017. };
  15018. function clampToMaxSize ( image, maxSize ) {
  15019. if ( image.width <= maxSize && image.height <= maxSize ) {
  15020. return image;
  15021. }
  15022. // Warning: Scaling through the canvas will only work with images that use
  15023. // premultiplied alpha.
  15024. var maxDimension = Math.max( image.width, image.height );
  15025. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15026. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15027. var canvas = document.createElement( 'canvas' );
  15028. canvas.width = newWidth;
  15029. canvas.height = newHeight;
  15030. var ctx = canvas.getContext( "2d" );
  15031. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15032. return canvas;
  15033. }
  15034. function setCubeTexture ( texture, slot ) {
  15035. if ( texture.image.length === 6 ) {
  15036. if ( texture.needsUpdate ) {
  15037. if ( ! texture.image.__webglTextureCube ) {
  15038. texture.addEventListener( 'dispose', onTextureDispose );
  15039. texture.image.__webglTextureCube = _gl.createTexture();
  15040. _this.info.memory.textures ++;
  15041. }
  15042. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15043. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15044. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15045. var isCompressed = texture instanceof THREE.CompressedTexture;
  15046. var cubeImage = [];
  15047. for ( var i = 0; i < 6; i ++ ) {
  15048. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15049. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15050. } else {
  15051. cubeImage[ i ] = texture.image[ i ];
  15052. }
  15053. }
  15054. var image = cubeImage[ 0 ],
  15055. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  15056. glFormat = paramThreeToGL( texture.format ),
  15057. glType = paramThreeToGL( texture.type );
  15058. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15059. for ( var i = 0; i < 6; i ++ ) {
  15060. if( !isCompressed ) {
  15061. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15062. } else {
  15063. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15064. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15065. mipmap = mipmaps[ j ];
  15066. if ( texture.format!==THREE.RGBAFormat ) {
  15067. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15068. } else {
  15069. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15070. }
  15071. }
  15072. }
  15073. }
  15074. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15075. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15076. }
  15077. texture.needsUpdate = false;
  15078. if ( texture.onUpdate ) texture.onUpdate();
  15079. } else {
  15080. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15081. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15082. }
  15083. }
  15084. };
  15085. function setCubeTextureDynamic ( texture, slot ) {
  15086. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15087. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15088. };
  15089. // Render targets
  15090. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15091. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15092. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15093. };
  15094. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15095. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15096. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15097. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15098. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15099. /* For some reason this is not working. Defaulting to RGBA4.
  15100. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15101. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15102. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15103. */
  15104. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15105. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15106. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15107. } else {
  15108. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15109. }
  15110. };
  15111. this.setRenderTarget = function ( renderTarget ) {
  15112. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15113. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15114. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15115. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15116. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15117. renderTarget.__webglTexture = _gl.createTexture();
  15118. _this.info.memory.textures ++;
  15119. // Setup texture, create render and frame buffers
  15120. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  15121. glFormat = paramThreeToGL( renderTarget.format ),
  15122. glType = paramThreeToGL( renderTarget.type );
  15123. if ( isCube ) {
  15124. renderTarget.__webglFramebuffer = [];
  15125. renderTarget.__webglRenderbuffer = [];
  15126. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15127. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15128. for ( var i = 0; i < 6; i ++ ) {
  15129. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15130. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15131. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15132. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15133. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15134. }
  15135. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15136. } else {
  15137. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15138. if ( renderTarget.shareDepthFrom ) {
  15139. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15140. } else {
  15141. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15142. }
  15143. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15144. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15145. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15146. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15147. if ( renderTarget.shareDepthFrom ) {
  15148. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15149. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15150. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15151. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15152. }
  15153. } else {
  15154. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15155. }
  15156. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15157. }
  15158. // Release everything
  15159. if ( isCube ) {
  15160. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15161. } else {
  15162. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15163. }
  15164. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15165. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15166. }
  15167. var framebuffer, width, height, vx, vy;
  15168. if ( renderTarget ) {
  15169. if ( isCube ) {
  15170. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15171. } else {
  15172. framebuffer = renderTarget.__webglFramebuffer;
  15173. }
  15174. width = renderTarget.width;
  15175. height = renderTarget.height;
  15176. vx = 0;
  15177. vy = 0;
  15178. } else {
  15179. framebuffer = null;
  15180. width = _viewportWidth;
  15181. height = _viewportHeight;
  15182. vx = _viewportX;
  15183. vy = _viewportY;
  15184. }
  15185. if ( framebuffer !== _currentFramebuffer ) {
  15186. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15187. _gl.viewport( vx, vy, width, height );
  15188. _currentFramebuffer = framebuffer;
  15189. }
  15190. _currentWidth = width;
  15191. _currentHeight = height;
  15192. };
  15193. function updateRenderTargetMipmap ( renderTarget ) {
  15194. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15195. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15196. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15197. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15198. } else {
  15199. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15200. _gl.generateMipmap( _gl.TEXTURE_2D );
  15201. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15202. }
  15203. };
  15204. // Fallback filters for non-power-of-2 textures
  15205. function filterFallback ( f ) {
  15206. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15207. return _gl.NEAREST;
  15208. }
  15209. return _gl.LINEAR;
  15210. };
  15211. // Map three.js constants to WebGL constants
  15212. function paramThreeToGL ( p ) {
  15213. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15214. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15215. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15216. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15217. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15218. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15219. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15220. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15221. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15222. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15223. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15224. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15225. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15226. if ( p === THREE.ByteType ) return _gl.BYTE;
  15227. if ( p === THREE.ShortType ) return _gl.SHORT;
  15228. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15229. if ( p === THREE.IntType ) return _gl.INT;
  15230. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15231. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15232. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15233. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15234. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15235. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15236. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15237. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15238. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15239. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15240. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15241. if ( p === THREE.OneFactor ) return _gl.ONE;
  15242. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15243. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15244. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15245. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15246. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15247. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15248. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15249. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15250. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15251. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15252. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15253. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15254. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15255. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15256. }
  15257. return 0;
  15258. };
  15259. // Allocations
  15260. function allocateBones ( object ) {
  15261. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15262. return 1024;
  15263. } else {
  15264. // default for when object is not specified
  15265. // ( for example when prebuilding shader
  15266. // to be used with multiple objects )
  15267. //
  15268. // - leave some extra space for other uniforms
  15269. // - limit here is ANGLE's 254 max uniform vectors
  15270. // (up to 54 should be safe)
  15271. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15272. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15273. var maxBones = nVertexMatrices;
  15274. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15275. maxBones = Math.min( object.bones.length, maxBones );
  15276. if ( maxBones < object.bones.length ) {
  15277. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15278. }
  15279. }
  15280. return maxBones;
  15281. }
  15282. };
  15283. function allocateLights( lights ) {
  15284. var dirLights = 0;
  15285. var pointLights = 0;
  15286. var spotLights = 0;
  15287. var hemiLights = 0;
  15288. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15289. var light = lights[ l ];
  15290. if ( light.onlyShadow ) continue;
  15291. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15292. if ( light instanceof THREE.PointLight ) pointLights ++;
  15293. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15294. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15295. }
  15296. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15297. };
  15298. function allocateShadows( lights ) {
  15299. var maxShadows = 0;
  15300. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  15301. var light = lights[ l ];
  15302. if ( ! light.castShadow ) continue;
  15303. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15304. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15305. }
  15306. return maxShadows;
  15307. };
  15308. // Initialization
  15309. function initGL() {
  15310. try {
  15311. var attributes = {
  15312. alpha: _alpha,
  15313. premultipliedAlpha: _premultipliedAlpha,
  15314. antialias: _antialias,
  15315. stencil: _stencil,
  15316. preserveDrawingBuffer: _preserveDrawingBuffer
  15317. };
  15318. _gl = _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  15319. if ( _gl === null ) {
  15320. throw 'Error creating WebGL context.';
  15321. }
  15322. } catch ( error ) {
  15323. console.error( error );
  15324. }
  15325. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15326. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15327. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15328. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15329. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15330. if ( ! _glExtensionTextureFloat ) {
  15331. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15332. }
  15333. if ( ! _glExtensionStandardDerivatives ) {
  15334. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15335. }
  15336. if ( ! _glExtensionTextureFilterAnisotropic ) {
  15337. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15338. }
  15339. if ( ! _glExtensionCompressedTextureS3TC ) {
  15340. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15341. }
  15342. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15343. _gl.getShaderPrecisionFormat = function() {
  15344. return {
  15345. "rangeMin" : 1,
  15346. "rangeMax" : 1,
  15347. "precision" : 1
  15348. };
  15349. }
  15350. }
  15351. };
  15352. function setDefaultGLState () {
  15353. _gl.clearColor( 0, 0, 0, 1 );
  15354. _gl.clearDepth( 1 );
  15355. _gl.clearStencil( 0 );
  15356. _gl.enable( _gl.DEPTH_TEST );
  15357. _gl.depthFunc( _gl.LEQUAL );
  15358. _gl.frontFace( _gl.CCW );
  15359. _gl.cullFace( _gl.BACK );
  15360. _gl.enable( _gl.CULL_FACE );
  15361. _gl.enable( _gl.BLEND );
  15362. _gl.blendEquation( _gl.FUNC_ADD );
  15363. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15364. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  15365. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15366. };
  15367. // default plugins (order is important)
  15368. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15369. this.addPrePlugin( this.shadowMapPlugin );
  15370. this.addPostPlugin( new THREE.SpritePlugin() );
  15371. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15372. };
  15373. /**
  15374. * @author szimek / https://github.com/szimek/
  15375. * @author alteredq / http://alteredqualia.com/
  15376. */
  15377. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15378. this.width = width;
  15379. this.height = height;
  15380. options = options || {};
  15381. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15382. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15383. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15384. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15385. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15386. this.offset = new THREE.Vector2( 0, 0 );
  15387. this.repeat = new THREE.Vector2( 1, 1 );
  15388. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15389. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15390. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15391. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15392. this.generateMipmaps = true;
  15393. this.shareDepthFrom = null;
  15394. };
  15395. THREE.WebGLRenderTarget.prototype = {
  15396. constructor: THREE.WebGLRenderTarget,
  15397. clone: function () {
  15398. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15399. tmp.wrapS = this.wrapS;
  15400. tmp.wrapT = this.wrapT;
  15401. tmp.magFilter = this.magFilter;
  15402. tmp.minFilter = this.minFilter;
  15403. tmp.anisotropy = this.anisotropy;
  15404. tmp.offset.copy( this.offset );
  15405. tmp.repeat.copy( this.repeat );
  15406. tmp.format = this.format;
  15407. tmp.type = this.type;
  15408. tmp.depthBuffer = this.depthBuffer;
  15409. tmp.stencilBuffer = this.stencilBuffer;
  15410. tmp.generateMipmaps = this.generateMipmaps;
  15411. tmp.shareDepthFrom = this.shareDepthFrom;
  15412. return tmp;
  15413. },
  15414. dispose: function () {
  15415. this.dispatchEvent( { type: 'dispose' } );
  15416. }
  15417. };
  15418. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  15419. /**
  15420. * @author alteredq / http://alteredqualia.com
  15421. */
  15422. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15423. THREE.WebGLRenderTarget.call( this, width, height, options );
  15424. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15425. };
  15426. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15427. /**
  15428. * @author mrdoob / http://mrdoob.com/
  15429. */
  15430. THREE.RenderableVertex = function () {
  15431. this.positionWorld = new THREE.Vector3();
  15432. this.positionScreen = new THREE.Vector4();
  15433. this.visible = true;
  15434. };
  15435. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15436. this.positionWorld.copy( vertex.positionWorld );
  15437. this.positionScreen.copy( vertex.positionScreen );
  15438. };
  15439. /**
  15440. * @author mrdoob / http://mrdoob.com/
  15441. */
  15442. THREE.RenderableFace3 = function () {
  15443. this.id = 0;
  15444. this.v1 = new THREE.RenderableVertex();
  15445. this.v2 = new THREE.RenderableVertex();
  15446. this.v3 = new THREE.RenderableVertex();
  15447. this.centroidModel = new THREE.Vector3();
  15448. this.normalModel = new THREE.Vector3();
  15449. this.normalModelView = new THREE.Vector3();
  15450. this.vertexNormalsLength = 0;
  15451. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15452. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15453. this.color = null;
  15454. this.material = null;
  15455. this.uvs = [[]];
  15456. this.z = 0;
  15457. };
  15458. /**
  15459. * @author mrdoob / http://mrdoob.com/
  15460. */
  15461. THREE.RenderableObject = function () {
  15462. this.id = 0;
  15463. this.object = null;
  15464. this.z = 0;
  15465. };
  15466. /**
  15467. * @author mrdoob / http://mrdoob.com/
  15468. */
  15469. THREE.RenderableSprite = function () {
  15470. this.id = 0;
  15471. this.object = null;
  15472. this.x = 0;
  15473. this.y = 0;
  15474. this.z = 0;
  15475. this.rotation = 0;
  15476. this.scale = new THREE.Vector2();
  15477. this.material = null;
  15478. };
  15479. /**
  15480. * @author mrdoob / http://mrdoob.com/
  15481. */
  15482. THREE.RenderableLine = function () {
  15483. this.id = 0;
  15484. this.v1 = new THREE.RenderableVertex();
  15485. this.v2 = new THREE.RenderableVertex();
  15486. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  15487. this.material = null;
  15488. this.z = 0;
  15489. };
  15490. /**
  15491. * @author mrdoob / http://mrdoob.com/
  15492. * @author alteredq / http://alteredqualia.com/
  15493. */
  15494. THREE.GeometryUtils = {
  15495. // Merge two geometries or geometry and geometry from object (using object's transform)
  15496. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  15497. var matrix, normalMatrix,
  15498. vertexOffset = geometry1.vertices.length,
  15499. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15500. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15501. vertices1 = geometry1.vertices,
  15502. vertices2 = geometry2.vertices,
  15503. faces1 = geometry1.faces,
  15504. faces2 = geometry2.faces,
  15505. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15506. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15507. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  15508. if ( object2 instanceof THREE.Mesh ) {
  15509. object2.matrixAutoUpdate && object2.updateMatrix();
  15510. matrix = object2.matrix;
  15511. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  15512. }
  15513. // vertices
  15514. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15515. var vertex = vertices2[ i ];
  15516. var vertexCopy = vertex.clone();
  15517. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15518. vertices1.push( vertexCopy );
  15519. }
  15520. // faces
  15521. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15522. var face = faces2[ i ], faceCopy, normal, color,
  15523. faceVertexNormals = face.vertexNormals,
  15524. faceVertexColors = face.vertexColors;
  15525. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15526. faceCopy.normal.copy( face.normal );
  15527. if ( normalMatrix ) {
  15528. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15529. }
  15530. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15531. normal = faceVertexNormals[ j ].clone();
  15532. if ( normalMatrix ) {
  15533. normal.applyMatrix3( normalMatrix ).normalize();
  15534. }
  15535. faceCopy.vertexNormals.push( normal );
  15536. }
  15537. faceCopy.color.copy( face.color );
  15538. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15539. color = faceVertexColors[ j ];
  15540. faceCopy.vertexColors.push( color.clone() );
  15541. }
  15542. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  15543. faceCopy.centroid.copy( face.centroid );
  15544. if ( matrix ) {
  15545. faceCopy.centroid.applyMatrix4( matrix );
  15546. }
  15547. faces1.push( faceCopy );
  15548. }
  15549. // uvs
  15550. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15551. var uv = uvs2[ i ], uvCopy = [];
  15552. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15553. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15554. }
  15555. uvs1.push( uvCopy );
  15556. }
  15557. },
  15558. // Get random point in triangle (via barycentric coordinates)
  15559. // (uniform distribution)
  15560. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15561. randomPointInTriangle: function () {
  15562. var vector = new THREE.Vector3();
  15563. return function ( vectorA, vectorB, vectorC ) {
  15564. var point = new THREE.Vector3();
  15565. var a = THREE.Math.random16();
  15566. var b = THREE.Math.random16();
  15567. if ( ( a + b ) > 1 ) {
  15568. a = 1 - a;
  15569. b = 1 - b;
  15570. }
  15571. var c = 1 - a - b;
  15572. point.copy( vectorA );
  15573. point.multiplyScalar( a );
  15574. vector.copy( vectorB );
  15575. vector.multiplyScalar( b );
  15576. point.add( vector );
  15577. vector.copy( vectorC );
  15578. vector.multiplyScalar( c );
  15579. point.add( vector );
  15580. return point;
  15581. };
  15582. }(),
  15583. // Get random point in face (triangle / quad)
  15584. // (uniform distribution)
  15585. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15586. var vA, vB, vC, vD;
  15587. vA = geometry.vertices[ face.a ];
  15588. vB = geometry.vertices[ face.b ];
  15589. vC = geometry.vertices[ face.c ];
  15590. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15591. },
  15592. // Get uniformly distributed random points in mesh
  15593. // - create array with cumulative sums of face areas
  15594. // - pick random number from 0 to total area
  15595. // - find corresponding place in area array by binary search
  15596. // - get random point in face
  15597. randomPointsInGeometry: function ( geometry, n ) {
  15598. var face, i,
  15599. faces = geometry.faces,
  15600. vertices = geometry.vertices,
  15601. il = faces.length,
  15602. totalArea = 0,
  15603. cumulativeAreas = [],
  15604. vA, vB, vC, vD;
  15605. // precompute face areas
  15606. for ( i = 0; i < il; i ++ ) {
  15607. face = faces[ i ];
  15608. vA = vertices[ face.a ];
  15609. vB = vertices[ face.b ];
  15610. vC = vertices[ face.c ];
  15611. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  15612. totalArea += face._area;
  15613. cumulativeAreas[ i ] = totalArea;
  15614. }
  15615. // binary search cumulative areas array
  15616. function binarySearchIndices( value ) {
  15617. function binarySearch( start, end ) {
  15618. // return closest larger index
  15619. // if exact number is not found
  15620. if ( end < start )
  15621. return start;
  15622. var mid = start + Math.floor( ( end - start ) / 2 );
  15623. if ( cumulativeAreas[ mid ] > value ) {
  15624. return binarySearch( start, mid - 1 );
  15625. } else if ( cumulativeAreas[ mid ] < value ) {
  15626. return binarySearch( mid + 1, end );
  15627. } else {
  15628. return mid;
  15629. }
  15630. }
  15631. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  15632. return result;
  15633. }
  15634. // pick random face weighted by face area
  15635. var r, index,
  15636. result = [];
  15637. var stats = {};
  15638. for ( i = 0; i < n; i ++ ) {
  15639. r = THREE.Math.random16() * totalArea;
  15640. index = binarySearchIndices( r );
  15641. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  15642. if ( ! stats[ index ] ) {
  15643. stats[ index ] = 1;
  15644. } else {
  15645. stats[ index ] += 1;
  15646. }
  15647. }
  15648. return result;
  15649. },
  15650. // Get triangle area (half of parallelogram)
  15651. // http://mathworld.wolfram.com/TriangleArea.html
  15652. triangleArea: function () {
  15653. var vector1 = new THREE.Vector3();
  15654. var vector2 = new THREE.Vector3();
  15655. return function ( vectorA, vectorB, vectorC ) {
  15656. vector1.subVectors( vectorB, vectorA );
  15657. vector2.subVectors( vectorC, vectorA );
  15658. vector1.cross( vector2 );
  15659. return 0.5 * vector1.length();
  15660. };
  15661. }(),
  15662. // Center geometry so that 0,0,0 is in center of bounding box
  15663. center: function ( geometry ) {
  15664. geometry.computeBoundingBox();
  15665. var bb = geometry.boundingBox;
  15666. var offset = new THREE.Vector3();
  15667. offset.addVectors( bb.min, bb.max );
  15668. offset.multiplyScalar( -0.5 );
  15669. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  15670. geometry.computeBoundingBox();
  15671. return offset;
  15672. },
  15673. triangulateQuads: function ( geometry ) {
  15674. var i, il, j, jl;
  15675. var faces = [];
  15676. var faceVertexUvs = [];
  15677. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15678. faceVertexUvs[ i ] = [];
  15679. }
  15680. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15681. var face = geometry.faces[ i ];
  15682. faces.push( face );
  15683. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15684. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15685. }
  15686. }
  15687. geometry.faces = faces;
  15688. geometry.faceVertexUvs = faceVertexUvs;
  15689. geometry.computeCentroids();
  15690. geometry.computeFaceNormals();
  15691. geometry.computeVertexNormals();
  15692. if ( geometry.hasTangents ) geometry.computeTangents();
  15693. }
  15694. };
  15695. /**
  15696. * @author alteredq / http://alteredqualia.com/
  15697. * @author mrdoob / http://mrdoob.com/
  15698. */
  15699. THREE.ImageUtils = {
  15700. crossOrigin: 'anonymous',
  15701. loadTexture: function ( url, mapping, onLoad, onError ) {
  15702. var loader = new THREE.ImageLoader();
  15703. loader.crossOrigin = this.crossOrigin;
  15704. var texture = new THREE.Texture( undefined, mapping );
  15705. var image = loader.load( url, function () {
  15706. texture.needsUpdate = true;
  15707. if ( onLoad ) onLoad( texture );
  15708. } );
  15709. texture.image = image;
  15710. texture.sourceFile = url;
  15711. return texture;
  15712. },
  15713. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15714. var texture = new THREE.CompressedTexture();
  15715. texture.mapping = mapping;
  15716. var request = new XMLHttpRequest();
  15717. request.onload = function () {
  15718. var buffer = request.response;
  15719. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15720. texture.format = dds.format;
  15721. texture.mipmaps = dds.mipmaps;
  15722. texture.image.width = dds.width;
  15723. texture.image.height = dds.height;
  15724. // gl.generateMipmap fails for compressed textures
  15725. // mipmaps must be embedded in the DDS file
  15726. // or texture filters must not use mipmapping
  15727. texture.generateMipmaps = false;
  15728. texture.needsUpdate = true;
  15729. if ( onLoad ) onLoad( texture );
  15730. }
  15731. request.onerror = onError;
  15732. request.open( 'GET', url, true );
  15733. request.responseType = "arraybuffer";
  15734. request.send( null );
  15735. return texture;
  15736. },
  15737. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15738. var images = [];
  15739. images.loadCount = 0;
  15740. var texture = new THREE.Texture();
  15741. texture.image = images;
  15742. if ( mapping !== undefined ) texture.mapping = mapping;
  15743. // no flipping needed for cube textures
  15744. texture.flipY = false;
  15745. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15746. var cubeImage = new Image();
  15747. images[ i ] = cubeImage;
  15748. cubeImage.onload = function () {
  15749. images.loadCount += 1;
  15750. if ( images.loadCount === 6 ) {
  15751. texture.needsUpdate = true;
  15752. if ( onLoad ) onLoad( texture );
  15753. }
  15754. };
  15755. cubeImage.onerror = onError;
  15756. cubeImage.crossOrigin = this.crossOrigin;
  15757. cubeImage.src = array[ i ];
  15758. }
  15759. return texture;
  15760. },
  15761. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15762. var images = [];
  15763. images.loadCount = 0;
  15764. var texture = new THREE.CompressedTexture();
  15765. texture.image = images;
  15766. if ( mapping !== undefined ) texture.mapping = mapping;
  15767. // no flipping for cube textures
  15768. // (also flipping doesn't work for compressed textures )
  15769. texture.flipY = false;
  15770. // can't generate mipmaps for compressed textures
  15771. // mips must be embedded in DDS files
  15772. texture.generateMipmaps = false;
  15773. var generateCubeFaceCallback = function ( rq, img ) {
  15774. return function () {
  15775. var buffer = rq.response;
  15776. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15777. img.format = dds.format;
  15778. img.mipmaps = dds.mipmaps;
  15779. img.width = dds.width;
  15780. img.height = dds.height;
  15781. images.loadCount += 1;
  15782. if ( images.loadCount === 6 ) {
  15783. texture.format = dds.format;
  15784. texture.needsUpdate = true;
  15785. if ( onLoad ) onLoad( texture );
  15786. }
  15787. }
  15788. }
  15789. // compressed cubemap textures as 6 separate DDS files
  15790. if ( array instanceof Array ) {
  15791. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15792. var cubeImage = {};
  15793. images[ i ] = cubeImage;
  15794. var request = new XMLHttpRequest();
  15795. request.onload = generateCubeFaceCallback( request, cubeImage );
  15796. request.onerror = onError;
  15797. var url = array[ i ];
  15798. request.open( 'GET', url, true );
  15799. request.responseType = "arraybuffer";
  15800. request.send( null );
  15801. }
  15802. // compressed cubemap texture stored in a single DDS file
  15803. } else {
  15804. var url = array;
  15805. var request = new XMLHttpRequest();
  15806. request.onload = function( ) {
  15807. var buffer = request.response;
  15808. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15809. if ( dds.isCubemap ) {
  15810. var faces = dds.mipmaps.length / dds.mipmapCount;
  15811. for ( var f = 0; f < faces; f ++ ) {
  15812. images[ f ] = { mipmaps : [] };
  15813. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15814. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15815. images[ f ].format = dds.format;
  15816. images[ f ].width = dds.width;
  15817. images[ f ].height = dds.height;
  15818. }
  15819. }
  15820. texture.format = dds.format;
  15821. texture.needsUpdate = true;
  15822. if ( onLoad ) onLoad( texture );
  15823. }
  15824. }
  15825. request.onerror = onError;
  15826. request.open( 'GET', url, true );
  15827. request.responseType = "arraybuffer";
  15828. request.send( null );
  15829. }
  15830. return texture;
  15831. },
  15832. loadDDSTexture: function ( url, mapping, onLoad, onError ) {
  15833. var images = [];
  15834. images.loadCount = 0;
  15835. var texture = new THREE.CompressedTexture();
  15836. texture.image = images;
  15837. if ( mapping !== undefined ) texture.mapping = mapping;
  15838. // no flipping for cube textures
  15839. // (also flipping doesn't work for compressed textures )
  15840. texture.flipY = false;
  15841. // can't generate mipmaps for compressed textures
  15842. // mips must be embedded in DDS files
  15843. texture.generateMipmaps = false;
  15844. {
  15845. var request = new XMLHttpRequest();
  15846. request.onload = function( ) {
  15847. var buffer = request.response;
  15848. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15849. if ( dds.isCubemap ) {
  15850. var faces = dds.mipmaps.length / dds.mipmapCount;
  15851. for ( var f = 0; f < faces; f ++ ) {
  15852. images[ f ] = { mipmaps : [] };
  15853. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15854. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15855. images[ f ].format = dds.format;
  15856. images[ f ].width = dds.width;
  15857. images[ f ].height = dds.height;
  15858. }
  15859. }
  15860. } else {
  15861. texture.image.width = dds.width;
  15862. texture.image.height = dds.height;
  15863. texture.mipmaps = dds.mipmaps;
  15864. }
  15865. texture.format = dds.format;
  15866. texture.needsUpdate = true;
  15867. if ( onLoad ) onLoad( texture );
  15868. }
  15869. request.onerror = onError;
  15870. request.open( 'GET', url, true );
  15871. request.responseType = "arraybuffer";
  15872. request.send( null );
  15873. }
  15874. return texture;
  15875. },
  15876. parseDDS: function ( buffer, loadMipmaps ) {
  15877. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15878. // Adapted from @toji's DDS utils
  15879. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15880. // All values and structures referenced from:
  15881. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15882. var DDS_MAGIC = 0x20534444;
  15883. var DDSD_CAPS = 0x1,
  15884. DDSD_HEIGHT = 0x2,
  15885. DDSD_WIDTH = 0x4,
  15886. DDSD_PITCH = 0x8,
  15887. DDSD_PIXELFORMAT = 0x1000,
  15888. DDSD_MIPMAPCOUNT = 0x20000,
  15889. DDSD_LINEARSIZE = 0x80000,
  15890. DDSD_DEPTH = 0x800000;
  15891. var DDSCAPS_COMPLEX = 0x8,
  15892. DDSCAPS_MIPMAP = 0x400000,
  15893. DDSCAPS_TEXTURE = 0x1000;
  15894. var DDSCAPS2_CUBEMAP = 0x200,
  15895. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15896. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15897. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15898. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15899. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15900. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15901. DDSCAPS2_VOLUME = 0x200000;
  15902. var DDPF_ALPHAPIXELS = 0x1,
  15903. DDPF_ALPHA = 0x2,
  15904. DDPF_FOURCC = 0x4,
  15905. DDPF_RGB = 0x40,
  15906. DDPF_YUV = 0x200,
  15907. DDPF_LUMINANCE = 0x20000;
  15908. function fourCCToInt32( value ) {
  15909. return value.charCodeAt(0) +
  15910. (value.charCodeAt(1) << 8) +
  15911. (value.charCodeAt(2) << 16) +
  15912. (value.charCodeAt(3) << 24);
  15913. }
  15914. function int32ToFourCC( value ) {
  15915. return String.fromCharCode(
  15916. value & 0xff,
  15917. (value >> 8) & 0xff,
  15918. (value >> 16) & 0xff,
  15919. (value >> 24) & 0xff
  15920. );
  15921. }
  15922. function loadARGBMip( buffer, dataOffset, width, height ) {
  15923. var dataLength = width*height*4;
  15924. var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength );
  15925. var byteArray = new Uint8Array( dataLength );
  15926. var dst = 0;
  15927. var src = 0;
  15928. for ( var y = 0; y < height; y++ ) {
  15929. for ( var x = 0; x < width; x++ ) {
  15930. var b = srcBuffer[src]; src++;
  15931. var g = srcBuffer[src]; src++;
  15932. var r = srcBuffer[src]; src++;
  15933. var a = srcBuffer[src]; src++;
  15934. byteArray[dst] = r; dst++; //r
  15935. byteArray[dst] = g; dst++; //g
  15936. byteArray[dst] = b; dst++; //b
  15937. byteArray[dst] = a; dst++; //a
  15938. }
  15939. }
  15940. return byteArray;
  15941. }
  15942. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15943. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15944. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15945. var headerLengthInt = 31; // The header length in 32 bit ints
  15946. // Offsets into the header array
  15947. var off_magic = 0;
  15948. var off_size = 1;
  15949. var off_flags = 2;
  15950. var off_height = 3;
  15951. var off_width = 4;
  15952. var off_mipmapCount = 7;
  15953. var off_pfFlags = 20;
  15954. var off_pfFourCC = 21;
  15955. var off_RGBBitCount = 22;
  15956. var off_RBitMask = 23;
  15957. var off_GBitMask = 24;
  15958. var off_BBitMask = 25;
  15959. var off_ABitMask = 26;
  15960. var off_caps = 27;
  15961. var off_caps2 = 28;
  15962. var off_caps3 = 29;
  15963. var off_caps4 = 30;
  15964. // Parse header
  15965. var header = new Int32Array( buffer, 0, headerLengthInt );
  15966. if ( header[ off_magic ] !== DDS_MAGIC ) {
  15967. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  15968. return dds;
  15969. }
  15970. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  15971. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  15972. return dds;
  15973. }
  15974. var blockBytes;
  15975. var fourCC = header[ off_pfFourCC ];
  15976. var isRGBAUncompressed = false;
  15977. switch ( fourCC ) {
  15978. case FOURCC_DXT1:
  15979. blockBytes = 8;
  15980. dds.format = THREE.RGB_S3TC_DXT1_Format;
  15981. break;
  15982. case FOURCC_DXT3:
  15983. blockBytes = 16;
  15984. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  15985. break;
  15986. case FOURCC_DXT5:
  15987. blockBytes = 16;
  15988. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  15989. break;
  15990. default:
  15991. if( header[off_RGBBitCount] ==32
  15992. && header[off_RBitMask]&0xff0000
  15993. && header[off_GBitMask]&0xff00
  15994. && header[off_BBitMask]&0xff
  15995. && header[off_ABitMask]&0xff000000 ) {
  15996. isRGBAUncompressed = true;
  15997. blockBytes = 64;
  15998. dds.format = THREE.RGBAFormat;
  15999. } else {
  16000. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  16001. return dds;
  16002. }
  16003. }
  16004. dds.mipmapCount = 1;
  16005. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  16006. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  16007. }
  16008. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  16009. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  16010. dds.width = header[ off_width ];
  16011. dds.height = header[ off_height ];
  16012. var dataOffset = header[ off_size ] + 4;
  16013. // Extract mipmaps buffers
  16014. var width = dds.width;
  16015. var height = dds.height;
  16016. var faces = dds.isCubemap ? 6 : 1;
  16017. for ( var face = 0; face < faces; face ++ ) {
  16018. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16019. if( isRGBAUncompressed ) {
  16020. var byteArray = loadARGBMip( buffer, dataOffset, width, height );
  16021. var dataLength = byteArray.length;
  16022. } else {
  16023. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16024. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16025. }
  16026. var mipmap = { "data": byteArray, "width": width, "height": height };
  16027. dds.mipmaps.push( mipmap );
  16028. dataOffset += dataLength;
  16029. width = Math.max( width * 0.5, 1 );
  16030. height = Math.max( height * 0.5, 1 );
  16031. }
  16032. width = dds.width;
  16033. height = dds.height;
  16034. }
  16035. return dds;
  16036. },
  16037. getNormalMap: function ( image, depth ) {
  16038. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16039. var cross = function ( a, b ) {
  16040. 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 ] ];
  16041. }
  16042. var subtract = function ( a, b ) {
  16043. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16044. }
  16045. var normalize = function ( a ) {
  16046. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16047. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16048. }
  16049. depth = depth | 1;
  16050. var width = image.width;
  16051. var height = image.height;
  16052. var canvas = document.createElement( 'canvas' );
  16053. canvas.width = width;
  16054. canvas.height = height;
  16055. var context = canvas.getContext( '2d' );
  16056. context.drawImage( image, 0, 0 );
  16057. var data = context.getImageData( 0, 0, width, height ).data;
  16058. var imageData = context.createImageData( width, height );
  16059. var output = imageData.data;
  16060. for ( var x = 0; x < width; x ++ ) {
  16061. for ( var y = 0; y < height; y ++ ) {
  16062. var ly = y - 1 < 0 ? 0 : y - 1;
  16063. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16064. var lx = x - 1 < 0 ? 0 : x - 1;
  16065. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16066. var points = [];
  16067. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16068. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16069. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16070. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16071. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16072. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16073. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16074. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16075. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16076. var normals = [];
  16077. var num_points = points.length;
  16078. for ( var i = 0; i < num_points; i ++ ) {
  16079. var v1 = points[ i ];
  16080. var v2 = points[ ( i + 1 ) % num_points ];
  16081. v1 = subtract( v1, origin );
  16082. v2 = subtract( v2, origin );
  16083. normals.push( normalize( cross( v1, v2 ) ) );
  16084. }
  16085. var normal = [ 0, 0, 0 ];
  16086. for ( var i = 0; i < normals.length; i ++ ) {
  16087. normal[ 0 ] += normals[ i ][ 0 ];
  16088. normal[ 1 ] += normals[ i ][ 1 ];
  16089. normal[ 2 ] += normals[ i ][ 2 ];
  16090. }
  16091. normal[ 0 ] /= normals.length;
  16092. normal[ 1 ] /= normals.length;
  16093. normal[ 2 ] /= normals.length;
  16094. var idx = ( y * width + x ) * 4;
  16095. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16096. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16097. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16098. output[ idx + 3 ] = 255;
  16099. }
  16100. }
  16101. context.putImageData( imageData, 0, 0 );
  16102. return canvas;
  16103. },
  16104. generateDataTexture: function ( width, height, color ) {
  16105. var size = width * height;
  16106. var data = new Uint8Array( 3 * size );
  16107. var r = Math.floor( color.r * 255 );
  16108. var g = Math.floor( color.g * 255 );
  16109. var b = Math.floor( color.b * 255 );
  16110. for ( var i = 0; i < size; i ++ ) {
  16111. data[ i * 3 ] = r;
  16112. data[ i * 3 + 1 ] = g;
  16113. data[ i * 3 + 2 ] = b;
  16114. }
  16115. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16116. texture.needsUpdate = true;
  16117. return texture;
  16118. }
  16119. };
  16120. /**
  16121. * @author alteredq / http://alteredqualia.com/
  16122. */
  16123. THREE.SceneUtils = {
  16124. createMultiMaterialObject: function ( geometry, materials ) {
  16125. var group = new THREE.Object3D();
  16126. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16127. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16128. }
  16129. return group;
  16130. },
  16131. detach : function ( child, parent, scene ) {
  16132. child.applyMatrix( parent.matrixWorld );
  16133. parent.remove( child );
  16134. scene.add( child );
  16135. },
  16136. attach: function ( child, scene, parent ) {
  16137. var matrixWorldInverse = new THREE.Matrix4();
  16138. matrixWorldInverse.getInverse( parent.matrixWorld );
  16139. child.applyMatrix( matrixWorldInverse );
  16140. scene.remove( child );
  16141. parent.add( child );
  16142. }
  16143. };
  16144. /**
  16145. * @author zz85 / http://www.lab4games.net/zz85/blog
  16146. * @author alteredq / http://alteredqualia.com/
  16147. *
  16148. * For Text operations in three.js (See TextGeometry)
  16149. *
  16150. * It uses techniques used in:
  16151. *
  16152. * typeface.js and canvastext
  16153. * For converting fonts and rendering with javascript
  16154. * http://typeface.neocracy.org
  16155. *
  16156. * Triangulation ported from AS3
  16157. * Simple Polygon Triangulation
  16158. * http://actionsnippet.com/?p=1462
  16159. *
  16160. * A Method to triangulate shapes with holes
  16161. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16162. *
  16163. */
  16164. THREE.FontUtils = {
  16165. faces : {},
  16166. // Just for now. face[weight][style]
  16167. face : "helvetiker",
  16168. weight: "normal",
  16169. style : "normal",
  16170. size : 150,
  16171. divisions : 10,
  16172. getFace : function() {
  16173. return this.faces[ this.face ][ this.weight ][ this.style ];
  16174. },
  16175. loadFace : function( data ) {
  16176. var family = data.familyName.toLowerCase();
  16177. var ThreeFont = this;
  16178. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16179. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16180. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16181. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16182. return data;
  16183. },
  16184. drawText : function( text ) {
  16185. var characterPts = [], allPts = [];
  16186. // RenderText
  16187. var i, p,
  16188. face = this.getFace(),
  16189. scale = this.size / face.resolution,
  16190. offset = 0,
  16191. chars = String( text ).split( '' ),
  16192. length = chars.length;
  16193. var fontPaths = [];
  16194. for ( i = 0; i < length; i ++ ) {
  16195. var path = new THREE.Path();
  16196. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16197. offset += ret.offset;
  16198. fontPaths.push( ret.path );
  16199. }
  16200. // get the width
  16201. var width = offset / 2;
  16202. //
  16203. // for ( p = 0; p < allPts.length; p++ ) {
  16204. //
  16205. // allPts[ p ].x -= width;
  16206. //
  16207. // }
  16208. //var extract = this.extractPoints( allPts, characterPts );
  16209. //extract.contour = allPts;
  16210. //extract.paths = fontPaths;
  16211. //extract.offset = width;
  16212. return { paths : fontPaths, offset : width };
  16213. },
  16214. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16215. var pts = [];
  16216. var i, i2, divisions,
  16217. outline, action, length,
  16218. scaleX, scaleY,
  16219. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16220. laste,
  16221. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16222. if ( !glyph ) return;
  16223. if ( glyph.o ) {
  16224. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16225. length = outline.length;
  16226. scaleX = scale;
  16227. scaleY = scale;
  16228. for ( i = 0; i < length; ) {
  16229. action = outline[ i ++ ];
  16230. //console.log( action );
  16231. switch( action ) {
  16232. case 'm':
  16233. // Move To
  16234. x = outline[ i++ ] * scaleX + offset;
  16235. y = outline[ i++ ] * scaleY;
  16236. path.moveTo( x, y );
  16237. break;
  16238. case 'l':
  16239. // Line To
  16240. x = outline[ i++ ] * scaleX + offset;
  16241. y = outline[ i++ ] * scaleY;
  16242. path.lineTo(x,y);
  16243. break;
  16244. case 'q':
  16245. // QuadraticCurveTo
  16246. cpx = outline[ i++ ] * scaleX + offset;
  16247. cpy = outline[ i++ ] * scaleY;
  16248. cpx1 = outline[ i++ ] * scaleX + offset;
  16249. cpy1 = outline[ i++ ] * scaleY;
  16250. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16251. laste = pts[ pts.length - 1 ];
  16252. if ( laste ) {
  16253. cpx0 = laste.x;
  16254. cpy0 = laste.y;
  16255. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16256. var t = i2 / divisions;
  16257. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16258. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16259. }
  16260. }
  16261. break;
  16262. case 'b':
  16263. // Cubic Bezier Curve
  16264. cpx = outline[ i++ ] * scaleX + offset;
  16265. cpy = outline[ i++ ] * scaleY;
  16266. cpx1 = outline[ i++ ] * scaleX + offset;
  16267. cpy1 = outline[ i++ ] * -scaleY;
  16268. cpx2 = outline[ i++ ] * scaleX + offset;
  16269. cpy2 = outline[ i++ ] * -scaleY;
  16270. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16271. laste = pts[ pts.length - 1 ];
  16272. if ( laste ) {
  16273. cpx0 = laste.x;
  16274. cpy0 = laste.y;
  16275. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16276. var t = i2 / divisions;
  16277. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16278. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16279. }
  16280. }
  16281. break;
  16282. }
  16283. }
  16284. }
  16285. return { offset: glyph.ha*scale, path:path};
  16286. }
  16287. };
  16288. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16289. // Parameters
  16290. parameters = parameters || {};
  16291. var size = parameters.size !== undefined ? parameters.size : 100;
  16292. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16293. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16294. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16295. var style = parameters.style !== undefined ? parameters.style : "normal";
  16296. THREE.FontUtils.size = size;
  16297. THREE.FontUtils.divisions = curveSegments;
  16298. THREE.FontUtils.face = font;
  16299. THREE.FontUtils.weight = weight;
  16300. THREE.FontUtils.style = style;
  16301. // Get a Font data json object
  16302. var data = THREE.FontUtils.drawText( text );
  16303. var paths = data.paths;
  16304. var shapes = [];
  16305. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16306. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16307. }
  16308. return shapes;
  16309. };
  16310. /**
  16311. * This code is a quick port of code written in C++ which was submitted to
  16312. * flipcode.com by John W. Ratcliff // July 22, 2000
  16313. * See original code and more information here:
  16314. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16315. *
  16316. * ported to actionscript by Zevan Rosser
  16317. * www.actionsnippet.com
  16318. *
  16319. * ported to javascript by Joshua Koo
  16320. * http://www.lab4games.net/zz85/blog
  16321. *
  16322. */
  16323. ( function( namespace ) {
  16324. var EPSILON = 0.0000000001;
  16325. // takes in an contour array and returns
  16326. var process = function( contour, indices ) {
  16327. var n = contour.length;
  16328. if ( n < 3 ) return null;
  16329. var result = [],
  16330. verts = [],
  16331. vertIndices = [];
  16332. /* we want a counter-clockwise polygon in verts */
  16333. var u, v, w;
  16334. if ( area( contour ) > 0.0 ) {
  16335. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16336. } else {
  16337. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16338. }
  16339. var nv = n;
  16340. /* remove nv - 2 vertices, creating 1 triangle every time */
  16341. var count = 2 * nv; /* error detection */
  16342. for( v = nv - 1; nv > 2; ) {
  16343. /* if we loop, it is probably a non-simple polygon */
  16344. if ( ( count-- ) <= 0 ) {
  16345. //** Triangulate: ERROR - probable bad polygon!
  16346. //throw ( "Warning, unable to triangulate polygon!" );
  16347. //return null;
  16348. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16349. console.log( "Warning, unable to triangulate polygon!" );
  16350. if ( indices ) return vertIndices;
  16351. return result;
  16352. }
  16353. /* three consecutive vertices in current polygon, <u,v,w> */
  16354. u = v; if ( nv <= u ) u = 0; /* previous */
  16355. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16356. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16357. if ( snip( contour, u, v, w, nv, verts ) ) {
  16358. var a, b, c, s, t;
  16359. /* true names of the vertices */
  16360. a = verts[ u ];
  16361. b = verts[ v ];
  16362. c = verts[ w ];
  16363. /* output Triangle */
  16364. result.push( [ contour[ a ],
  16365. contour[ b ],
  16366. contour[ c ] ] );
  16367. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16368. /* remove v from the remaining polygon */
  16369. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16370. verts[ s ] = verts[ t ];
  16371. }
  16372. nv--;
  16373. /* reset error detection counter */
  16374. count = 2 * nv;
  16375. }
  16376. }
  16377. if ( indices ) return vertIndices;
  16378. return result;
  16379. };
  16380. // calculate area of the contour polygon
  16381. var area = function ( contour ) {
  16382. var n = contour.length;
  16383. var a = 0.0;
  16384. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16385. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16386. }
  16387. return a * 0.5;
  16388. };
  16389. var snip = function ( contour, u, v, w, n, verts ) {
  16390. var p;
  16391. var ax, ay, bx, by;
  16392. var cx, cy, px, py;
  16393. ax = contour[ verts[ u ] ].x;
  16394. ay = contour[ verts[ u ] ].y;
  16395. bx = contour[ verts[ v ] ].x;
  16396. by = contour[ verts[ v ] ].y;
  16397. cx = contour[ verts[ w ] ].x;
  16398. cy = contour[ verts[ w ] ].y;
  16399. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16400. var aX, aY, bX, bY, cX, cY;
  16401. var apx, apy, bpx, bpy, cpx, cpy;
  16402. var cCROSSap, bCROSScp, aCROSSbp;
  16403. aX = cx - bx; aY = cy - by;
  16404. bX = ax - cx; bY = ay - cy;
  16405. cX = bx - ax; cY = by - ay;
  16406. for ( p = 0; p < n; p++ ) {
  16407. if( (p === u) || (p === v) || (p === w) ) continue;
  16408. px = contour[ verts[ p ] ].x
  16409. py = contour[ verts[ p ] ].y
  16410. apx = px - ax; apy = py - ay;
  16411. bpx = px - bx; bpy = py - by;
  16412. cpx = px - cx; cpy = py - cy;
  16413. // see if p is inside triangle abc
  16414. aCROSSbp = aX*bpy - aY*bpx;
  16415. cCROSSap = cX*apy - cY*apx;
  16416. bCROSScp = bX*cpy - bY*cpx;
  16417. if ( (aCROSSbp >= -EPSILON) && (bCROSScp >= -EPSILON) && (cCROSSap >= -EPSILON) ) return false;
  16418. }
  16419. return true;
  16420. };
  16421. namespace.Triangulate = process;
  16422. namespace.Triangulate.area = area;
  16423. return namespace;
  16424. })(THREE.FontUtils);
  16425. // To use the typeface.js face files, hook up the API
  16426. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16427. THREE.typeface_js = self._typeface_js;
  16428. /**
  16429. * @author zz85 / http://www.lab4games.net/zz85/blog
  16430. * Extensible curve object
  16431. *
  16432. * Some common of Curve methods
  16433. * .getPoint(t), getTangent(t)
  16434. * .getPointAt(u), getTagentAt(u)
  16435. * .getPoints(), .getSpacedPoints()
  16436. * .getLength()
  16437. * .updateArcLengths()
  16438. *
  16439. * This following classes subclasses THREE.Curve:
  16440. *
  16441. * -- 2d classes --
  16442. * THREE.LineCurve
  16443. * THREE.QuadraticBezierCurve
  16444. * THREE.CubicBezierCurve
  16445. * THREE.SplineCurve
  16446. * THREE.ArcCurve
  16447. * THREE.EllipseCurve
  16448. *
  16449. * -- 3d classes --
  16450. * THREE.LineCurve3
  16451. * THREE.QuadraticBezierCurve3
  16452. * THREE.CubicBezierCurve3
  16453. * THREE.SplineCurve3
  16454. * THREE.ClosedSplineCurve3
  16455. *
  16456. * A series of curves can be represented as a THREE.CurvePath
  16457. *
  16458. **/
  16459. /**************************************************************
  16460. * Abstract Curve base class
  16461. **************************************************************/
  16462. THREE.Curve = function () {
  16463. };
  16464. // Virtual base class method to overwrite and implement in subclasses
  16465. // - t [0 .. 1]
  16466. THREE.Curve.prototype.getPoint = function ( t ) {
  16467. console.log( "Warning, getPoint() not implemented!" );
  16468. return null;
  16469. };
  16470. // Get point at relative position in curve according to arc length
  16471. // - u [0 .. 1]
  16472. THREE.Curve.prototype.getPointAt = function ( u ) {
  16473. var t = this.getUtoTmapping( u );
  16474. return this.getPoint( t );
  16475. };
  16476. // Get sequence of points using getPoint( t )
  16477. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16478. if ( !divisions ) divisions = 5;
  16479. var d, pts = [];
  16480. for ( d = 0; d <= divisions; d ++ ) {
  16481. pts.push( this.getPoint( d / divisions ) );
  16482. }
  16483. return pts;
  16484. };
  16485. // Get sequence of points using getPointAt( u )
  16486. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16487. if ( !divisions ) divisions = 5;
  16488. var d, pts = [];
  16489. for ( d = 0; d <= divisions; d ++ ) {
  16490. pts.push( this.getPointAt( d / divisions ) );
  16491. }
  16492. return pts;
  16493. };
  16494. // Get total curve arc length
  16495. THREE.Curve.prototype.getLength = function () {
  16496. var lengths = this.getLengths();
  16497. return lengths[ lengths.length - 1 ];
  16498. };
  16499. // Get list of cumulative segment lengths
  16500. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16501. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16502. if ( this.cacheArcLengths
  16503. && ( this.cacheArcLengths.length == divisions + 1 )
  16504. && !this.needsUpdate) {
  16505. //console.log( "cached", this.cacheArcLengths );
  16506. return this.cacheArcLengths;
  16507. }
  16508. this.needsUpdate = false;
  16509. var cache = [];
  16510. var current, last = this.getPoint( 0 );
  16511. var p, sum = 0;
  16512. cache.push( 0 );
  16513. for ( p = 1; p <= divisions; p ++ ) {
  16514. current = this.getPoint ( p / divisions );
  16515. sum += current.distanceTo( last );
  16516. cache.push( sum );
  16517. last = current;
  16518. }
  16519. this.cacheArcLengths = cache;
  16520. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16521. };
  16522. THREE.Curve.prototype.updateArcLengths = function() {
  16523. this.needsUpdate = true;
  16524. this.getLengths();
  16525. };
  16526. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16527. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16528. var arcLengths = this.getLengths();
  16529. var i = 0, il = arcLengths.length;
  16530. var targetArcLength; // The targeted u distance value to get
  16531. if ( distance ) {
  16532. targetArcLength = distance;
  16533. } else {
  16534. targetArcLength = u * arcLengths[ il - 1 ];
  16535. }
  16536. //var time = Date.now();
  16537. // binary search for the index with largest value smaller than target u distance
  16538. var low = 0, high = il - 1, comparison;
  16539. while ( low <= high ) {
  16540. 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
  16541. comparison = arcLengths[ i ] - targetArcLength;
  16542. if ( comparison < 0 ) {
  16543. low = i + 1;
  16544. continue;
  16545. } else if ( comparison > 0 ) {
  16546. high = i - 1;
  16547. continue;
  16548. } else {
  16549. high = i;
  16550. break;
  16551. // DONE
  16552. }
  16553. }
  16554. i = high;
  16555. //console.log('b' , i, low, high, Date.now()- time);
  16556. if ( arcLengths[ i ] == targetArcLength ) {
  16557. var t = i / ( il - 1 );
  16558. return t;
  16559. }
  16560. // we could get finer grain at lengths, or use simple interpolatation between two points
  16561. var lengthBefore = arcLengths[ i ];
  16562. var lengthAfter = arcLengths[ i + 1 ];
  16563. var segmentLength = lengthAfter - lengthBefore;
  16564. // determine where we are between the 'before' and 'after' points
  16565. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16566. // add that fractional amount to t
  16567. var t = ( i + segmentFraction ) / ( il -1 );
  16568. return t;
  16569. };
  16570. // Returns a unit vector tangent at t
  16571. // In case any sub curve does not implement its tangent derivation,
  16572. // 2 points a small delta apart will be used to find its gradient
  16573. // which seems to give a reasonable approximation
  16574. THREE.Curve.prototype.getTangent = function( t ) {
  16575. var delta = 0.0001;
  16576. var t1 = t - delta;
  16577. var t2 = t + delta;
  16578. // Capping in case of danger
  16579. if ( t1 < 0 ) t1 = 0;
  16580. if ( t2 > 1 ) t2 = 1;
  16581. var pt1 = this.getPoint( t1 );
  16582. var pt2 = this.getPoint( t2 );
  16583. var vec = pt2.clone().sub(pt1);
  16584. return vec.normalize();
  16585. };
  16586. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16587. var t = this.getUtoTmapping( u );
  16588. return this.getTangent( t );
  16589. };
  16590. /**************************************************************
  16591. * Utils
  16592. **************************************************************/
  16593. THREE.Curve.Utils = {
  16594. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16595. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16596. },
  16597. // Puay Bing, thanks for helping with this derivative!
  16598. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16599. return -3 * p0 * (1 - t) * (1 - t) +
  16600. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16601. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16602. 3 * t * t * p3;
  16603. },
  16604. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16605. // To check if my formulas are correct
  16606. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16607. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16608. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16609. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16610. return h00 + h10 + h01 + h11;
  16611. },
  16612. // Catmull-Rom
  16613. interpolate: function( p0, p1, p2, p3, t ) {
  16614. var v0 = ( p2 - p0 ) * 0.5;
  16615. var v1 = ( p3 - p1 ) * 0.5;
  16616. var t2 = t * t;
  16617. var t3 = t * t2;
  16618. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16619. }
  16620. };
  16621. // TODO: Transformation for Curves?
  16622. /**************************************************************
  16623. * 3D Curves
  16624. **************************************************************/
  16625. // A Factory method for creating new curve subclasses
  16626. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16627. constructor.prototype = Object.create( THREE.Curve.prototype );
  16628. constructor.prototype.getPoint = getPointFunc;
  16629. return constructor;
  16630. };
  16631. /**
  16632. * @author zz85 / http://www.lab4games.net/zz85/blog
  16633. *
  16634. **/
  16635. /**************************************************************
  16636. * Curved Path - a curve path is simply a array of connected
  16637. * curves, but retains the api of a curve
  16638. **************************************************************/
  16639. THREE.CurvePath = function () {
  16640. this.curves = [];
  16641. this.bends = [];
  16642. this.autoClose = false; // Automatically closes the path
  16643. };
  16644. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16645. THREE.CurvePath.prototype.add = function ( curve ) {
  16646. this.curves.push( curve );
  16647. };
  16648. THREE.CurvePath.prototype.checkConnection = function() {
  16649. // TODO
  16650. // If the ending of curve is not connected to the starting
  16651. // or the next curve, then, this is not a real path
  16652. };
  16653. THREE.CurvePath.prototype.closePath = function() {
  16654. // TODO Test
  16655. // and verify for vector3 (needs to implement equals)
  16656. // Add a line curve if start and end of lines are not connected
  16657. var startPoint = this.curves[0].getPoint(0);
  16658. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16659. if (!startPoint.equals(endPoint)) {
  16660. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16661. }
  16662. };
  16663. // To get accurate point with reference to
  16664. // entire path distance at time t,
  16665. // following has to be done:
  16666. // 1. Length of each sub path have to be known
  16667. // 2. Locate and identify type of curve
  16668. // 3. Get t for the curve
  16669. // 4. Return curve.getPointAt(t')
  16670. THREE.CurvePath.prototype.getPoint = function( t ) {
  16671. var d = t * this.getLength();
  16672. var curveLengths = this.getCurveLengths();
  16673. var i = 0, diff, curve;
  16674. // To think about boundaries points.
  16675. while ( i < curveLengths.length ) {
  16676. if ( curveLengths[ i ] >= d ) {
  16677. diff = curveLengths[ i ] - d;
  16678. curve = this.curves[ i ];
  16679. var u = 1 - diff / curve.getLength();
  16680. return curve.getPointAt( u );
  16681. break;
  16682. }
  16683. i ++;
  16684. }
  16685. return null;
  16686. // loop where sum != 0, sum > d , sum+1 <d
  16687. };
  16688. /*
  16689. THREE.CurvePath.prototype.getTangent = function( t ) {
  16690. };*/
  16691. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16692. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16693. // getPoint() depends on getLength
  16694. THREE.CurvePath.prototype.getLength = function() {
  16695. var lens = this.getCurveLengths();
  16696. return lens[ lens.length - 1 ];
  16697. };
  16698. // Compute lengths and cache them
  16699. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16700. THREE.CurvePath.prototype.getCurveLengths = function() {
  16701. // We use cache values if curves and cache array are same length
  16702. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16703. return this.cacheLengths;
  16704. };
  16705. // Get length of subsurve
  16706. // Push sums into cached array
  16707. var lengths = [], sums = 0;
  16708. var i, il = this.curves.length;
  16709. for ( i = 0; i < il; i ++ ) {
  16710. sums += this.curves[ i ].getLength();
  16711. lengths.push( sums );
  16712. }
  16713. this.cacheLengths = lengths;
  16714. return lengths;
  16715. };
  16716. // Returns min and max coordinates, as well as centroid
  16717. THREE.CurvePath.prototype.getBoundingBox = function () {
  16718. var points = this.getPoints();
  16719. var maxX, maxY, maxZ;
  16720. var minX, minY, minZ;
  16721. maxX = maxY = Number.NEGATIVE_INFINITY;
  16722. minX = minY = Number.POSITIVE_INFINITY;
  16723. var p, i, il, sum;
  16724. var v3 = points[0] instanceof THREE.Vector3;
  16725. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16726. for ( i = 0, il = points.length; i < il; i ++ ) {
  16727. p = points[ i ];
  16728. if ( p.x > maxX ) maxX = p.x;
  16729. else if ( p.x < minX ) minX = p.x;
  16730. if ( p.y > maxY ) maxY = p.y;
  16731. else if ( p.y < minY ) minY = p.y;
  16732. if ( v3 ) {
  16733. if ( p.z > maxZ ) maxZ = p.z;
  16734. else if ( p.z < minZ ) minZ = p.z;
  16735. }
  16736. sum.add( p );
  16737. }
  16738. var ret = {
  16739. minX: minX,
  16740. minY: minY,
  16741. maxX: maxX,
  16742. maxY: maxY,
  16743. centroid: sum.divideScalar( il )
  16744. };
  16745. if ( v3 ) {
  16746. ret.maxZ = maxZ;
  16747. ret.minZ = minZ;
  16748. }
  16749. return ret;
  16750. };
  16751. /**************************************************************
  16752. * Create Geometries Helpers
  16753. **************************************************************/
  16754. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16755. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16756. var pts = this.getPoints( divisions, true );
  16757. return this.createGeometry( pts );
  16758. };
  16759. // Generate geometry from equidistance sampling along the path
  16760. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16761. var pts = this.getSpacedPoints( divisions, true );
  16762. return this.createGeometry( pts );
  16763. };
  16764. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16765. var geometry = new THREE.Geometry();
  16766. for ( var i = 0; i < points.length; i ++ ) {
  16767. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16768. }
  16769. return geometry;
  16770. };
  16771. /**************************************************************
  16772. * Bend / Wrap Helper Methods
  16773. **************************************************************/
  16774. // Wrap path / Bend modifiers?
  16775. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16776. this.bends.push( bendpath );
  16777. };
  16778. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16779. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16780. var i, il;
  16781. if ( !bends ) {
  16782. bends = this.bends;
  16783. }
  16784. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16785. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16786. }
  16787. return oldPts;
  16788. };
  16789. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16790. var oldPts = this.getSpacedPoints( segments );
  16791. var i, il;
  16792. if ( !bends ) {
  16793. bends = this.bends;
  16794. }
  16795. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16796. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16797. }
  16798. return oldPts;
  16799. };
  16800. // This returns getPoints() bend/wrapped around the contour of a path.
  16801. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16802. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16803. var bounds = this.getBoundingBox();
  16804. var i, il, p, oldX, oldY, xNorm;
  16805. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16806. p = oldPts[ i ];
  16807. oldX = p.x;
  16808. oldY = p.y;
  16809. xNorm = oldX / bounds.maxX;
  16810. // If using actual distance, for length > path, requires line extrusions
  16811. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16812. xNorm = path.getUtoTmapping( xNorm, oldX );
  16813. // check for out of bounds?
  16814. var pathPt = path.getPoint( xNorm );
  16815. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  16816. p.x = pathPt.x + normal.x;
  16817. p.y = pathPt.y + normal.y;
  16818. }
  16819. return oldPts;
  16820. };
  16821. /**
  16822. * @author alteredq / http://alteredqualia.com/
  16823. */
  16824. THREE.Gyroscope = function () {
  16825. THREE.Object3D.call( this );
  16826. };
  16827. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16828. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16829. this.matrixAutoUpdate && this.updateMatrix();
  16830. // update matrixWorld
  16831. if ( this.matrixWorldNeedsUpdate || force ) {
  16832. if ( this.parent ) {
  16833. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16834. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  16835. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  16836. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  16837. } else {
  16838. this.matrixWorld.copy( this.matrix );
  16839. }
  16840. this.matrixWorldNeedsUpdate = false;
  16841. force = true;
  16842. }
  16843. // update children
  16844. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16845. this.children[ i ].updateMatrixWorld( force );
  16846. }
  16847. };
  16848. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16849. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16850. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  16851. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  16852. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16853. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16854. /**
  16855. * @author zz85 / http://www.lab4games.net/zz85/blog
  16856. * Creates free form 2d path using series of points, lines or curves.
  16857. *
  16858. **/
  16859. THREE.Path = function ( points ) {
  16860. THREE.CurvePath.call(this);
  16861. this.actions = [];
  16862. if ( points ) {
  16863. this.fromPoints( points );
  16864. }
  16865. };
  16866. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16867. THREE.PathActions = {
  16868. MOVE_TO: 'moveTo',
  16869. LINE_TO: 'lineTo',
  16870. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16871. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16872. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16873. ARC: 'arc', // Circle
  16874. ELLIPSE: 'ellipse'
  16875. };
  16876. // TODO Clean up PATH API
  16877. // Create path using straight lines to connect all points
  16878. // - vectors: array of Vector2
  16879. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16880. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16881. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16882. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16883. };
  16884. };
  16885. // startPath() endPath()?
  16886. THREE.Path.prototype.moveTo = function ( x, y ) {
  16887. var args = Array.prototype.slice.call( arguments );
  16888. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16889. };
  16890. THREE.Path.prototype.lineTo = function ( x, y ) {
  16891. var args = Array.prototype.slice.call( arguments );
  16892. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16893. var x0 = lastargs[ lastargs.length - 2 ];
  16894. var y0 = lastargs[ lastargs.length - 1 ];
  16895. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16896. this.curves.push( curve );
  16897. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16898. };
  16899. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16900. var args = Array.prototype.slice.call( arguments );
  16901. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16902. var x0 = lastargs[ lastargs.length - 2 ];
  16903. var y0 = lastargs[ lastargs.length - 1 ];
  16904. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16905. new THREE.Vector2( aCPx, aCPy ),
  16906. new THREE.Vector2( aX, aY ) );
  16907. this.curves.push( curve );
  16908. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16909. };
  16910. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16911. aCP2x, aCP2y,
  16912. aX, aY ) {
  16913. var args = Array.prototype.slice.call( arguments );
  16914. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16915. var x0 = lastargs[ lastargs.length - 2 ];
  16916. var y0 = lastargs[ lastargs.length - 1 ];
  16917. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16918. new THREE.Vector2( aCP1x, aCP1y ),
  16919. new THREE.Vector2( aCP2x, aCP2y ),
  16920. new THREE.Vector2( aX, aY ) );
  16921. this.curves.push( curve );
  16922. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16923. };
  16924. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16925. var args = Array.prototype.slice.call( arguments );
  16926. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16927. var x0 = lastargs[ lastargs.length - 2 ];
  16928. var y0 = lastargs[ lastargs.length - 1 ];
  16929. //---
  16930. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16931. Array.prototype.push.apply( npts, pts );
  16932. var curve = new THREE.SplineCurve( npts );
  16933. this.curves.push( curve );
  16934. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16935. };
  16936. // FUTURE: Change the API or follow canvas API?
  16937. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16938. aStartAngle, aEndAngle, aClockwise ) {
  16939. var lastargs = this.actions[ this.actions.length - 1].args;
  16940. var x0 = lastargs[ lastargs.length - 2 ];
  16941. var y0 = lastargs[ lastargs.length - 1 ];
  16942. this.absarc(aX + x0, aY + y0, aRadius,
  16943. aStartAngle, aEndAngle, aClockwise );
  16944. };
  16945. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16946. aStartAngle, aEndAngle, aClockwise ) {
  16947. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16948. };
  16949. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16950. aStartAngle, aEndAngle, aClockwise ) {
  16951. var lastargs = this.actions[ this.actions.length - 1].args;
  16952. var x0 = lastargs[ lastargs.length - 2 ];
  16953. var y0 = lastargs[ lastargs.length - 1 ];
  16954. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16955. aStartAngle, aEndAngle, aClockwise );
  16956. };
  16957. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16958. aStartAngle, aEndAngle, aClockwise ) {
  16959. var args = Array.prototype.slice.call( arguments );
  16960. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16961. aStartAngle, aEndAngle, aClockwise );
  16962. this.curves.push( curve );
  16963. var lastPoint = curve.getPoint(1);
  16964. args.push(lastPoint.x);
  16965. args.push(lastPoint.y);
  16966. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16967. };
  16968. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16969. if ( ! divisions ) divisions = 40;
  16970. var points = [];
  16971. for ( var i = 0; i < divisions; i ++ ) {
  16972. points.push( this.getPoint( i / divisions ) );
  16973. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16974. }
  16975. // if ( closedPath ) {
  16976. //
  16977. // points.push( points[ 0 ] );
  16978. //
  16979. // }
  16980. return points;
  16981. };
  16982. /* Return an array of vectors based on contour of the path */
  16983. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16984. if (this.useSpacedPoints) {
  16985. console.log('tata');
  16986. return this.getSpacedPoints( divisions, closedPath );
  16987. }
  16988. divisions = divisions || 12;
  16989. var points = [];
  16990. var i, il, item, action, args;
  16991. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16992. laste, j,
  16993. t, tx, ty;
  16994. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16995. item = this.actions[ i ];
  16996. action = item.action;
  16997. args = item.args;
  16998. switch( action ) {
  16999. case THREE.PathActions.MOVE_TO:
  17000. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17001. break;
  17002. case THREE.PathActions.LINE_TO:
  17003. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17004. break;
  17005. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17006. cpx = args[ 2 ];
  17007. cpy = args[ 3 ];
  17008. cpx1 = args[ 0 ];
  17009. cpy1 = args[ 1 ];
  17010. if ( points.length > 0 ) {
  17011. laste = points[ points.length - 1 ];
  17012. cpx0 = laste.x;
  17013. cpy0 = laste.y;
  17014. } else {
  17015. laste = this.actions[ i - 1 ].args;
  17016. cpx0 = laste[ laste.length - 2 ];
  17017. cpy0 = laste[ laste.length - 1 ];
  17018. }
  17019. for ( j = 1; j <= divisions; j ++ ) {
  17020. t = j / divisions;
  17021. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17022. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17023. points.push( new THREE.Vector2( tx, ty ) );
  17024. }
  17025. break;
  17026. case THREE.PathActions.BEZIER_CURVE_TO:
  17027. cpx = args[ 4 ];
  17028. cpy = args[ 5 ];
  17029. cpx1 = args[ 0 ];
  17030. cpy1 = args[ 1 ];
  17031. cpx2 = args[ 2 ];
  17032. cpy2 = args[ 3 ];
  17033. if ( points.length > 0 ) {
  17034. laste = points[ points.length - 1 ];
  17035. cpx0 = laste.x;
  17036. cpy0 = laste.y;
  17037. } else {
  17038. laste = this.actions[ i - 1 ].args;
  17039. cpx0 = laste[ laste.length - 2 ];
  17040. cpy0 = laste[ laste.length - 1 ];
  17041. }
  17042. for ( j = 1; j <= divisions; j ++ ) {
  17043. t = j / divisions;
  17044. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17045. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17046. points.push( new THREE.Vector2( tx, ty ) );
  17047. }
  17048. break;
  17049. case THREE.PathActions.CSPLINE_THRU:
  17050. laste = this.actions[ i - 1 ].args;
  17051. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17052. var spts = [ last ];
  17053. var n = divisions * args[ 0 ].length;
  17054. spts = spts.concat( args[ 0 ] );
  17055. var spline = new THREE.SplineCurve( spts );
  17056. for ( j = 1; j <= n; j ++ ) {
  17057. points.push( spline.getPointAt( j / n ) ) ;
  17058. }
  17059. break;
  17060. case THREE.PathActions.ARC:
  17061. var aX = args[ 0 ], aY = args[ 1 ],
  17062. aRadius = args[ 2 ],
  17063. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17064. aClockwise = !!args[ 5 ];
  17065. var deltaAngle = aEndAngle - aStartAngle;
  17066. var angle;
  17067. var tdivisions = divisions * 2;
  17068. for ( j = 1; j <= tdivisions; j ++ ) {
  17069. t = j / tdivisions;
  17070. if ( ! aClockwise ) {
  17071. t = 1 - t;
  17072. }
  17073. angle = aStartAngle + t * deltaAngle;
  17074. tx = aX + aRadius * Math.cos( angle );
  17075. ty = aY + aRadius * Math.sin( angle );
  17076. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17077. points.push( new THREE.Vector2( tx, ty ) );
  17078. }
  17079. //console.log(points);
  17080. break;
  17081. case THREE.PathActions.ELLIPSE:
  17082. var aX = args[ 0 ], aY = args[ 1 ],
  17083. xRadius = args[ 2 ],
  17084. yRadius = args[ 3 ],
  17085. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17086. aClockwise = !!args[ 6 ];
  17087. var deltaAngle = aEndAngle - aStartAngle;
  17088. var angle;
  17089. var tdivisions = divisions * 2;
  17090. for ( j = 1; j <= tdivisions; j ++ ) {
  17091. t = j / tdivisions;
  17092. if ( ! aClockwise ) {
  17093. t = 1 - t;
  17094. }
  17095. angle = aStartAngle + t * deltaAngle;
  17096. tx = aX + xRadius * Math.cos( angle );
  17097. ty = aY + yRadius * Math.sin( angle );
  17098. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17099. points.push( new THREE.Vector2( tx, ty ) );
  17100. }
  17101. //console.log(points);
  17102. break;
  17103. } // end switch
  17104. }
  17105. // Normalize to remove the closing point by default.
  17106. var lastPoint = points[ points.length - 1];
  17107. var EPSILON = 0.0000000001;
  17108. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17109. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17110. points.splice( points.length - 1, 1);
  17111. if ( closedPath ) {
  17112. points.push( points[ 0 ] );
  17113. }
  17114. return points;
  17115. };
  17116. // Breaks path into shapes
  17117. THREE.Path.prototype.toShapes = function( isCCW ) {
  17118. var i, il, item, action, args;
  17119. var subPaths = [], lastPath = new THREE.Path();
  17120. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17121. item = this.actions[ i ];
  17122. args = item.args;
  17123. action = item.action;
  17124. if ( action == THREE.PathActions.MOVE_TO ) {
  17125. if ( lastPath.actions.length != 0 ) {
  17126. subPaths.push( lastPath );
  17127. lastPath = new THREE.Path();
  17128. }
  17129. }
  17130. lastPath[ action ].apply( lastPath, args );
  17131. }
  17132. if ( lastPath.actions.length != 0 ) {
  17133. subPaths.push( lastPath );
  17134. }
  17135. // console.log(subPaths);
  17136. if ( subPaths.length == 0 ) return [];
  17137. var solid, tmpPath, tmpShape, shapes = [];
  17138. if ( subPaths.length == 1) {
  17139. tmpPath = subPaths[0];
  17140. tmpShape = new THREE.Shape();
  17141. tmpShape.actions = tmpPath.actions;
  17142. tmpShape.curves = tmpPath.curves;
  17143. shapes.push( tmpShape );
  17144. return shapes;
  17145. }
  17146. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17147. holesFirst = isCCW ? !holesFirst : holesFirst;
  17148. // console.log("Holes first", holesFirst);
  17149. if ( holesFirst ) {
  17150. tmpShape = new THREE.Shape();
  17151. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17152. tmpPath = subPaths[ i ];
  17153. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17154. solid = isCCW ? !solid : solid;
  17155. if ( solid ) {
  17156. tmpShape.actions = tmpPath.actions;
  17157. tmpShape.curves = tmpPath.curves;
  17158. shapes.push( tmpShape );
  17159. tmpShape = new THREE.Shape();
  17160. //console.log('cw', i);
  17161. } else {
  17162. tmpShape.holes.push( tmpPath );
  17163. //console.log('ccw', i);
  17164. }
  17165. }
  17166. } else {
  17167. // Shapes first
  17168. tmpShape = undefined;
  17169. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17170. tmpPath = subPaths[ i ];
  17171. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17172. solid = isCCW ? !solid : solid;
  17173. if ( solid ) {
  17174. if ( tmpShape ) shapes.push( tmpShape );
  17175. tmpShape = new THREE.Shape();
  17176. tmpShape.actions = tmpPath.actions;
  17177. tmpShape.curves = tmpPath.curves;
  17178. } else {
  17179. tmpShape.holes.push( tmpPath );
  17180. }
  17181. }
  17182. shapes.push( tmpShape );
  17183. }
  17184. //console.log("shape", shapes);
  17185. return shapes;
  17186. };
  17187. /**
  17188. * @author zz85 / http://www.lab4games.net/zz85/blog
  17189. * Defines a 2d shape plane using paths.
  17190. **/
  17191. // STEP 1 Create a path.
  17192. // STEP 2 Turn path into shape.
  17193. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17194. // STEP 3a - Extract points from each shape, turn to vertices
  17195. // STEP 3b - Triangulate each shape, add faces.
  17196. THREE.Shape = function () {
  17197. THREE.Path.apply( this, arguments );
  17198. this.holes = [];
  17199. };
  17200. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17201. // Convenience method to return ExtrudeGeometry
  17202. THREE.Shape.prototype.extrude = function ( options ) {
  17203. var extruded = new THREE.ExtrudeGeometry( this, options );
  17204. return extruded;
  17205. };
  17206. // Convenience method to return ShapeGeometry
  17207. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17208. var geometry = new THREE.ShapeGeometry( this, options );
  17209. return geometry;
  17210. };
  17211. // Get points of holes
  17212. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17213. var i, il = this.holes.length, holesPts = [];
  17214. for ( i = 0; i < il; i ++ ) {
  17215. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17216. }
  17217. return holesPts;
  17218. };
  17219. // Get points of holes (spaced by regular distance)
  17220. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17221. var i, il = this.holes.length, holesPts = [];
  17222. for ( i = 0; i < il; i ++ ) {
  17223. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17224. }
  17225. return holesPts;
  17226. };
  17227. // Get points of shape and holes (keypoints based on segments parameter)
  17228. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17229. return {
  17230. shape: this.getTransformedPoints( divisions ),
  17231. holes: this.getPointsHoles( divisions )
  17232. };
  17233. };
  17234. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17235. if (this.useSpacedPoints) {
  17236. return this.extractAllSpacedPoints(divisions);
  17237. }
  17238. return this.extractAllPoints(divisions);
  17239. };
  17240. //
  17241. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17242. //
  17243. // return {
  17244. //
  17245. // shape: this.transform( bend, divisions ),
  17246. // holes: this.getPointsHoles( divisions, bend )
  17247. //
  17248. // };
  17249. //
  17250. // };
  17251. // Get points of shape and holes (spaced by regular distance)
  17252. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17253. return {
  17254. shape: this.getTransformedSpacedPoints( divisions ),
  17255. holes: this.getSpacedPointsHoles( divisions )
  17256. };
  17257. };
  17258. /**************************************************************
  17259. * Utils
  17260. **************************************************************/
  17261. THREE.Shape.Utils = {
  17262. /*
  17263. contour - array of vector2 for contour
  17264. holes - array of array of vector2
  17265. */
  17266. removeHoles: function ( contour, holes ) {
  17267. var shape = contour.concat(); // work on this shape
  17268. var allpoints = shape.concat();
  17269. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17270. var prevShapeVert, nextShapeVert,
  17271. prevHoleVert, nextHoleVert,
  17272. holeIndex, shapeIndex,
  17273. shapeId, shapeGroup,
  17274. h, h2,
  17275. hole, shortest, d,
  17276. p, pts1, pts2,
  17277. tmpShape1, tmpShape2,
  17278. tmpHole1, tmpHole2,
  17279. verts = [];
  17280. for ( h = 0; h < holes.length; h ++ ) {
  17281. hole = holes[ h ];
  17282. /*
  17283. shapeholes[ h ].concat(); // preserves original
  17284. holes.push( hole );
  17285. */
  17286. Array.prototype.push.apply( allpoints, hole );
  17287. shortest = Number.POSITIVE_INFINITY;
  17288. // Find the shortest pair of pts between shape and hole
  17289. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17290. // Using distanceToSquared() intead of distanceTo() should speed a little
  17291. // since running square roots operations are reduced.
  17292. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17293. pts1 = hole[ h2 ];
  17294. var dist = [];
  17295. for ( p = 0; p < shape.length; p++ ) {
  17296. pts2 = shape[ p ];
  17297. d = pts1.distanceToSquared( pts2 );
  17298. dist.push( d );
  17299. if ( d < shortest ) {
  17300. shortest = d;
  17301. holeIndex = h2;
  17302. shapeIndex = p;
  17303. }
  17304. }
  17305. }
  17306. //console.log("shortest", shortest, dist);
  17307. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17308. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17309. var areaapts = [
  17310. hole[ holeIndex ],
  17311. shape[ shapeIndex ],
  17312. shape[ prevShapeVert ]
  17313. ];
  17314. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17315. var areabpts = [
  17316. hole[ holeIndex ],
  17317. hole[ prevHoleVert ],
  17318. shape[ shapeIndex ]
  17319. ];
  17320. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17321. var shapeOffset = 1;
  17322. var holeOffset = -1;
  17323. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17324. shapeIndex += shapeOffset;
  17325. holeIndex += holeOffset;
  17326. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17327. shapeIndex %= shape.length;
  17328. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17329. holeIndex %= hole.length;
  17330. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17331. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17332. areaapts = [
  17333. hole[ holeIndex ],
  17334. shape[ shapeIndex ],
  17335. shape[ prevShapeVert ]
  17336. ];
  17337. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17338. areabpts = [
  17339. hole[ holeIndex ],
  17340. hole[ prevHoleVert ],
  17341. shape[ shapeIndex ]
  17342. ];
  17343. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17344. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17345. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17346. // In case areas are not correct.
  17347. //console.log("USE THIS");
  17348. shapeIndex = oldShapeIndex;
  17349. holeIndex = oldHoleIndex ;
  17350. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17351. shapeIndex %= shape.length;
  17352. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17353. holeIndex %= hole.length;
  17354. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17355. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17356. } else {
  17357. //console.log("USE THAT ")
  17358. }
  17359. tmpShape1 = shape.slice( 0, shapeIndex );
  17360. tmpShape2 = shape.slice( shapeIndex );
  17361. tmpHole1 = hole.slice( holeIndex );
  17362. tmpHole2 = hole.slice( 0, holeIndex );
  17363. // Should check orders here again?
  17364. var trianglea = [
  17365. hole[ holeIndex ],
  17366. shape[ shapeIndex ],
  17367. shape[ prevShapeVert ]
  17368. ];
  17369. var triangleb = [
  17370. hole[ holeIndex ] ,
  17371. hole[ prevHoleVert ],
  17372. shape[ shapeIndex ]
  17373. ];
  17374. verts.push( trianglea );
  17375. verts.push( triangleb );
  17376. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17377. }
  17378. return {
  17379. shape:shape, /* shape with no holes */
  17380. isolatedPts: verts, /* isolated faces */
  17381. allpoints: allpoints
  17382. }
  17383. },
  17384. triangulateShape: function ( contour, holes ) {
  17385. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17386. var shape = shapeWithoutHoles.shape,
  17387. allpoints = shapeWithoutHoles.allpoints,
  17388. isolatedPts = shapeWithoutHoles.isolatedPts;
  17389. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17390. // 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.
  17391. //console.log( "triangles",triangles, triangles.length );
  17392. //console.log( "allpoints",allpoints, allpoints.length );
  17393. var i, il, f, face,
  17394. key, index,
  17395. allPointsMap = {},
  17396. isolatedPointsMap = {};
  17397. // prepare all points map
  17398. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17399. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17400. if ( allPointsMap[ key ] !== undefined ) {
  17401. console.log( "Duplicate point", key );
  17402. }
  17403. allPointsMap[ key ] = i;
  17404. }
  17405. // check all face vertices against all points map
  17406. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17407. face = triangles[ i ];
  17408. for ( f = 0; f < 3; f ++ ) {
  17409. key = face[ f ].x + ":" + face[ f ].y;
  17410. index = allPointsMap[ key ];
  17411. if ( index !== undefined ) {
  17412. face[ f ] = index;
  17413. }
  17414. }
  17415. }
  17416. // check isolated points vertices against all points map
  17417. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17418. face = isolatedPts[ i ];
  17419. for ( f = 0; f < 3; f ++ ) {
  17420. key = face[ f ].x + ":" + face[ f ].y;
  17421. index = allPointsMap[ key ];
  17422. if ( index !== undefined ) {
  17423. face[ f ] = index;
  17424. }
  17425. }
  17426. }
  17427. return triangles.concat( isolatedPts );
  17428. }, // end triangulate shapes
  17429. /*
  17430. triangulate2 : function( pts, holes ) {
  17431. // For use with Poly2Tri.js
  17432. var allpts = pts.concat();
  17433. var shape = [];
  17434. for (var p in pts) {
  17435. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17436. }
  17437. var swctx = new js.poly2tri.SweepContext(shape);
  17438. for (var h in holes) {
  17439. var aHole = holes[h];
  17440. var newHole = []
  17441. for (i in aHole) {
  17442. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17443. allpts.push(aHole[i]);
  17444. }
  17445. swctx.AddHole(newHole);
  17446. }
  17447. var find;
  17448. var findIndexForPt = function (pt) {
  17449. find = new THREE.Vector2(pt.x, pt.y);
  17450. var p;
  17451. for (p=0, pl = allpts.length; p<pl; p++) {
  17452. if (allpts[p].equals(find)) return p;
  17453. }
  17454. return -1;
  17455. };
  17456. // triangulate
  17457. js.poly2tri.sweep.Triangulate(swctx);
  17458. var triangles = swctx.GetTriangles();
  17459. var tr ;
  17460. var facesPts = [];
  17461. for (var t in triangles) {
  17462. tr = triangles[t];
  17463. facesPts.push([
  17464. findIndexForPt(tr.GetPoint(0)),
  17465. findIndexForPt(tr.GetPoint(1)),
  17466. findIndexForPt(tr.GetPoint(2))
  17467. ]);
  17468. }
  17469. // console.log(facesPts);
  17470. // console.log("triangles", triangles.length, triangles);
  17471. // Returns array of faces with 3 element each
  17472. return facesPts;
  17473. },
  17474. */
  17475. isClockWise: function ( pts ) {
  17476. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17477. },
  17478. // Bezier Curves formulas obtained from
  17479. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17480. // Quad Bezier Functions
  17481. b2p0: function ( t, p ) {
  17482. var k = 1 - t;
  17483. return k * k * p;
  17484. },
  17485. b2p1: function ( t, p ) {
  17486. return 2 * ( 1 - t ) * t * p;
  17487. },
  17488. b2p2: function ( t, p ) {
  17489. return t * t * p;
  17490. },
  17491. b2: function ( t, p0, p1, p2 ) {
  17492. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17493. },
  17494. // Cubic Bezier Functions
  17495. b3p0: function ( t, p ) {
  17496. var k = 1 - t;
  17497. return k * k * k * p;
  17498. },
  17499. b3p1: function ( t, p ) {
  17500. var k = 1 - t;
  17501. return 3 * k * k * t * p;
  17502. },
  17503. b3p2: function ( t, p ) {
  17504. var k = 1 - t;
  17505. return 3 * k * t * t * p;
  17506. },
  17507. b3p3: function ( t, p ) {
  17508. return t * t * t * p;
  17509. },
  17510. b3: function ( t, p0, p1, p2, p3 ) {
  17511. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17512. }
  17513. };
  17514. /**************************************************************
  17515. * Line
  17516. **************************************************************/
  17517. THREE.LineCurve = function ( v1, v2 ) {
  17518. this.v1 = v1;
  17519. this.v2 = v2;
  17520. };
  17521. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17522. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17523. var point = this.v2.clone().sub(this.v1);
  17524. point.multiplyScalar( t ).add( this.v1 );
  17525. return point;
  17526. };
  17527. // Line curve is linear, so we can overwrite default getPointAt
  17528. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17529. return this.getPoint( u );
  17530. };
  17531. THREE.LineCurve.prototype.getTangent = function( t ) {
  17532. var tangent = this.v2.clone().sub(this.v1);
  17533. return tangent.normalize();
  17534. };
  17535. /**************************************************************
  17536. * Quadratic Bezier curve
  17537. **************************************************************/
  17538. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17539. this.v0 = v0;
  17540. this.v1 = v1;
  17541. this.v2 = v2;
  17542. };
  17543. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17544. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17545. var tx, ty;
  17546. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17547. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17548. return new THREE.Vector2( tx, ty );
  17549. };
  17550. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17551. var tx, ty;
  17552. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17553. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17554. // returns unit vector
  17555. var tangent = new THREE.Vector2( tx, ty );
  17556. tangent.normalize();
  17557. return tangent;
  17558. };
  17559. /**************************************************************
  17560. * Cubic Bezier curve
  17561. **************************************************************/
  17562. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17563. this.v0 = v0;
  17564. this.v1 = v1;
  17565. this.v2 = v2;
  17566. this.v3 = v3;
  17567. };
  17568. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17569. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  17570. var tx, ty;
  17571. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17572. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17573. return new THREE.Vector2( tx, ty );
  17574. };
  17575. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  17576. var tx, ty;
  17577. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17578. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17579. var tangent = new THREE.Vector2( tx, ty );
  17580. tangent.normalize();
  17581. return tangent;
  17582. };
  17583. /**************************************************************
  17584. * Spline curve
  17585. **************************************************************/
  17586. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  17587. this.points = (points == undefined) ? [] : points;
  17588. };
  17589. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  17590. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  17591. var v = new THREE.Vector2();
  17592. var c = [];
  17593. var points = this.points, point, intPoint, weight;
  17594. point = ( points.length - 1 ) * t;
  17595. intPoint = Math.floor( point );
  17596. weight = point - intPoint;
  17597. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17598. c[ 1 ] = intPoint;
  17599. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  17600. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  17601. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17602. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17603. return v;
  17604. };
  17605. /**************************************************************
  17606. * Ellipse curve
  17607. **************************************************************/
  17608. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  17609. this.aX = aX;
  17610. this.aY = aY;
  17611. this.xRadius = xRadius;
  17612. this.yRadius = yRadius;
  17613. this.aStartAngle = aStartAngle;
  17614. this.aEndAngle = aEndAngle;
  17615. this.aClockwise = aClockwise;
  17616. };
  17617. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  17618. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  17619. var angle;
  17620. var deltaAngle = this.aEndAngle - this.aStartAngle;
  17621. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  17622. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  17623. if ( this.aClockwise === true ) {
  17624. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  17625. } else {
  17626. angle = this.aStartAngle + t * deltaAngle;
  17627. }
  17628. var tx = this.aX + this.xRadius * Math.cos( angle );
  17629. var ty = this.aY + this.yRadius * Math.sin( angle );
  17630. return new THREE.Vector2( tx, ty );
  17631. };
  17632. /**************************************************************
  17633. * Arc curve
  17634. **************************************************************/
  17635. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17636. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  17637. };
  17638. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  17639. /**************************************************************
  17640. * Line3D
  17641. **************************************************************/
  17642. THREE.LineCurve3 = THREE.Curve.create(
  17643. function ( v1, v2 ) {
  17644. this.v1 = v1;
  17645. this.v2 = v2;
  17646. },
  17647. function ( t ) {
  17648. var r = new THREE.Vector3();
  17649. r.subVectors( this.v2, this.v1 ); // diff
  17650. r.multiplyScalar( t );
  17651. r.add( this.v1 );
  17652. return r;
  17653. }
  17654. );
  17655. /**************************************************************
  17656. * Quadratic Bezier 3D curve
  17657. **************************************************************/
  17658. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  17659. function ( v0, v1, v2 ) {
  17660. this.v0 = v0;
  17661. this.v1 = v1;
  17662. this.v2 = v2;
  17663. },
  17664. function ( t ) {
  17665. var tx, ty, tz;
  17666. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17667. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17668. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  17669. return new THREE.Vector3( tx, ty, tz );
  17670. }
  17671. );
  17672. /**************************************************************
  17673. * Cubic Bezier 3D curve
  17674. **************************************************************/
  17675. THREE.CubicBezierCurve3 = THREE.Curve.create(
  17676. function ( v0, v1, v2, v3 ) {
  17677. this.v0 = v0;
  17678. this.v1 = v1;
  17679. this.v2 = v2;
  17680. this.v3 = v3;
  17681. },
  17682. function ( t ) {
  17683. var tx, ty, tz;
  17684. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17685. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17686. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  17687. return new THREE.Vector3( tx, ty, tz );
  17688. }
  17689. );
  17690. /**************************************************************
  17691. * Spline 3D curve
  17692. **************************************************************/
  17693. THREE.SplineCurve3 = THREE.Curve.create(
  17694. function ( points /* array of Vector3 */) {
  17695. this.points = (points == undefined) ? [] : points;
  17696. },
  17697. function ( t ) {
  17698. var v = new THREE.Vector3();
  17699. var c = [];
  17700. var points = this.points, point, intPoint, weight;
  17701. point = ( points.length - 1 ) * t;
  17702. intPoint = Math.floor( point );
  17703. weight = point - intPoint;
  17704. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17705. c[ 1 ] = intPoint;
  17706. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17707. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17708. var pt0 = points[ c[0] ],
  17709. pt1 = points[ c[1] ],
  17710. pt2 = points[ c[2] ],
  17711. pt3 = points[ c[3] ];
  17712. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  17713. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  17714. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  17715. return v;
  17716. }
  17717. );
  17718. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  17719. // var v = new THREE.Vector3();
  17720. // var c = [];
  17721. // var points = this.points, point, intPoint, weight;
  17722. // point = ( points.length - 1 ) * t;
  17723. // intPoint = Math.floor( point );
  17724. // weight = point - intPoint;
  17725. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17726. // c[ 1 ] = intPoint;
  17727. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17728. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17729. // var pt0 = points[ c[0] ],
  17730. // pt1 = points[ c[1] ],
  17731. // pt2 = points[ c[2] ],
  17732. // pt3 = points[ c[3] ];
  17733. // // t = weight;
  17734. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  17735. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  17736. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  17737. // return v;
  17738. // }
  17739. /**************************************************************
  17740. * Closed Spline 3D curve
  17741. **************************************************************/
  17742. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  17743. function ( points /* array of Vector3 */) {
  17744. this.points = (points == undefined) ? [] : points;
  17745. },
  17746. function ( t ) {
  17747. var v = new THREE.Vector3();
  17748. var c = [];
  17749. var points = this.points, point, intPoint, weight;
  17750. point = ( points.length - 0 ) * t;
  17751. // This needs to be from 0-length +1
  17752. intPoint = Math.floor( point );
  17753. weight = point - intPoint;
  17754. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  17755. c[ 0 ] = ( intPoint - 1 ) % points.length;
  17756. c[ 1 ] = ( intPoint ) % points.length;
  17757. c[ 2 ] = ( intPoint + 1 ) % points.length;
  17758. c[ 3 ] = ( intPoint + 2 ) % points.length;
  17759. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17760. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17761. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  17762. return v;
  17763. }
  17764. );
  17765. /**
  17766. * @author mikael emtinger / http://gomo.se/
  17767. */
  17768. THREE.AnimationHandler = (function() {
  17769. var playing = [];
  17770. var library = {};
  17771. var that = {};
  17772. //--- update ---
  17773. that.update = function( deltaTimeMS ) {
  17774. for( var i = 0; i < playing.length; i ++ )
  17775. playing[ i ].update( deltaTimeMS );
  17776. };
  17777. //--- add ---
  17778. that.addToUpdate = function( animation ) {
  17779. if ( playing.indexOf( animation ) === -1 )
  17780. playing.push( animation );
  17781. };
  17782. //--- remove ---
  17783. that.removeFromUpdate = function( animation ) {
  17784. var index = playing.indexOf( animation );
  17785. if( index !== -1 )
  17786. playing.splice( index, 1 );
  17787. };
  17788. //--- add ---
  17789. that.add = function( data ) {
  17790. if ( library[ data.name ] !== undefined )
  17791. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17792. library[ data.name ] = data;
  17793. initData( data );
  17794. };
  17795. //--- get ---
  17796. that.get = function( name ) {
  17797. if ( typeof name === "string" ) {
  17798. if ( library[ name ] ) {
  17799. return library[ name ];
  17800. } else {
  17801. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17802. return null;
  17803. }
  17804. } else {
  17805. // todo: add simple tween library
  17806. }
  17807. };
  17808. //--- parse ---
  17809. that.parse = function( root ) {
  17810. // setup hierarchy
  17811. var hierarchy = [];
  17812. if ( root instanceof THREE.SkinnedMesh ) {
  17813. for( var b = 0; b < root.bones.length; b++ ) {
  17814. hierarchy.push( root.bones[ b ] );
  17815. }
  17816. } else {
  17817. parseRecurseHierarchy( root, hierarchy );
  17818. }
  17819. return hierarchy;
  17820. };
  17821. var parseRecurseHierarchy = function( root, hierarchy ) {
  17822. hierarchy.push( root );
  17823. for( var c = 0; c < root.children.length; c++ )
  17824. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17825. }
  17826. //--- init data ---
  17827. var initData = function( data ) {
  17828. if( data.initialized === true )
  17829. return;
  17830. // loop through all keys
  17831. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17832. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17833. // remove minus times
  17834. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17835. data.hierarchy[ h ].keys[ k ].time = 0;
  17836. // create quaternions
  17837. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17838. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17839. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17840. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17841. }
  17842. }
  17843. // prepare morph target keys
  17844. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17845. // get all used
  17846. var usedMorphTargets = {};
  17847. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17848. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17849. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17850. usedMorphTargets[ morphTargetName ] = -1;
  17851. }
  17852. }
  17853. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17854. // set all used on all frames
  17855. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17856. var influences = {};
  17857. for ( var morphTargetName in usedMorphTargets ) {
  17858. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17859. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17860. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17861. break;
  17862. }
  17863. }
  17864. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17865. influences[ morphTargetName ] = 0;
  17866. }
  17867. }
  17868. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17869. }
  17870. }
  17871. // remove all keys that are on the same time
  17872. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17873. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17874. data.hierarchy[ h ].keys.splice( k, 1 );
  17875. k --;
  17876. }
  17877. }
  17878. // set index
  17879. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17880. data.hierarchy[ h ].keys[ k ].index = k;
  17881. }
  17882. }
  17883. // JIT
  17884. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17885. data.JIT = {};
  17886. data.JIT.hierarchy = [];
  17887. for( var h = 0; h < data.hierarchy.length; h ++ )
  17888. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17889. // done
  17890. data.initialized = true;
  17891. };
  17892. // interpolation types
  17893. that.LINEAR = 0;
  17894. that.CATMULLROM = 1;
  17895. that.CATMULLROM_FORWARD = 2;
  17896. return that;
  17897. }());
  17898. /**
  17899. * @author mikael emtinger / http://gomo.se/
  17900. * @author mrdoob / http://mrdoob.com/
  17901. * @author alteredq / http://alteredqualia.com/
  17902. */
  17903. THREE.Animation = function ( root, name, interpolationType ) {
  17904. this.root = root;
  17905. this.data = THREE.AnimationHandler.get( name );
  17906. this.hierarchy = THREE.AnimationHandler.parse( root );
  17907. this.currentTime = 0;
  17908. this.timeScale = 1;
  17909. this.isPlaying = false;
  17910. this.isPaused = true;
  17911. this.loop = true;
  17912. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17913. this.points = [];
  17914. this.target = new THREE.Vector3();
  17915. };
  17916. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17917. if ( this.isPlaying === false ) {
  17918. this.isPlaying = true;
  17919. this.loop = loop !== undefined ? loop : true;
  17920. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17921. // reset key cache
  17922. var h, hl = this.hierarchy.length,
  17923. object;
  17924. for ( h = 0; h < hl; h ++ ) {
  17925. object = this.hierarchy[ h ];
  17926. object.matrixAutoUpdate = true;
  17927. if ( object.animationCache === undefined ) {
  17928. object.animationCache = {};
  17929. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17930. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17931. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17932. }
  17933. var prevKey = object.animationCache.prevKey;
  17934. var nextKey = object.animationCache.nextKey;
  17935. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17936. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17937. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17938. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17939. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17940. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17941. }
  17942. this.update( 0 );
  17943. }
  17944. this.isPaused = false;
  17945. THREE.AnimationHandler.addToUpdate( this );
  17946. };
  17947. THREE.Animation.prototype.pause = function() {
  17948. if ( this.isPaused === true ) {
  17949. THREE.AnimationHandler.addToUpdate( this );
  17950. } else {
  17951. THREE.AnimationHandler.removeFromUpdate( this );
  17952. }
  17953. this.isPaused = !this.isPaused;
  17954. };
  17955. THREE.Animation.prototype.stop = function() {
  17956. this.isPlaying = false;
  17957. this.isPaused = false;
  17958. THREE.AnimationHandler.removeFromUpdate( this );
  17959. };
  17960. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17961. // early out
  17962. if ( this.isPlaying === false ) return;
  17963. // vars
  17964. var types = [ "pos", "rot", "scl" ];
  17965. var type;
  17966. var scale;
  17967. var vector;
  17968. var prevXYZ, nextXYZ;
  17969. var prevKey, nextKey;
  17970. var object;
  17971. var animationCache;
  17972. var frame;
  17973. var JIThierarchy = this.data.JIT.hierarchy;
  17974. var currentTime, unloopedCurrentTime;
  17975. var currentPoint, forwardPoint, angle;
  17976. this.currentTime += deltaTimeMS * this.timeScale;
  17977. unloopedCurrentTime = this.currentTime;
  17978. currentTime = this.currentTime = this.currentTime % this.data.length;
  17979. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17980. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17981. object = this.hierarchy[ h ];
  17982. animationCache = object.animationCache;
  17983. // loop through pos/rot/scl
  17984. for ( var t = 0; t < 3; t ++ ) {
  17985. // get keys
  17986. type = types[ t ];
  17987. prevKey = animationCache.prevKey[ type ];
  17988. nextKey = animationCache.nextKey[ type ];
  17989. // switch keys?
  17990. if ( nextKey.time <= unloopedCurrentTime ) {
  17991. // did we loop?
  17992. if ( currentTime < unloopedCurrentTime ) {
  17993. if ( this.loop ) {
  17994. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17995. nextKey = this.getNextKeyWith( type, h, 1 );
  17996. while( nextKey.time < currentTime ) {
  17997. prevKey = nextKey;
  17998. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17999. }
  18000. } else {
  18001. this.stop();
  18002. return;
  18003. }
  18004. } else {
  18005. do {
  18006. prevKey = nextKey;
  18007. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18008. } while( nextKey.time < currentTime )
  18009. }
  18010. animationCache.prevKey[ type ] = prevKey;
  18011. animationCache.nextKey[ type ] = nextKey;
  18012. }
  18013. object.matrixAutoUpdate = true;
  18014. object.matrixWorldNeedsUpdate = true;
  18015. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18016. prevXYZ = prevKey[ type ];
  18017. nextXYZ = nextKey[ type ];
  18018. // check scale error
  18019. if ( scale < 0 || scale > 1 ) {
  18020. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  18021. scale = scale < 0 ? 0 : 1;
  18022. }
  18023. // interpolate
  18024. if ( type === "pos" ) {
  18025. vector = object.position;
  18026. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18027. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18028. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18029. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18030. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18031. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18032. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18033. this.points[ 1 ] = prevXYZ;
  18034. this.points[ 2 ] = nextXYZ;
  18035. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18036. scale = scale * 0.33 + 0.33;
  18037. currentPoint = this.interpolateCatmullRom( this.points, scale );
  18038. vector.x = currentPoint[ 0 ];
  18039. vector.y = currentPoint[ 1 ];
  18040. vector.z = currentPoint[ 2 ];
  18041. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18042. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  18043. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18044. this.target.sub( vector );
  18045. this.target.y = 0;
  18046. this.target.normalize();
  18047. angle = Math.atan2( this.target.x, this.target.z );
  18048. object.rotation.set( 0, angle, 0 );
  18049. }
  18050. }
  18051. } else if ( type === "rot" ) {
  18052. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18053. } else if ( type === "scl" ) {
  18054. vector = object.scale;
  18055. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18056. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18057. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18058. }
  18059. }
  18060. }
  18061. };
  18062. // Catmull-Rom spline
  18063. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  18064. var c = [], v3 = [],
  18065. point, intPoint, weight, w2, w3,
  18066. pa, pb, pc, pd;
  18067. point = ( points.length - 1 ) * scale;
  18068. intPoint = Math.floor( point );
  18069. weight = point - intPoint;
  18070. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18071. c[ 1 ] = intPoint;
  18072. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18073. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18074. pa = points[ c[ 0 ] ];
  18075. pb = points[ c[ 1 ] ];
  18076. pc = points[ c[ 2 ] ];
  18077. pd = points[ c[ 3 ] ];
  18078. w2 = weight * weight;
  18079. w3 = weight * w2;
  18080. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18081. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18082. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18083. return v3;
  18084. };
  18085. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18086. var v0 = ( p2 - p0 ) * 0.5,
  18087. v1 = ( p3 - p1 ) * 0.5;
  18088. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18089. };
  18090. // Get next key with
  18091. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18092. var keys = this.data.hierarchy[ h ].keys;
  18093. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18094. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18095. key = key < keys.length - 1 ? key : keys.length - 1;
  18096. } else {
  18097. key = key % keys.length;
  18098. }
  18099. for ( ; key < keys.length; key++ ) {
  18100. if ( keys[ key ][ type ] !== undefined ) {
  18101. return keys[ key ];
  18102. }
  18103. }
  18104. return this.data.hierarchy[ h ].keys[ 0 ];
  18105. };
  18106. // Get previous key with
  18107. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18108. var keys = this.data.hierarchy[ h ].keys;
  18109. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18110. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18111. key = key > 0 ? key : 0;
  18112. } else {
  18113. key = key >= 0 ? key : key + keys.length;
  18114. }
  18115. for ( ; key >= 0; key -- ) {
  18116. if ( keys[ key ][ type ] !== undefined ) {
  18117. return keys[ key ];
  18118. }
  18119. }
  18120. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18121. };
  18122. /**
  18123. * @author mikael emtinger / http://gomo.se/
  18124. * @author mrdoob / http://mrdoob.com/
  18125. * @author alteredq / http://alteredqualia.com/
  18126. * @author khang duong
  18127. * @author erik kitson
  18128. */
  18129. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  18130. this.root = root;
  18131. this.data = THREE.AnimationHandler.get( data );
  18132. this.hierarchy = THREE.AnimationHandler.parse( root );
  18133. this.currentTime = 0;
  18134. this.timeScale = 0.001;
  18135. this.isPlaying = false;
  18136. this.isPaused = true;
  18137. this.loop = true;
  18138. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  18139. // initialize to first keyframes
  18140. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18141. var keys = this.data.hierarchy[h].keys,
  18142. sids = this.data.hierarchy[h].sids,
  18143. obj = this.hierarchy[h];
  18144. if ( keys.length && sids ) {
  18145. for ( var s = 0; s < sids.length; s++ ) {
  18146. var sid = sids[ s ],
  18147. next = this.getNextKeyWith( sid, h, 0 );
  18148. if ( next ) {
  18149. next.apply( sid );
  18150. }
  18151. }
  18152. obj.matrixAutoUpdate = false;
  18153. this.data.hierarchy[h].node.updateMatrix();
  18154. obj.matrixWorldNeedsUpdate = true;
  18155. }
  18156. }
  18157. };
  18158. // Play
  18159. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18160. if( !this.isPlaying ) {
  18161. this.isPlaying = true;
  18162. this.loop = loop !== undefined ? loop : true;
  18163. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18164. this.startTimeMs = startTimeMS;
  18165. this.startTime = 10000000;
  18166. this.endTime = -this.startTime;
  18167. // reset key cache
  18168. var h, hl = this.hierarchy.length,
  18169. object,
  18170. node;
  18171. for ( h = 0; h < hl; h++ ) {
  18172. object = this.hierarchy[ h ];
  18173. node = this.data.hierarchy[ h ];
  18174. if ( node.animationCache === undefined ) {
  18175. node.animationCache = {};
  18176. node.animationCache.prevKey = null;
  18177. node.animationCache.nextKey = null;
  18178. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18179. }
  18180. var keys = this.data.hierarchy[h].keys;
  18181. if (keys.length) {
  18182. node.animationCache.prevKey = keys[ 0 ];
  18183. node.animationCache.nextKey = keys[ 1 ];
  18184. this.startTime = Math.min( keys[0].time, this.startTime );
  18185. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18186. }
  18187. }
  18188. this.update( 0 );
  18189. }
  18190. this.isPaused = false;
  18191. THREE.AnimationHandler.addToUpdate( this );
  18192. };
  18193. // Pause
  18194. THREE.KeyFrameAnimation.prototype.pause = function() {
  18195. if( this.isPaused ) {
  18196. THREE.AnimationHandler.addToUpdate( this );
  18197. } else {
  18198. THREE.AnimationHandler.removeFromUpdate( this );
  18199. }
  18200. this.isPaused = !this.isPaused;
  18201. };
  18202. // Stop
  18203. THREE.KeyFrameAnimation.prototype.stop = function() {
  18204. this.isPlaying = false;
  18205. this.isPaused = false;
  18206. THREE.AnimationHandler.removeFromUpdate( this );
  18207. // reset JIT matrix and remove cache
  18208. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18209. var obj = this.hierarchy[ h ];
  18210. var node = this.data.hierarchy[ h ];
  18211. if ( node.animationCache !== undefined ) {
  18212. var original = node.animationCache.originalMatrix;
  18213. if( obj instanceof THREE.Bone ) {
  18214. original.copy( obj.skinMatrix );
  18215. obj.skinMatrix = original;
  18216. } else {
  18217. original.copy( obj.matrix );
  18218. obj.matrix = original;
  18219. }
  18220. delete node.animationCache;
  18221. }
  18222. }
  18223. };
  18224. // Update
  18225. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18226. // early out
  18227. if( !this.isPlaying ) return;
  18228. // vars
  18229. var prevKey, nextKey;
  18230. var object;
  18231. var node;
  18232. var frame;
  18233. var JIThierarchy = this.data.JIT.hierarchy;
  18234. var currentTime, unloopedCurrentTime;
  18235. var looped;
  18236. // update
  18237. this.currentTime += deltaTimeMS * this.timeScale;
  18238. unloopedCurrentTime = this.currentTime;
  18239. currentTime = this.currentTime = this.currentTime % this.data.length;
  18240. // if looped around, the current time should be based on the startTime
  18241. if ( currentTime < this.startTimeMs ) {
  18242. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18243. }
  18244. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18245. looped = currentTime < unloopedCurrentTime;
  18246. if ( looped && !this.loop ) {
  18247. // Set the animation to the last keyframes and stop
  18248. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18249. var keys = this.data.hierarchy[h].keys,
  18250. sids = this.data.hierarchy[h].sids,
  18251. end = keys.length-1,
  18252. obj = this.hierarchy[h];
  18253. if ( keys.length ) {
  18254. for ( var s = 0; s < sids.length; s++ ) {
  18255. var sid = sids[ s ],
  18256. prev = this.getPrevKeyWith( sid, h, end );
  18257. if ( prev ) {
  18258. prev.apply( sid );
  18259. }
  18260. }
  18261. this.data.hierarchy[h].node.updateMatrix();
  18262. obj.matrixWorldNeedsUpdate = true;
  18263. }
  18264. }
  18265. this.stop();
  18266. return;
  18267. }
  18268. // check pre-infinity
  18269. if ( currentTime < this.startTime ) {
  18270. return;
  18271. }
  18272. // update
  18273. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18274. object = this.hierarchy[ h ];
  18275. node = this.data.hierarchy[ h ];
  18276. var keys = node.keys,
  18277. animationCache = node.animationCache;
  18278. // use JIT?
  18279. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18280. if( object instanceof THREE.Bone ) {
  18281. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18282. object.matrixWorldNeedsUpdate = false;
  18283. } else {
  18284. object.matrix = JIThierarchy[ h ][ frame ];
  18285. object.matrixWorldNeedsUpdate = true;
  18286. }
  18287. // use interpolation
  18288. } else if ( keys.length ) {
  18289. // make sure so original matrix and not JIT matrix is set
  18290. if ( this.JITCompile && animationCache ) {
  18291. if( object instanceof THREE.Bone ) {
  18292. object.skinMatrix = animationCache.originalMatrix;
  18293. } else {
  18294. object.matrix = animationCache.originalMatrix;
  18295. }
  18296. }
  18297. prevKey = animationCache.prevKey;
  18298. nextKey = animationCache.nextKey;
  18299. if ( prevKey && nextKey ) {
  18300. // switch keys?
  18301. if ( nextKey.time <= unloopedCurrentTime ) {
  18302. // did we loop?
  18303. if ( looped && this.loop ) {
  18304. prevKey = keys[ 0 ];
  18305. nextKey = keys[ 1 ];
  18306. while ( nextKey.time < currentTime ) {
  18307. prevKey = nextKey;
  18308. nextKey = keys[ prevKey.index + 1 ];
  18309. }
  18310. } else if ( !looped ) {
  18311. var lastIndex = keys.length - 1;
  18312. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18313. prevKey = nextKey;
  18314. nextKey = keys[ prevKey.index + 1 ];
  18315. }
  18316. }
  18317. animationCache.prevKey = prevKey;
  18318. animationCache.nextKey = nextKey;
  18319. }
  18320. if(nextKey.time >= currentTime)
  18321. prevKey.interpolate( nextKey, currentTime );
  18322. else
  18323. prevKey.interpolate( nextKey, nextKey.time);
  18324. }
  18325. this.data.hierarchy[h].node.updateMatrix();
  18326. object.matrixWorldNeedsUpdate = true;
  18327. }
  18328. }
  18329. // update JIT?
  18330. if ( this.JITCompile ) {
  18331. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18332. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18333. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18334. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18335. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18336. } else {
  18337. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18338. }
  18339. }
  18340. }
  18341. }
  18342. };
  18343. // Get next key with
  18344. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18345. var keys = this.data.hierarchy[ h ].keys;
  18346. key = key % keys.length;
  18347. for ( ; key < keys.length; key++ ) {
  18348. if ( keys[ key ].hasTarget( sid ) ) {
  18349. return keys[ key ];
  18350. }
  18351. }
  18352. return keys[ 0 ];
  18353. };
  18354. // Get previous key with
  18355. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18356. var keys = this.data.hierarchy[ h ].keys;
  18357. key = key >= 0 ? key : key + keys.length;
  18358. for ( ; key >= 0; key-- ) {
  18359. if ( keys[ key ].hasTarget( sid ) ) {
  18360. return keys[ key ];
  18361. }
  18362. }
  18363. return keys[ keys.length - 1 ];
  18364. };
  18365. /**
  18366. * Camera for rendering cube maps
  18367. * - renders scene into axis-aligned cube
  18368. *
  18369. * @author alteredq / http://alteredqualia.com/
  18370. */
  18371. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18372. THREE.Object3D.call( this );
  18373. var fov = 90, aspect = 1;
  18374. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18375. cameraPX.up.set( 0, -1, 0 );
  18376. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18377. this.add( cameraPX );
  18378. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18379. cameraNX.up.set( 0, -1, 0 );
  18380. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18381. this.add( cameraNX );
  18382. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18383. cameraPY.up.set( 0, 0, 1 );
  18384. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18385. this.add( cameraPY );
  18386. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18387. cameraNY.up.set( 0, 0, -1 );
  18388. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18389. this.add( cameraNY );
  18390. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18391. cameraPZ.up.set( 0, -1, 0 );
  18392. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18393. this.add( cameraPZ );
  18394. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18395. cameraNZ.up.set( 0, -1, 0 );
  18396. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18397. this.add( cameraNZ );
  18398. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18399. this.updateCubeMap = function ( renderer, scene ) {
  18400. var renderTarget = this.renderTarget;
  18401. var generateMipmaps = renderTarget.generateMipmaps;
  18402. renderTarget.generateMipmaps = false;
  18403. renderTarget.activeCubeFace = 0;
  18404. renderer.render( scene, cameraPX, renderTarget );
  18405. renderTarget.activeCubeFace = 1;
  18406. renderer.render( scene, cameraNX, renderTarget );
  18407. renderTarget.activeCubeFace = 2;
  18408. renderer.render( scene, cameraPY, renderTarget );
  18409. renderTarget.activeCubeFace = 3;
  18410. renderer.render( scene, cameraNY, renderTarget );
  18411. renderTarget.activeCubeFace = 4;
  18412. renderer.render( scene, cameraPZ, renderTarget );
  18413. renderTarget.generateMipmaps = generateMipmaps;
  18414. renderTarget.activeCubeFace = 5;
  18415. renderer.render( scene, cameraNZ, renderTarget );
  18416. };
  18417. };
  18418. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18419. /*
  18420. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18421. *
  18422. * A general perpose camera, for setting FOV, Lens Focal Length,
  18423. * and switching between perspective and orthographic views easily.
  18424. * Use this only if you do not wish to manage
  18425. * both a Orthographic and Perspective Camera
  18426. *
  18427. */
  18428. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18429. THREE.Camera.call( this );
  18430. this.fov = fov;
  18431. this.left = -width / 2;
  18432. this.right = width / 2
  18433. this.top = height / 2;
  18434. this.bottom = -height / 2;
  18435. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18436. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18437. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18438. this.zoom = 1;
  18439. this.toPerspective();
  18440. var aspect = width/height;
  18441. };
  18442. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18443. THREE.CombinedCamera.prototype.toPerspective = function () {
  18444. // Switches to the Perspective Camera
  18445. this.near = this.cameraP.near;
  18446. this.far = this.cameraP.far;
  18447. this.cameraP.fov = this.fov / this.zoom ;
  18448. this.cameraP.updateProjectionMatrix();
  18449. this.projectionMatrix = this.cameraP.projectionMatrix;
  18450. this.inPerspectiveMode = true;
  18451. this.inOrthographicMode = false;
  18452. };
  18453. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18454. // Switches to the Orthographic camera estimating viewport from Perspective
  18455. var fov = this.fov;
  18456. var aspect = this.cameraP.aspect;
  18457. var near = this.cameraP.near;
  18458. var far = this.cameraP.far;
  18459. // The size that we set is the mid plane of the viewing frustum
  18460. var hyperfocus = ( near + far ) / 2;
  18461. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18462. var planeHeight = 2 * halfHeight;
  18463. var planeWidth = planeHeight * aspect;
  18464. var halfWidth = planeWidth / 2;
  18465. halfHeight /= this.zoom;
  18466. halfWidth /= this.zoom;
  18467. this.cameraO.left = -halfWidth;
  18468. this.cameraO.right = halfWidth;
  18469. this.cameraO.top = halfHeight;
  18470. this.cameraO.bottom = -halfHeight;
  18471. // this.cameraO.left = -farHalfWidth;
  18472. // this.cameraO.right = farHalfWidth;
  18473. // this.cameraO.top = farHalfHeight;
  18474. // this.cameraO.bottom = -farHalfHeight;
  18475. // this.cameraO.left = this.left / this.zoom;
  18476. // this.cameraO.right = this.right / this.zoom;
  18477. // this.cameraO.top = this.top / this.zoom;
  18478. // this.cameraO.bottom = this.bottom / this.zoom;
  18479. this.cameraO.updateProjectionMatrix();
  18480. this.near = this.cameraO.near;
  18481. this.far = this.cameraO.far;
  18482. this.projectionMatrix = this.cameraO.projectionMatrix;
  18483. this.inPerspectiveMode = false;
  18484. this.inOrthographicMode = true;
  18485. };
  18486. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18487. this.cameraP.aspect = width / height;
  18488. this.left = -width / 2;
  18489. this.right = width / 2
  18490. this.top = height / 2;
  18491. this.bottom = -height / 2;
  18492. };
  18493. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18494. this.fov = fov;
  18495. if ( this.inPerspectiveMode ) {
  18496. this.toPerspective();
  18497. } else {
  18498. this.toOrthographic();
  18499. }
  18500. };
  18501. // For mantaining similar API with PerspectiveCamera
  18502. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18503. if ( this.inPerspectiveMode ) {
  18504. this.toPerspective();
  18505. } else {
  18506. this.toPerspective();
  18507. this.toOrthographic();
  18508. }
  18509. };
  18510. /*
  18511. * Uses Focal Length (in mm) to estimate and set FOV
  18512. * 35mm (fullframe) camera is used if frame size is not specified;
  18513. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18514. */
  18515. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18516. if ( frameHeight === undefined ) frameHeight = 24;
  18517. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18518. this.setFov( fov );
  18519. return fov;
  18520. };
  18521. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18522. this.zoom = zoom;
  18523. if ( this.inPerspectiveMode ) {
  18524. this.toPerspective();
  18525. } else {
  18526. this.toOrthographic();
  18527. }
  18528. };
  18529. THREE.CombinedCamera.prototype.toFrontView = function() {
  18530. this.rotation.x = 0;
  18531. this.rotation.y = 0;
  18532. this.rotation.z = 0;
  18533. // should we be modifing the matrix instead?
  18534. this.rotationAutoUpdate = false;
  18535. };
  18536. THREE.CombinedCamera.prototype.toBackView = function() {
  18537. this.rotation.x = 0;
  18538. this.rotation.y = Math.PI;
  18539. this.rotation.z = 0;
  18540. this.rotationAutoUpdate = false;
  18541. };
  18542. THREE.CombinedCamera.prototype.toLeftView = function() {
  18543. this.rotation.x = 0;
  18544. this.rotation.y = - Math.PI / 2;
  18545. this.rotation.z = 0;
  18546. this.rotationAutoUpdate = false;
  18547. };
  18548. THREE.CombinedCamera.prototype.toRightView = function() {
  18549. this.rotation.x = 0;
  18550. this.rotation.y = Math.PI / 2;
  18551. this.rotation.z = 0;
  18552. this.rotationAutoUpdate = false;
  18553. };
  18554. THREE.CombinedCamera.prototype.toTopView = function() {
  18555. this.rotation.x = - Math.PI / 2;
  18556. this.rotation.y = 0;
  18557. this.rotation.z = 0;
  18558. this.rotationAutoUpdate = false;
  18559. };
  18560. THREE.CombinedCamera.prototype.toBottomView = function() {
  18561. this.rotation.x = Math.PI / 2;
  18562. this.rotation.y = 0;
  18563. this.rotation.z = 0;
  18564. this.rotationAutoUpdate = false;
  18565. };
  18566. /**
  18567. * @author hughes
  18568. */
  18569. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18570. THREE.Geometry.call( this );
  18571. this.radius = radius = radius || 50;
  18572. this.segments = segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18573. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18574. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18575. var i, uvs = [],
  18576. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18577. this.vertices.push(center);
  18578. uvs.push( centerUV );
  18579. for ( i = 0; i <= segments; i ++ ) {
  18580. var vertex = new THREE.Vector3();
  18581. var segment = thetaStart + i / segments * thetaLength;
  18582. vertex.x = radius * Math.cos( segment );
  18583. vertex.y = radius * Math.sin( segment );
  18584. this.vertices.push( vertex );
  18585. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  18586. }
  18587. var n = new THREE.Vector3( 0, 0, 1 );
  18588. for ( i = 1; i <= segments; i ++ ) {
  18589. var v1 = i;
  18590. var v2 = i + 1 ;
  18591. var v3 = 0;
  18592. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  18593. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  18594. }
  18595. this.computeCentroids();
  18596. this.computeFaceNormals();
  18597. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18598. };
  18599. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18600. /**
  18601. * @author mrdoob / http://mrdoob.com/
  18602. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18603. */
  18604. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18605. THREE.Geometry.call( this );
  18606. var scope = this;
  18607. this.width = width;
  18608. this.height = height;
  18609. this.depth = depth;
  18610. this.widthSegments = widthSegments || 1;
  18611. this.heightSegments = heightSegments || 1;
  18612. this.depthSegments = depthSegments || 1;
  18613. var width_half = this.width / 2;
  18614. var height_half = this.height / 2;
  18615. var depth_half = this.depth / 2;
  18616. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18617. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18618. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18619. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18620. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18621. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18622. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18623. var w, ix, iy,
  18624. gridX = scope.widthSegments,
  18625. gridY = scope.heightSegments,
  18626. width_half = width / 2,
  18627. height_half = height / 2,
  18628. offset = scope.vertices.length;
  18629. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18630. w = 'z';
  18631. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18632. w = 'y';
  18633. gridY = scope.depthSegments;
  18634. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18635. w = 'x';
  18636. gridX = scope.depthSegments;
  18637. }
  18638. var gridX1 = gridX + 1,
  18639. gridY1 = gridY + 1,
  18640. segment_width = width / gridX,
  18641. segment_height = height / gridY,
  18642. normal = new THREE.Vector3();
  18643. normal[ w ] = depth > 0 ? 1 : - 1;
  18644. for ( iy = 0; iy < gridY1; iy ++ ) {
  18645. for ( ix = 0; ix < gridX1; ix ++ ) {
  18646. var vector = new THREE.Vector3();
  18647. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18648. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18649. vector[ w ] = depth;
  18650. scope.vertices.push( vector );
  18651. }
  18652. }
  18653. for ( iy = 0; iy < gridY; iy++ ) {
  18654. for ( ix = 0; ix < gridX; ix++ ) {
  18655. var a = ix + gridX1 * iy;
  18656. var b = ix + gridX1 * ( iy + 1 );
  18657. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18658. var d = ( ix + 1 ) + gridX1 * iy;
  18659. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  18660. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  18661. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  18662. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  18663. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  18664. face.normal.copy( normal );
  18665. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18666. face.materialIndex = materialIndex;
  18667. scope.faces.push( face );
  18668. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  18669. face = new THREE.Face3( b + offset, c + offset, d + offset );
  18670. face.normal.copy( normal );
  18671. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18672. face.materialIndex = materialIndex;
  18673. scope.faces.push( face );
  18674. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  18675. }
  18676. }
  18677. }
  18678. this.computeCentroids();
  18679. this.mergeVertices();
  18680. };
  18681. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18682. /**
  18683. * @author mrdoob / http://mrdoob.com/
  18684. */
  18685. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  18686. THREE.Geometry.call( this );
  18687. this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18688. this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18689. this.height = height = height !== undefined ? height : 100;
  18690. this.radialSegments = radialSegments = radialSegments || 8;
  18691. this.heightSegments = heightSegments = heightSegments || 1;
  18692. this.openEnded = openEnded = openEnded !== undefined ? openEnded : false;
  18693. var heightHalf = height / 2;
  18694. var x, y, vertices = [], uvs = [];
  18695. for ( y = 0; y <= heightSegments; y ++ ) {
  18696. var verticesRow = [];
  18697. var uvsRow = [];
  18698. var v = y / heightSegments;
  18699. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18700. for ( x = 0; x <= radialSegments; x ++ ) {
  18701. var u = x / radialSegments;
  18702. var vertex = new THREE.Vector3();
  18703. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18704. vertex.y = - v * height + heightHalf;
  18705. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18706. this.vertices.push( vertex );
  18707. verticesRow.push( this.vertices.length - 1 );
  18708. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18709. }
  18710. vertices.push( verticesRow );
  18711. uvs.push( uvsRow );
  18712. }
  18713. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18714. var na, nb;
  18715. for ( x = 0; x < radialSegments; x ++ ) {
  18716. if ( radiusTop !== 0 ) {
  18717. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18718. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18719. } else {
  18720. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18721. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18722. }
  18723. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18724. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18725. for ( y = 0; y < heightSegments; y ++ ) {
  18726. var v1 = vertices[ y ][ x ];
  18727. var v2 = vertices[ y + 1 ][ x ];
  18728. var v3 = vertices[ y + 1 ][ x + 1 ];
  18729. var v4 = vertices[ y ][ x + 1 ];
  18730. var n1 = na.clone();
  18731. var n2 = na.clone();
  18732. var n3 = nb.clone();
  18733. var n4 = nb.clone();
  18734. var uv1 = uvs[ y ][ x ].clone();
  18735. var uv2 = uvs[ y + 1 ][ x ].clone();
  18736. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18737. var uv4 = uvs[ y ][ x + 1 ].clone();
  18738. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  18739. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  18740. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2, n3, n4 ] ) );
  18741. this.faceVertexUvs[ 0 ].push( [ uv2, uv3, uv4 ] );
  18742. }
  18743. }
  18744. // top cap
  18745. if ( openEnded === false && radiusTop > 0 ) {
  18746. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18747. for ( x = 0; x < radialSegments; x ++ ) {
  18748. var v1 = vertices[ 0 ][ x ];
  18749. var v2 = vertices[ 0 ][ x + 1 ];
  18750. var v3 = this.vertices.length - 1;
  18751. var n1 = new THREE.Vector3( 0, 1, 0 );
  18752. var n2 = new THREE.Vector3( 0, 1, 0 );
  18753. var n3 = new THREE.Vector3( 0, 1, 0 );
  18754. var uv1 = uvs[ 0 ][ x ].clone();
  18755. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18756. var uv3 = new THREE.Vector2( uv2.u, 0 );
  18757. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18758. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18759. }
  18760. }
  18761. // bottom cap
  18762. if ( openEnded === false && radiusBottom > 0 ) {
  18763. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18764. for ( x = 0; x < radialSegments; x ++ ) {
  18765. var v1 = vertices[ y ][ x + 1 ];
  18766. var v2 = vertices[ y ][ x ];
  18767. var v3 = this.vertices.length - 1;
  18768. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18769. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18770. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18771. var uv1 = uvs[ y ][ x + 1 ].clone();
  18772. var uv2 = uvs[ y ][ x ].clone();
  18773. var uv3 = new THREE.Vector2( uv2.u, 1 );
  18774. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18775. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18776. }
  18777. }
  18778. this.computeCentroids();
  18779. this.computeFaceNormals();
  18780. }
  18781. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18782. /**
  18783. * @author zz85 / http://www.lab4games.net/zz85/blog
  18784. *
  18785. * Creates extruded geometry from a path shape.
  18786. *
  18787. * parameters = {
  18788. *
  18789. * curveSegments: <int>, // number of points on the curves
  18790. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18791. * amount: <int>, // Depth to extrude the shape
  18792. *
  18793. * bevelEnabled: <bool>, // turn on bevel
  18794. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18795. * bevelSize: <float>, // how far from shape outline is bevel
  18796. * bevelSegments: <int>, // number of bevel layers
  18797. *
  18798. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18799. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18800. *
  18801. * material: <int> // material index for front and back faces
  18802. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18803. * uvGenerator: <Object> // object that provides UV generator functions
  18804. *
  18805. * }
  18806. **/
  18807. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18808. if ( typeof( shapes ) === "undefined" ) {
  18809. shapes = [];
  18810. return;
  18811. }
  18812. THREE.Geometry.call( this );
  18813. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18814. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18815. this.addShapeList( shapes, options );
  18816. this.computeCentroids();
  18817. this.computeFaceNormals();
  18818. // can't really use automatic vertex normals
  18819. // as then front and back sides get smoothed too
  18820. // should do separate smoothing just for sides
  18821. //this.computeVertexNormals();
  18822. //console.log( "took", ( Date.now() - startTime ) );
  18823. };
  18824. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18825. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18826. var sl = shapes.length;
  18827. for ( var s = 0; s < sl; s ++ ) {
  18828. var shape = shapes[ s ];
  18829. this.addShape( shape, options );
  18830. }
  18831. };
  18832. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18833. var amount = options.amount !== undefined ? options.amount : 100;
  18834. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18835. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18836. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18837. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18838. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18839. var steps = options.steps !== undefined ? options.steps : 1;
  18840. var extrudePath = options.extrudePath;
  18841. var extrudePts, extrudeByPath = false;
  18842. var material = options.material;
  18843. var extrudeMaterial = options.extrudeMaterial;
  18844. // Use default WorldUVGenerator if no UV generators are specified.
  18845. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18846. var shapebb = this.shapebb;
  18847. //shapebb = shape.getBoundingBox();
  18848. var splineTube, binormal, normal, position2;
  18849. if ( extrudePath ) {
  18850. extrudePts = extrudePath.getSpacedPoints( steps );
  18851. extrudeByPath = true;
  18852. bevelEnabled = false; // bevels not supported for path extrusion
  18853. // SETUP TNB variables
  18854. // Reuse TNB from TubeGeomtry for now.
  18855. // TODO1 - have a .isClosed in spline?
  18856. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18857. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18858. binormal = new THREE.Vector3();
  18859. normal = new THREE.Vector3();
  18860. position2 = new THREE.Vector3();
  18861. }
  18862. // Safeguards if bevels are not enabled
  18863. if ( ! bevelEnabled ) {
  18864. bevelSegments = 0;
  18865. bevelThickness = 0;
  18866. bevelSize = 0;
  18867. }
  18868. // Variables initalization
  18869. var ahole, h, hl; // looping of holes
  18870. var scope = this;
  18871. var bevelPoints = [];
  18872. var shapesOffset = this.vertices.length;
  18873. var shapePoints = shape.extractPoints( curveSegments );
  18874. var vertices = shapePoints.shape;
  18875. var holes = shapePoints.holes;
  18876. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18877. if ( reverse ) {
  18878. vertices = vertices.reverse();
  18879. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18880. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18881. ahole = holes[ h ];
  18882. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18883. holes[ h ] = ahole.reverse();
  18884. }
  18885. }
  18886. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18887. }
  18888. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18889. /* Vertices */
  18890. var contour = vertices; // vertices has all points but contour has only points of circumference
  18891. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18892. ahole = holes[ h ];
  18893. vertices = vertices.concat( ahole );
  18894. }
  18895. function scalePt2 ( pt, vec, size ) {
  18896. if ( !vec ) console.log( "die" );
  18897. return vec.clone().multiplyScalar( size ).add( pt );
  18898. }
  18899. var b, bs, t, z,
  18900. vert, vlen = vertices.length,
  18901. face, flen = faces.length,
  18902. cont, clen = contour.length;
  18903. // Find directions for point movement
  18904. var RAD_TO_DEGREES = 180 / Math.PI;
  18905. function getBevelVec( pt_i, pt_j, pt_k ) {
  18906. // Algorithm 2
  18907. return getBevelVec2( pt_i, pt_j, pt_k );
  18908. }
  18909. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18910. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18911. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18912. if ( anglea > angleb ) {
  18913. angleb += Math.PI * 2;
  18914. }
  18915. var anglec = ( anglea + angleb ) / 2;
  18916. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18917. var x = - Math.cos( anglec );
  18918. var y = - Math.sin( anglec );
  18919. var vec = new THREE.Vector2( x, y ); //.normalize();
  18920. return vec;
  18921. }
  18922. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18923. var a = THREE.ExtrudeGeometry.__v1,
  18924. b = THREE.ExtrudeGeometry.__v2,
  18925. v_hat = THREE.ExtrudeGeometry.__v3,
  18926. w_hat = THREE.ExtrudeGeometry.__v4,
  18927. p = THREE.ExtrudeGeometry.__v5,
  18928. q = THREE.ExtrudeGeometry.__v6,
  18929. v, w,
  18930. v_dot_w_hat, q_sub_p_dot_w_hat,
  18931. s, intersection;
  18932. // good reading for line-line intersection
  18933. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18934. // define a as vector j->i
  18935. // define b as vectot k->i
  18936. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18937. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18938. // get unit vectors
  18939. v = a.normalize();
  18940. w = b.normalize();
  18941. // normals from pt i
  18942. v_hat.set( -v.y, v.x );
  18943. w_hat.set( w.y, -w.x );
  18944. // pts from i
  18945. p.copy( pt_i ).add( v_hat );
  18946. q.copy( pt_i ).add( w_hat );
  18947. if ( p.equals( q ) ) {
  18948. //console.log("Warning: lines are straight");
  18949. return w_hat.clone();
  18950. }
  18951. // Points from j, k. helps prevents points cross overover most of the time
  18952. p.copy( pt_j ).add( v_hat );
  18953. q.copy( pt_k ).add( w_hat );
  18954. v_dot_w_hat = v.dot( w_hat );
  18955. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  18956. // We should not reach these conditions
  18957. if ( v_dot_w_hat === 0 ) {
  18958. console.log( "Either infinite or no solutions!" );
  18959. if ( q_sub_p_dot_w_hat === 0 ) {
  18960. console.log( "Its finite solutions." );
  18961. } else {
  18962. console.log( "Too bad, no solutions." );
  18963. }
  18964. }
  18965. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18966. if ( s < 0 ) {
  18967. // in case of emergecy, revert to algorithm 1.
  18968. return getBevelVec1( pt_i, pt_j, pt_k );
  18969. }
  18970. intersection = v.multiplyScalar( s ).add( p );
  18971. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18972. }
  18973. var contourMovements = [];
  18974. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18975. if ( j === il ) j = 0;
  18976. if ( k === il ) k = 0;
  18977. // (j)---(i)---(k)
  18978. // console.log('i,j,k', i, j , k)
  18979. var pt_i = contour[ i ];
  18980. var pt_j = contour[ j ];
  18981. var pt_k = contour[ k ];
  18982. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18983. }
  18984. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18985. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18986. ahole = holes[ h ];
  18987. oneHoleMovements = [];
  18988. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18989. if ( j === il ) j = 0;
  18990. if ( k === il ) k = 0;
  18991. // (j)---(i)---(k)
  18992. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18993. }
  18994. holesMovements.push( oneHoleMovements );
  18995. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18996. }
  18997. // Loop bevelSegments, 1 for the front, 1 for the back
  18998. for ( b = 0; b < bevelSegments; b ++ ) {
  18999. //for ( b = bevelSegments; b > 0; b -- ) {
  19000. t = b / bevelSegments;
  19001. z = bevelThickness * ( 1 - t );
  19002. //z = bevelThickness * t;
  19003. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  19004. //bs = bevelSize * t ; // linear
  19005. // contract shape
  19006. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19007. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19008. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  19009. v( vert.x, vert.y, - z );
  19010. }
  19011. // expand holes
  19012. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19013. ahole = holes[ h ];
  19014. oneHoleMovements = holesMovements[ h ];
  19015. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19016. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19017. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  19018. v( vert.x, vert.y, -z );
  19019. }
  19020. }
  19021. }
  19022. bs = bevelSize;
  19023. // Back facing vertices
  19024. for ( i = 0; i < vlen; i ++ ) {
  19025. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19026. if ( !extrudeByPath ) {
  19027. v( vert.x, vert.y, 0 );
  19028. } else {
  19029. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19030. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19031. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19032. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  19033. v( position2.x, position2.y, position2.z );
  19034. }
  19035. }
  19036. // Add stepped vertices...
  19037. // Including front facing vertices
  19038. var s;
  19039. for ( s = 1; s <= steps; s ++ ) {
  19040. for ( i = 0; i < vlen; i ++ ) {
  19041. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19042. if ( !extrudeByPath ) {
  19043. v( vert.x, vert.y, amount / steps * s );
  19044. } else {
  19045. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19046. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19047. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19048. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19049. v( position2.x, position2.y, position2.z );
  19050. }
  19051. }
  19052. }
  19053. // Add bevel segments planes
  19054. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19055. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19056. t = b / bevelSegments;
  19057. z = bevelThickness * ( 1 - t );
  19058. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19059. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19060. // contract shape
  19061. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19062. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19063. v( vert.x, vert.y, amount + z );
  19064. }
  19065. // expand holes
  19066. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19067. ahole = holes[ h ];
  19068. oneHoleMovements = holesMovements[ h ];
  19069. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19070. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19071. if ( !extrudeByPath ) {
  19072. v( vert.x, vert.y, amount + z );
  19073. } else {
  19074. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19075. }
  19076. }
  19077. }
  19078. }
  19079. /* Faces */
  19080. // Top and bottom faces
  19081. buildLidFaces();
  19082. // Sides faces
  19083. buildSideFaces();
  19084. ///// Internal functions
  19085. function buildLidFaces() {
  19086. if ( bevelEnabled ) {
  19087. var layer = 0 ; // steps + 1
  19088. var offset = vlen * layer;
  19089. // Bottom faces
  19090. for ( i = 0; i < flen; i ++ ) {
  19091. face = faces[ i ];
  19092. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19093. }
  19094. layer = steps + bevelSegments * 2;
  19095. offset = vlen * layer;
  19096. // Top faces
  19097. for ( i = 0; i < flen; i ++ ) {
  19098. face = faces[ i ];
  19099. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19100. }
  19101. } else {
  19102. // Bottom faces
  19103. for ( i = 0; i < flen; i++ ) {
  19104. face = faces[ i ];
  19105. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19106. }
  19107. // Top faces
  19108. for ( i = 0; i < flen; i ++ ) {
  19109. face = faces[ i ];
  19110. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19111. }
  19112. }
  19113. }
  19114. // Create faces for the z-sides of the shape
  19115. function buildSideFaces() {
  19116. var layeroffset = 0;
  19117. sidewalls( contour, layeroffset );
  19118. layeroffset += contour.length;
  19119. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19120. ahole = holes[ h ];
  19121. sidewalls( ahole, layeroffset );
  19122. //, true
  19123. layeroffset += ahole.length;
  19124. }
  19125. }
  19126. function sidewalls( contour, layeroffset ) {
  19127. var j, k;
  19128. i = contour.length;
  19129. while ( --i >= 0 ) {
  19130. j = i;
  19131. k = i - 1;
  19132. if ( k < 0 ) k = contour.length - 1;
  19133. //console.log('b', i,j, i-1, k,vertices.length);
  19134. var s = 0, sl = steps + bevelSegments * 2;
  19135. for ( s = 0; s < sl; s ++ ) {
  19136. var slen1 = vlen * s;
  19137. var slen2 = vlen * ( s + 1 );
  19138. var a = layeroffset + j + slen1,
  19139. b = layeroffset + k + slen1,
  19140. c = layeroffset + k + slen2,
  19141. d = layeroffset + j + slen2;
  19142. f4( a, b, c, d, contour, s, sl, j, k );
  19143. }
  19144. }
  19145. }
  19146. function v( x, y, z ) {
  19147. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19148. }
  19149. function f3( a, b, c, isBottom ) {
  19150. a += shapesOffset;
  19151. b += shapesOffset;
  19152. c += shapesOffset;
  19153. // normal, color, material
  19154. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19155. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19156. scope.faceVertexUvs[ 0 ].push( uvs );
  19157. }
  19158. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19159. a += shapesOffset;
  19160. b += shapesOffset;
  19161. c += shapesOffset;
  19162. d += shapesOffset;
  19163. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  19164. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  19165. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19166. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19167. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  19168. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  19169. }
  19170. };
  19171. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19172. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19173. var ax = geometry.vertices[ indexA ].x,
  19174. ay = geometry.vertices[ indexA ].y,
  19175. bx = geometry.vertices[ indexB ].x,
  19176. by = geometry.vertices[ indexB ].y,
  19177. cx = geometry.vertices[ indexC ].x,
  19178. cy = geometry.vertices[ indexC ].y;
  19179. return [
  19180. new THREE.Vector2( ax, ay ),
  19181. new THREE.Vector2( bx, by ),
  19182. new THREE.Vector2( cx, cy )
  19183. ];
  19184. },
  19185. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19186. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19187. },
  19188. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19189. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19190. contourIndex1, contourIndex2 ) {
  19191. var ax = geometry.vertices[ indexA ].x,
  19192. ay = geometry.vertices[ indexA ].y,
  19193. az = geometry.vertices[ indexA ].z,
  19194. bx = geometry.vertices[ indexB ].x,
  19195. by = geometry.vertices[ indexB ].y,
  19196. bz = geometry.vertices[ indexB ].z,
  19197. cx = geometry.vertices[ indexC ].x,
  19198. cy = geometry.vertices[ indexC ].y,
  19199. cz = geometry.vertices[ indexC ].z,
  19200. dx = geometry.vertices[ indexD ].x,
  19201. dy = geometry.vertices[ indexD ].y,
  19202. dz = geometry.vertices[ indexD ].z;
  19203. if ( Math.abs( ay - by ) < 0.01 ) {
  19204. return [
  19205. new THREE.Vector2( ax, 1 - az ),
  19206. new THREE.Vector2( bx, 1 - bz ),
  19207. new THREE.Vector2( cx, 1 - cz ),
  19208. new THREE.Vector2( dx, 1 - dz )
  19209. ];
  19210. } else {
  19211. return [
  19212. new THREE.Vector2( ay, 1 - az ),
  19213. new THREE.Vector2( by, 1 - bz ),
  19214. new THREE.Vector2( cy, 1 - cz ),
  19215. new THREE.Vector2( dy, 1 - dz )
  19216. ];
  19217. }
  19218. }
  19219. };
  19220. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19221. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19222. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19223. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19224. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19225. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19226. /**
  19227. * @author jonobr1 / http://jonobr1.com
  19228. *
  19229. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19230. * ExtrudeGeometry.
  19231. *
  19232. * parameters = {
  19233. *
  19234. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19235. *
  19236. * material: <int> // material index for front and back faces
  19237. * uvGenerator: <Object> // object that provides UV generator functions
  19238. *
  19239. * }
  19240. **/
  19241. THREE.ShapeGeometry = function ( shapes, options ) {
  19242. THREE.Geometry.call( this );
  19243. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19244. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19245. this.addShapeList( shapes, options );
  19246. this.computeCentroids();
  19247. this.computeFaceNormals();
  19248. };
  19249. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19250. /**
  19251. * Add an array of shapes to THREE.ShapeGeometry.
  19252. */
  19253. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19254. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19255. this.addShape( shapes[ i ], options );
  19256. }
  19257. return this;
  19258. };
  19259. /**
  19260. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19261. */
  19262. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19263. if ( options === undefined ) options = {};
  19264. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19265. var material = options.material;
  19266. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19267. var shapebb = this.shapebb;
  19268. //
  19269. var i, l, hole, s;
  19270. var shapesOffset = this.vertices.length;
  19271. var shapePoints = shape.extractPoints( curveSegments );
  19272. var vertices = shapePoints.shape;
  19273. var holes = shapePoints.holes;
  19274. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19275. if ( reverse ) {
  19276. vertices = vertices.reverse();
  19277. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19278. for ( i = 0, l = holes.length; i < l; i++ ) {
  19279. hole = holes[ i ];
  19280. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19281. holes[ i ] = hole.reverse();
  19282. }
  19283. }
  19284. reverse = false;
  19285. }
  19286. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19287. // Vertices
  19288. var contour = vertices;
  19289. for ( i = 0, l = holes.length; i < l; i++ ) {
  19290. hole = holes[ i ];
  19291. vertices = vertices.concat( hole );
  19292. }
  19293. //
  19294. var vert, vlen = vertices.length;
  19295. var face, flen = faces.length;
  19296. var cont, clen = contour.length;
  19297. for ( i = 0; i < vlen; i++ ) {
  19298. vert = vertices[ i ];
  19299. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19300. }
  19301. for ( i = 0; i < flen; i++ ) {
  19302. face = faces[ i ];
  19303. var a = face[ 0 ] + shapesOffset;
  19304. var b = face[ 1 ] + shapesOffset;
  19305. var c = face[ 2 ] + shapesOffset;
  19306. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19307. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19308. }
  19309. };
  19310. /**
  19311. * @author astrodud / http://astrodud.isgreat.org/
  19312. * @author zz85 / https://github.com/zz85
  19313. * @author bhouston / http://exocortex.com
  19314. */
  19315. // points - to create a closed torus, one must use a set of points
  19316. // like so: [ a, b, c, d, a ], see first is the same as last.
  19317. // segments - the number of circumference segments to create
  19318. // phiStart - the starting radian
  19319. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19320. // 2*pi is a closed lathe, less than 2PI is a portion.
  19321. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19322. THREE.Geometry.call( this );
  19323. segments = segments || 12;
  19324. phiStart = phiStart || 0;
  19325. phiLength = phiLength || 2 * Math.PI;
  19326. var inversePointLength = 1.0 / ( points.length - 1 );
  19327. var inverseSegments = 1.0 / segments;
  19328. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19329. var phi = phiStart + i * inverseSegments * phiLength;
  19330. var c = Math.cos( phi ),
  19331. s = Math.sin( phi );
  19332. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19333. var pt = points[ j ];
  19334. var vertex = new THREE.Vector3();
  19335. vertex.x = c * pt.x - s * pt.y;
  19336. vertex.y = s * pt.x + c * pt.y;
  19337. vertex.z = pt.z;
  19338. this.vertices.push( vertex );
  19339. }
  19340. }
  19341. var np = points.length;
  19342. for ( var i = 0, il = segments; i < il; i ++ ) {
  19343. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19344. var base = j + np * i;
  19345. var a = base;
  19346. var b = base + np;
  19347. var c = base + 1 + np;
  19348. var d = base + 1;
  19349. var u0 = i * inverseSegments;
  19350. var v0 = j * inversePointLength;
  19351. var u1 = u0 + inverseSegments;
  19352. var v1 = v0 + inversePointLength;
  19353. this.faces.push( new THREE.Face3( a, b, d ) );
  19354. this.faceVertexUvs[ 0 ].push( [
  19355. new THREE.Vector2( u0, v0 ),
  19356. new THREE.Vector2( u1, v0 ),
  19357. new THREE.Vector2( u0, v1 )
  19358. ] );
  19359. this.faces.push( new THREE.Face3( b, c, d ) );
  19360. this.faceVertexUvs[ 0 ].push( [
  19361. new THREE.Vector2( u1, v0 ),
  19362. new THREE.Vector2( u1, v1 ),
  19363. new THREE.Vector2( u0, v1 )
  19364. ] );
  19365. }
  19366. }
  19367. this.mergeVertices();
  19368. this.computeCentroids();
  19369. this.computeFaceNormals();
  19370. this.computeVertexNormals();
  19371. };
  19372. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19373. /**
  19374. * @author mrdoob / http://mrdoob.com/
  19375. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19376. */
  19377. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19378. THREE.Geometry.call( this );
  19379. this.width = width;
  19380. this.height = height;
  19381. this.widthSegments = widthSegments || 1;
  19382. this.heightSegments = heightSegments || 1;
  19383. var ix, iz;
  19384. var width_half = width / 2;
  19385. var height_half = height / 2;
  19386. var gridX = this.widthSegments;
  19387. var gridZ = this.heightSegments;
  19388. var gridX1 = gridX + 1;
  19389. var gridZ1 = gridZ + 1;
  19390. var segment_width = this.width / gridX;
  19391. var segment_height = this.height / gridZ;
  19392. var normal = new THREE.Vector3( 0, 0, 1 );
  19393. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19394. for ( ix = 0; ix < gridX1; ix ++ ) {
  19395. var x = ix * segment_width - width_half;
  19396. var y = iz * segment_height - height_half;
  19397. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19398. }
  19399. }
  19400. for ( iz = 0; iz < gridZ; iz ++ ) {
  19401. for ( ix = 0; ix < gridX; ix ++ ) {
  19402. var a = ix + gridX1 * iz;
  19403. var b = ix + gridX1 * ( iz + 1 );
  19404. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19405. var d = ( ix + 1 ) + gridX1 * iz;
  19406. var uva = new THREE.Vector2( ix / gridX, 1 - iz / gridZ );
  19407. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ );
  19408. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ );
  19409. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ );
  19410. var face = new THREE.Face3( a, b, d );
  19411. face.normal.copy( normal );
  19412. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19413. this.faces.push( face );
  19414. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19415. face = new THREE.Face3( b, c, d );
  19416. face.normal.copy( normal );
  19417. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19418. this.faces.push( face );
  19419. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19420. }
  19421. }
  19422. this.computeCentroids();
  19423. };
  19424. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19425. /**
  19426. * @author Kaleb Murphy
  19427. */
  19428. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19429. THREE.Geometry.call( this );
  19430. innerRadius = innerRadius || 0;
  19431. outerRadius = outerRadius || 50;
  19432. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19433. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19434. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19435. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19436. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19437. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19438. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19439. var vertex = new THREE.Vector3();
  19440. var segment = thetaStart + o / thetaSegments * thetaLength;
  19441. vertex.x = radius * Math.cos( segment );
  19442. vertex.y = radius * Math.sin( segment );
  19443. this.vertices.push( vertex );
  19444. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  19445. }
  19446. radius += radiusStep;
  19447. }
  19448. var n = new THREE.Vector3( 0, 0, 1 );
  19449. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19450. var thetaSegment = i * thetaSegments;
  19451. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19452. var segment = o + thetaSegment;
  19453. var v1 = segment + i;
  19454. var v2 = segment + thetaSegments + i;
  19455. var v3 = segment + thetaSegments + 1 + i;
  19456. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19457. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19458. v1 = segment + i;
  19459. v2 = segment + thetaSegments + 1 + i;
  19460. v3 = segment + 1 + i;
  19461. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19462. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19463. }
  19464. }
  19465. this.computeCentroids();
  19466. this.computeFaceNormals();
  19467. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19468. };
  19469. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19470. /**
  19471. * @author mrdoob / http://mrdoob.com/
  19472. */
  19473. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19474. THREE.Geometry.call( this );
  19475. this.radius = radius = radius || 50;
  19476. this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19477. this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19478. this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0;
  19479. this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19480. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19481. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19482. var x, y, vertices = [], uvs = [];
  19483. for ( y = 0; y <= heightSegments; y ++ ) {
  19484. var verticesRow = [];
  19485. var uvsRow = [];
  19486. for ( x = 0; x <= widthSegments; x ++ ) {
  19487. var u = x / widthSegments;
  19488. var v = y / heightSegments;
  19489. var vertex = new THREE.Vector3();
  19490. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19491. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19492. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19493. this.vertices.push( vertex );
  19494. verticesRow.push( this.vertices.length - 1 );
  19495. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19496. }
  19497. vertices.push( verticesRow );
  19498. uvs.push( uvsRow );
  19499. }
  19500. for ( y = 0; y < this.heightSegments; y ++ ) {
  19501. for ( x = 0; x < this.widthSegments; x ++ ) {
  19502. var v1 = vertices[ y ][ x + 1 ];
  19503. var v2 = vertices[ y ][ x ];
  19504. var v3 = vertices[ y + 1 ][ x ];
  19505. var v4 = vertices[ y + 1 ][ x + 1 ];
  19506. var n1 = this.vertices[ v1 ].clone().normalize();
  19507. var n2 = this.vertices[ v2 ].clone().normalize();
  19508. var n3 = this.vertices[ v3 ].clone().normalize();
  19509. var n4 = this.vertices[ v4 ].clone().normalize();
  19510. var uv1 = uvs[ y ][ x + 1 ].clone();
  19511. var uv2 = uvs[ y ][ x ].clone();
  19512. var uv3 = uvs[ y + 1 ][ x ].clone();
  19513. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19514. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19515. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19516. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19517. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19518. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19519. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19520. } else {
  19521. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19522. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19523. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2, n3, n4 ] ) );
  19524. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19525. }
  19526. }
  19527. }
  19528. this.computeCentroids();
  19529. this.computeFaceNormals();
  19530. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19531. };
  19532. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19533. /**
  19534. * @author zz85 / http://www.lab4games.net/zz85/blog
  19535. * @author alteredq / http://alteredqualia.com/
  19536. *
  19537. * For creating 3D text geometry in three.js
  19538. *
  19539. * Text = 3D Text
  19540. *
  19541. * parameters = {
  19542. * size: <float>, // size of the text
  19543. * height: <float>, // thickness to extrude text
  19544. * curveSegments: <int>, // number of points on the curves
  19545. *
  19546. * font: <string>, // font name
  19547. * weight: <string>, // font weight (normal, bold)
  19548. * style: <string>, // font style (normal, italics)
  19549. *
  19550. * bevelEnabled: <bool>, // turn on bevel
  19551. * bevelThickness: <float>, // how deep into text bevel goes
  19552. * bevelSize: <float>, // how far from text outline is bevel
  19553. * }
  19554. *
  19555. */
  19556. /* Usage Examples
  19557. // TextGeometry wrapper
  19558. var text3d = new TextGeometry( text, options );
  19559. // Complete manner
  19560. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19561. var text3d = new ExtrudeGeometry( textShapes, options );
  19562. */
  19563. THREE.TextGeometry = function ( text, parameters ) {
  19564. parameters = parameters || {};
  19565. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19566. // translate parameters to ExtrudeGeometry API
  19567. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19568. // defaults
  19569. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19570. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19571. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19572. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19573. };
  19574. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19575. /**
  19576. * @author oosmoxiecode
  19577. * @author mrdoob / http://mrdoob.com/
  19578. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19579. */
  19580. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19581. THREE.Geometry.call( this );
  19582. var scope = this;
  19583. this.radius = radius || 100;
  19584. this.tube = tube || 40;
  19585. this.radialSegments = radialSegments || 8;
  19586. this.tubularSegments = tubularSegments || 6;
  19587. this.arc = arc || Math.PI * 2;
  19588. var center = new THREE.Vector3(), uvs = [], normals = [];
  19589. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19590. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19591. var u = i / this.tubularSegments * this.arc;
  19592. var v = j / this.radialSegments * Math.PI * 2;
  19593. center.x = this.radius * Math.cos( u );
  19594. center.y = this.radius * Math.sin( u );
  19595. var vertex = new THREE.Vector3();
  19596. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19597. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19598. vertex.z = this.tube * Math.sin( v );
  19599. this.vertices.push( vertex );
  19600. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19601. normals.push( vertex.clone().sub( center ).normalize() );
  19602. }
  19603. }
  19604. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19605. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19606. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19607. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19608. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19609. var d = ( this.tubularSegments + 1 ) * j + i;
  19610. var face = new THREE.Face3( a, b, d, [ normals[ a ], normals[ b ], normals[ d ] ] );
  19611. face.normal.add( normals[ a ] );
  19612. face.normal.add( normals[ b ] );
  19613. face.normal.add( normals[ d ] );
  19614. face.normal.normalize();
  19615. this.faces.push( face );
  19616. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  19617. face = new THREE.Face3( b, c, d, [ normals[ b ], normals[ c ], normals[ d ] ] );
  19618. face.normal.add( normals[ b ] );
  19619. face.normal.add( normals[ c ] );
  19620. face.normal.add( normals[ d ] );
  19621. face.normal.normalize();
  19622. this.faces.push( face );
  19623. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19624. }
  19625. }
  19626. this.computeCentroids();
  19627. };
  19628. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19629. /**
  19630. * @author oosmoxiecode
  19631. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19632. */
  19633. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19634. THREE.Geometry.call( this );
  19635. var scope = this;
  19636. this.radius = radius || 100;
  19637. this.tube = tube || 40;
  19638. this.radialSegments = radialSegments || 64;
  19639. this.tubularSegments = tubularSegments || 8;
  19640. this.p = p || 2;
  19641. this.q = q || 3;
  19642. this.heightScale = heightScale || 1;
  19643. this.grid = new Array( this.radialSegments );
  19644. var tang = new THREE.Vector3();
  19645. var n = new THREE.Vector3();
  19646. var bitan = new THREE.Vector3();
  19647. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19648. this.grid[ i ] = new Array( this.tubularSegments );
  19649. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19650. var p1 = getPos( u, this.q, this.p, this.radius, this.heightScale );
  19651. var p2 = getPos( u + 0.01, this.q, this.p, this.radius, this.heightScale );
  19652. tang.subVectors( p2, p1 );
  19653. n.addVectors( p2, p1 );
  19654. bitan.crossVectors( tang, n );
  19655. n.crossVectors( bitan, tang );
  19656. bitan.normalize();
  19657. n.normalize();
  19658. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19659. var v = j / this.tubularSegments * 2 * Math.PI;
  19660. var cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19661. var cy = this.tube * Math.sin( v );
  19662. var pos = new THREE.Vector3();
  19663. pos.x = p1.x + cx * n.x + cy * bitan.x;
  19664. pos.y = p1.y + cx * n.y + cy * bitan.y;
  19665. pos.z = p1.z + cx * n.z + cy * bitan.z;
  19666. this.grid[ i ][ j ] = scope.vertices.push( pos ) - 1;
  19667. }
  19668. }
  19669. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19670. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19671. var ip = ( i + 1 ) % this.radialSegments;
  19672. var jp = ( j + 1 ) % this.tubularSegments;
  19673. var a = this.grid[ i ][ j ];
  19674. var b = this.grid[ ip ][ j ];
  19675. var c = this.grid[ ip ][ jp ];
  19676. var d = this.grid[ i ][ jp ];
  19677. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19678. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19679. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19680. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19681. this.faces.push( new THREE.Face3( a, b, d ) );
  19682. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19683. this.faces.push( new THREE.Face3( b, c, d ) );
  19684. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19685. }
  19686. }
  19687. this.computeCentroids();
  19688. this.computeFaceNormals();
  19689. this.computeVertexNormals();
  19690. function getPos( u, in_q, in_p, radius, heightScale ) {
  19691. var cu = Math.cos( u );
  19692. var su = Math.sin( u );
  19693. var quOverP = in_q / in_p * u;
  19694. var cs = Math.cos( quOverP );
  19695. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19696. var ty = radius * ( 2 + cs ) * su * 0.5;
  19697. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19698. return new THREE.Vector3( tx, ty, tz );
  19699. }
  19700. };
  19701. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19702. /**
  19703. * @author WestLangley / https://github.com/WestLangley
  19704. * @author zz85 / https://github.com/zz85
  19705. * @author miningold / https://github.com/miningold
  19706. *
  19707. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19708. *
  19709. * Creates a tube which extrudes along a 3d spline
  19710. *
  19711. * Uses parallel transport frames as described in
  19712. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19713. */
  19714. THREE.TubeGeometry = function( path, segments, radius, radialSegments, closed ) {
  19715. THREE.Geometry.call( this );
  19716. this.path = path;
  19717. this.segments = segments || 64;
  19718. this.radius = radius || 1;
  19719. this.radialSegments = radialSegments || 8;
  19720. this.closed = closed || false;
  19721. this.grid = [];
  19722. var scope = this,
  19723. tangent,
  19724. normal,
  19725. binormal,
  19726. numpoints = this.segments + 1,
  19727. x, y, z,
  19728. tx, ty, tz,
  19729. u, v,
  19730. cx, cy,
  19731. pos, pos2 = new THREE.Vector3(),
  19732. i, j,
  19733. ip, jp,
  19734. a, b, c, d,
  19735. uva, uvb, uvc, uvd;
  19736. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19737. tangents = frames.tangents,
  19738. normals = frames.normals,
  19739. binormals = frames.binormals;
  19740. // proxy internals
  19741. this.tangents = tangents;
  19742. this.normals = normals;
  19743. this.binormals = binormals;
  19744. function vert( x, y, z ) {
  19745. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19746. }
  19747. // consruct the grid
  19748. for ( i = 0; i < numpoints; i++ ) {
  19749. this.grid[ i ] = [];
  19750. u = i / ( numpoints - 1 );
  19751. pos = path.getPointAt( u );
  19752. tangent = tangents[ i ];
  19753. normal = normals[ i ];
  19754. binormal = binormals[ i ];
  19755. for ( j = 0; j < this.radialSegments; j++ ) {
  19756. v = j / this.radialSegments * 2 * Math.PI;
  19757. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19758. cy = this.radius * Math.sin( v );
  19759. pos2.copy( pos );
  19760. pos2.x += cx * normal.x + cy * binormal.x;
  19761. pos2.y += cx * normal.y + cy * binormal.y;
  19762. pos2.z += cx * normal.z + cy * binormal.z;
  19763. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19764. }
  19765. }
  19766. // construct the mesh
  19767. for ( i = 0; i < this.segments; i++ ) {
  19768. for ( j = 0; j < this.radialSegments; j++ ) {
  19769. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  19770. jp = (j + 1) % this.radialSegments;
  19771. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19772. b = this.grid[ ip ][ j ];
  19773. c = this.grid[ ip ][ jp ];
  19774. d = this.grid[ i ][ jp ];
  19775. uva = new THREE.Vector2( i / this.segments, j / this.radialSegments );
  19776. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radialSegments );
  19777. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radialSegments );
  19778. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radialSegments );
  19779. this.faces.push( new THREE.Face3( a, b, d ) );
  19780. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19781. this.faces.push( new THREE.Face3( b, c, d ) );
  19782. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19783. }
  19784. }
  19785. this.computeCentroids();
  19786. this.computeFaceNormals();
  19787. this.computeVertexNormals();
  19788. };
  19789. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19790. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19791. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19792. var tangent = new THREE.Vector3(),
  19793. normal = new THREE.Vector3(),
  19794. binormal = new THREE.Vector3(),
  19795. tangents = [],
  19796. normals = [],
  19797. binormals = [],
  19798. vec = new THREE.Vector3(),
  19799. mat = new THREE.Matrix4(),
  19800. numpoints = segments + 1,
  19801. theta,
  19802. epsilon = 0.0001,
  19803. smallest,
  19804. tx, ty, tz,
  19805. i, u, v;
  19806. // expose internals
  19807. this.tangents = tangents;
  19808. this.normals = normals;
  19809. this.binormals = binormals;
  19810. // compute the tangent vectors for each segment on the path
  19811. for ( i = 0; i < numpoints; i++ ) {
  19812. u = i / ( numpoints - 1 );
  19813. tangents[ i ] = path.getTangentAt( u );
  19814. tangents[ i ].normalize();
  19815. }
  19816. initialNormal3();
  19817. function initialNormal1(lastBinormal) {
  19818. // fixed start binormal. Has dangers of 0 vectors
  19819. normals[ 0 ] = new THREE.Vector3();
  19820. binormals[ 0 ] = new THREE.Vector3();
  19821. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19822. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19823. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19824. }
  19825. function initialNormal2() {
  19826. // This uses the Frenet-Serret formula for deriving binormal
  19827. var t2 = path.getTangentAt( epsilon );
  19828. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19829. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19830. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19831. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19832. }
  19833. function initialNormal3() {
  19834. // select an initial normal vector perpenicular to the first tangent vector,
  19835. // and in the direction of the smallest tangent xyz component
  19836. normals[ 0 ] = new THREE.Vector3();
  19837. binormals[ 0 ] = new THREE.Vector3();
  19838. smallest = Number.MAX_VALUE;
  19839. tx = Math.abs( tangents[ 0 ].x );
  19840. ty = Math.abs( tangents[ 0 ].y );
  19841. tz = Math.abs( tangents[ 0 ].z );
  19842. if ( tx <= smallest ) {
  19843. smallest = tx;
  19844. normal.set( 1, 0, 0 );
  19845. }
  19846. if ( ty <= smallest ) {
  19847. smallest = ty;
  19848. normal.set( 0, 1, 0 );
  19849. }
  19850. if ( tz <= smallest ) {
  19851. normal.set( 0, 0, 1 );
  19852. }
  19853. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19854. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19855. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19856. }
  19857. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19858. for ( i = 1; i < numpoints; i++ ) {
  19859. normals[ i ] = normals[ i-1 ].clone();
  19860. binormals[ i ] = binormals[ i-1 ].clone();
  19861. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  19862. if ( vec.length() > epsilon ) {
  19863. vec.normalize();
  19864. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  19865. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19866. }
  19867. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19868. }
  19869. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19870. if ( closed ) {
  19871. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  19872. theta /= ( numpoints - 1 );
  19873. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19874. theta = -theta;
  19875. }
  19876. for ( i = 1; i < numpoints; i++ ) {
  19877. // twist a little...
  19878. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19879. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19880. }
  19881. }
  19882. };
  19883. /**
  19884. * @author clockworkgeek / https://github.com/clockworkgeek
  19885. * @author timothypratley / https://github.com/timothypratley
  19886. * @author WestLangley / http://github.com/WestLangley
  19887. */
  19888. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19889. THREE.Geometry.call( this );
  19890. radius = radius || 1;
  19891. detail = detail || 0;
  19892. var that = this;
  19893. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19894. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19895. }
  19896. var midpoints = [], p = this.vertices;
  19897. var f = [];
  19898. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19899. var v1 = p[ faces[ i ][ 0 ] ];
  19900. var v2 = p[ faces[ i ][ 1 ] ];
  19901. var v3 = p[ faces[ i ][ 2 ] ];
  19902. f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19903. }
  19904. for ( var i = 0, l = f.length; i < l; i ++ ) {
  19905. subdivide(f[ i ], detail);
  19906. }
  19907. // Handle case when face straddles the seam
  19908. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  19909. var uvs = this.faceVertexUvs[ 0 ][ i ];
  19910. var x0 = uvs[ 0 ].x;
  19911. var x1 = uvs[ 1 ].x;
  19912. var x2 = uvs[ 2 ].x;
  19913. var max = Math.max( x0, Math.max( x1, x2 ) );
  19914. var min = Math.min( x0, Math.min( x1, x2 ) );
  19915. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  19916. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  19917. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  19918. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  19919. }
  19920. }
  19921. // Apply radius
  19922. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19923. this.vertices[ i ].multiplyScalar( radius );
  19924. }
  19925. // Merge vertices
  19926. this.mergeVertices();
  19927. this.computeCentroids();
  19928. this.computeFaceNormals();
  19929. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19930. // Project vector onto sphere's surface
  19931. function prepare( vector ) {
  19932. var vertex = vector.normalize().clone();
  19933. vertex.index = that.vertices.push( vertex ) - 1;
  19934. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19935. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19936. var v = inclination( vector ) / Math.PI + 0.5;
  19937. vertex.uv = new THREE.Vector2( u, 1 - v );
  19938. return vertex;
  19939. }
  19940. // Approximate a curved face with recursively sub-divided triangles.
  19941. function make( v1, v2, v3 ) {
  19942. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19943. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19944. that.faces.push( face );
  19945. var azi = azimuth( face.centroid );
  19946. that.faceVertexUvs[ 0 ].push( [
  19947. correctUV( v1.uv, v1, azi ),
  19948. correctUV( v2.uv, v2, azi ),
  19949. correctUV( v3.uv, v3, azi )
  19950. ] );
  19951. }
  19952. // Analytically subdivide a face to the required detail level.
  19953. function subdivide(face, detail ) {
  19954. var cols = Math.pow(2, detail);
  19955. var cells = Math.pow(4, detail);
  19956. var a = prepare( that.vertices[ face.a ] );
  19957. var b = prepare( that.vertices[ face.b ] );
  19958. var c = prepare( that.vertices[ face.c ] );
  19959. var v = [];
  19960. // Construct all of the vertices for this subdivision.
  19961. for ( var i = 0 ; i <= cols; i ++ ) {
  19962. v[ i ] = [];
  19963. var aj = prepare( a.clone().lerp( c, i / cols ) );
  19964. var bj = prepare( b.clone().lerp( c, i / cols ) );
  19965. var rows = cols - i;
  19966. for ( var j = 0; j <= rows; j ++) {
  19967. if ( j == 0 && i == cols ) {
  19968. v[ i ][ j ] = aj;
  19969. } else {
  19970. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  19971. }
  19972. }
  19973. }
  19974. // Construct all of the faces.
  19975. for ( var i = 0; i < cols ; i ++ ) {
  19976. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  19977. var k = Math.floor( j / 2 );
  19978. if ( j % 2 == 0 ) {
  19979. make(
  19980. v[ i ][ k + 1],
  19981. v[ i + 1 ][ k ],
  19982. v[ i ][ k ]
  19983. );
  19984. } else {
  19985. make(
  19986. v[ i ][ k + 1 ],
  19987. v[ i + 1][ k + 1],
  19988. v[ i + 1 ][ k ]
  19989. );
  19990. }
  19991. }
  19992. }
  19993. }
  19994. // Angle around the Y axis, counter-clockwise when looking from above.
  19995. function azimuth( vector ) {
  19996. return Math.atan2( vector.z, -vector.x );
  19997. }
  19998. // Angle above the XZ plane.
  19999. function inclination( vector ) {
  20000. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20001. }
  20002. // Texture fixing helper. Spheres have some odd behaviours.
  20003. function correctUV( uv, vector, azimuth ) {
  20004. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  20005. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  20006. return uv.clone();
  20007. }
  20008. };
  20009. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20010. /**
  20011. * @author timothypratley / https://github.com/timothypratley
  20012. */
  20013. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20014. this.radius = radius;
  20015. this.detail = detail;
  20016. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20017. var vertices = [
  20018. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  20019. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  20020. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  20021. ];
  20022. var faces = [
  20023. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  20024. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  20025. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  20026. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  20027. ];
  20028. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20029. };
  20030. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20031. /**
  20032. * @author timothypratley / https://github.com/timothypratley
  20033. */
  20034. THREE.OctahedronGeometry = function ( radius, detail ) {
  20035. var vertices = [
  20036. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  20037. ];
  20038. var faces = [
  20039. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  20040. ];
  20041. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20042. };
  20043. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20044. /**
  20045. * @author timothypratley / https://github.com/timothypratley
  20046. */
  20047. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20048. var vertices = [
  20049. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  20050. ];
  20051. var faces = [
  20052. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  20053. ];
  20054. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20055. };
  20056. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20057. /**
  20058. * @author zz85 / https://github.com/zz85
  20059. * Parametric Surfaces Geometry
  20060. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20061. *
  20062. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  20063. *
  20064. */
  20065. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  20066. THREE.Geometry.call( this );
  20067. var verts = this.vertices;
  20068. var faces = this.faces;
  20069. var uvs = this.faceVertexUvs[ 0 ];
  20070. var i, il, j, p;
  20071. var u, v;
  20072. var stackCount = stacks + 1;
  20073. var sliceCount = slices + 1;
  20074. for ( i = 0; i <= stacks; i ++ ) {
  20075. v = i / stacks;
  20076. for ( j = 0; j <= slices; j ++ ) {
  20077. u = j / slices;
  20078. p = func( u, v );
  20079. verts.push( p );
  20080. }
  20081. }
  20082. var a, b, c, d;
  20083. var uva, uvb, uvc, uvd;
  20084. for ( i = 0; i < stacks; i ++ ) {
  20085. for ( j = 0; j < slices; j ++ ) {
  20086. a = i * sliceCount + j;
  20087. b = i * sliceCount + j + 1;
  20088. c = (i + 1) * sliceCount + j + 1;
  20089. d = (i + 1) * sliceCount + j;
  20090. uva = new THREE.Vector2( j / slices, i / stacks );
  20091. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20092. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20093. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20094. faces.push( new THREE.Face3( a, b, d ) );
  20095. uvs.push( [ uva, uvb, uvd ] );
  20096. faces.push( new THREE.Face3( b, c, d ) );
  20097. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  20098. }
  20099. }
  20100. // console.log(this);
  20101. // magic bullet
  20102. // var diff = this.mergeVertices();
  20103. // console.log('removed ', diff, ' vertices by merging');
  20104. this.computeCentroids();
  20105. this.computeFaceNormals();
  20106. this.computeVertexNormals();
  20107. };
  20108. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20109. /**
  20110. * @author sroucheray / http://sroucheray.org/
  20111. * @author mrdoob / http://mrdoob.com/
  20112. */
  20113. THREE.AxisHelper = function ( size ) {
  20114. size = size || 1;
  20115. var geometry = new THREE.Geometry();
  20116. geometry.vertices.push(
  20117. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  20118. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  20119. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  20120. );
  20121. geometry.colors.push(
  20122. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20123. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20124. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20125. );
  20126. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20127. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20128. };
  20129. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20130. /**
  20131. * @author WestLangley / http://github.com/WestLangley
  20132. * @author zz85 / http://github.com/zz85
  20133. * @author bhouston / http://exocortex.com
  20134. *
  20135. * Creates an arrow for visualizing directions
  20136. *
  20137. * Parameters:
  20138. * dir - Vector3
  20139. * origin - Vector3
  20140. * length - Number
  20141. * hex - color in hex value
  20142. */
  20143. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  20144. // dir is assumed to be normalized
  20145. THREE.Object3D.call( this );
  20146. if ( hex === undefined ) hex = 0xffff00;
  20147. if ( length === undefined ) length = 1;
  20148. this.position = origin;
  20149. var lineGeometry = new THREE.Geometry();
  20150. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20151. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20152. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20153. this.line.matrixAutoUpdate = false;
  20154. this.add( this.line );
  20155. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  20156. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, 0.875, 0 ) );
  20157. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20158. this.cone.matrixAutoUpdate = false;
  20159. this.add( this.cone );
  20160. this.setDirection( dir );
  20161. this.setLength( length );
  20162. };
  20163. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20164. THREE.ArrowHelper.prototype.setDirection = function () {
  20165. var axis = new THREE.Vector3();
  20166. var radians;
  20167. return function ( dir ) {
  20168. // dir is assumed to be normalized
  20169. if ( dir.y > 0.99999 ) {
  20170. this.quaternion.set( 0, 0, 0, 1 );
  20171. } else if ( dir.y < - 0.99999 ) {
  20172. this.quaternion.set( 1, 0, 0, 0 );
  20173. } else {
  20174. axis.set( dir.z, 0, - dir.x ).normalize();
  20175. radians = Math.acos( dir.y );
  20176. this.quaternion.setFromAxisAngle( axis, radians );
  20177. }
  20178. };
  20179. }();
  20180. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20181. this.scale.set( length, length, length );
  20182. };
  20183. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20184. this.line.material.color.setHex( hex );
  20185. this.cone.material.color.setHex( hex );
  20186. };
  20187. /**
  20188. * @author mrdoob / http://mrdoob.com/
  20189. */
  20190. THREE.BoxHelper = function ( object ) {
  20191. // 5____4
  20192. // 1/___0/|
  20193. // | 6__|_7
  20194. // 2/___3/
  20195. var vertices = [
  20196. new THREE.Vector3( 1, 1, 1 ),
  20197. new THREE.Vector3( - 1, 1, 1 ),
  20198. new THREE.Vector3( - 1, - 1, 1 ),
  20199. new THREE.Vector3( 1, - 1, 1 ),
  20200. new THREE.Vector3( 1, 1, - 1 ),
  20201. new THREE.Vector3( - 1, 1, - 1 ),
  20202. new THREE.Vector3( - 1, - 1, - 1 ),
  20203. new THREE.Vector3( 1, - 1, - 1 )
  20204. ];
  20205. this.vertices = vertices;
  20206. // TODO: Wouldn't be nice if Line had .segments?
  20207. var geometry = new THREE.Geometry();
  20208. geometry.vertices.push(
  20209. vertices[ 0 ], vertices[ 1 ],
  20210. vertices[ 1 ], vertices[ 2 ],
  20211. vertices[ 2 ], vertices[ 3 ],
  20212. vertices[ 3 ], vertices[ 0 ],
  20213. vertices[ 4 ], vertices[ 5 ],
  20214. vertices[ 5 ], vertices[ 6 ],
  20215. vertices[ 6 ], vertices[ 7 ],
  20216. vertices[ 7 ], vertices[ 4 ],
  20217. vertices[ 0 ], vertices[ 4 ],
  20218. vertices[ 1 ], vertices[ 5 ],
  20219. vertices[ 2 ], vertices[ 6 ],
  20220. vertices[ 3 ], vertices[ 7 ]
  20221. );
  20222. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20223. if ( object !== undefined ) {
  20224. this.update( object );
  20225. }
  20226. };
  20227. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20228. THREE.BoxHelper.prototype.update = function ( object ) {
  20229. var geometry = object.geometry;
  20230. if ( geometry.boundingBox === null ) {
  20231. geometry.computeBoundingBox();
  20232. }
  20233. var min = geometry.boundingBox.min;
  20234. var max = geometry.boundingBox.max;
  20235. var vertices = this.vertices;
  20236. vertices[ 0 ].set( max.x, max.y, max.z );
  20237. vertices[ 1 ].set( min.x, max.y, max.z );
  20238. vertices[ 2 ].set( min.x, min.y, max.z );
  20239. vertices[ 3 ].set( max.x, min.y, max.z );
  20240. vertices[ 4 ].set( max.x, max.y, min.z );
  20241. vertices[ 5 ].set( min.x, max.y, min.z );
  20242. vertices[ 6 ].set( min.x, min.y, min.z );
  20243. vertices[ 7 ].set( max.x, min.y, min.z );
  20244. this.geometry.computeBoundingSphere();
  20245. this.geometry.verticesNeedUpdate = true;
  20246. this.matrixAutoUpdate = false;
  20247. this.matrixWorld = object.matrixWorld;
  20248. };
  20249. /**
  20250. * @author WestLangley / http://github.com/WestLangley
  20251. */
  20252. // a helper to show the world-axis-aligned bounding box for an object
  20253. THREE.BoundingBoxHelper = function ( object, hex ) {
  20254. var color = hex || 0x888888;
  20255. this.object = object;
  20256. this.box = new THREE.Box3();
  20257. THREE.Mesh.call( this, new THREE.CubeGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20258. };
  20259. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20260. THREE.BoundingBoxHelper.prototype.update = function () {
  20261. this.box.setFromObject( this.object );
  20262. this.box.size( this.scale );
  20263. this.box.center( this.position );
  20264. };
  20265. /**
  20266. * @author alteredq / http://alteredqualia.com/
  20267. *
  20268. * - shows frustum, line of sight and up of the camera
  20269. * - suitable for fast updates
  20270. * - based on frustum visualization in lightgl.js shadowmap example
  20271. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20272. */
  20273. THREE.CameraHelper = function ( camera ) {
  20274. var geometry = new THREE.Geometry();
  20275. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20276. var pointMap = {};
  20277. // colors
  20278. var hexFrustum = 0xffaa00;
  20279. var hexCone = 0xff0000;
  20280. var hexUp = 0x00aaff;
  20281. var hexTarget = 0xffffff;
  20282. var hexCross = 0x333333;
  20283. // near
  20284. addLine( "n1", "n2", hexFrustum );
  20285. addLine( "n2", "n4", hexFrustum );
  20286. addLine( "n4", "n3", hexFrustum );
  20287. addLine( "n3", "n1", hexFrustum );
  20288. // far
  20289. addLine( "f1", "f2", hexFrustum );
  20290. addLine( "f2", "f4", hexFrustum );
  20291. addLine( "f4", "f3", hexFrustum );
  20292. addLine( "f3", "f1", hexFrustum );
  20293. // sides
  20294. addLine( "n1", "f1", hexFrustum );
  20295. addLine( "n2", "f2", hexFrustum );
  20296. addLine( "n3", "f3", hexFrustum );
  20297. addLine( "n4", "f4", hexFrustum );
  20298. // cone
  20299. addLine( "p", "n1", hexCone );
  20300. addLine( "p", "n2", hexCone );
  20301. addLine( "p", "n3", hexCone );
  20302. addLine( "p", "n4", hexCone );
  20303. // up
  20304. addLine( "u1", "u2", hexUp );
  20305. addLine( "u2", "u3", hexUp );
  20306. addLine( "u3", "u1", hexUp );
  20307. // target
  20308. addLine( "c", "t", hexTarget );
  20309. addLine( "p", "c", hexCross );
  20310. // cross
  20311. addLine( "cn1", "cn2", hexCross );
  20312. addLine( "cn3", "cn4", hexCross );
  20313. addLine( "cf1", "cf2", hexCross );
  20314. addLine( "cf3", "cf4", hexCross );
  20315. function addLine( a, b, hex ) {
  20316. addPoint( a, hex );
  20317. addPoint( b, hex );
  20318. }
  20319. function addPoint( id, hex ) {
  20320. geometry.vertices.push( new THREE.Vector3() );
  20321. geometry.colors.push( new THREE.Color( hex ) );
  20322. if ( pointMap[ id ] === undefined ) {
  20323. pointMap[ id ] = [];
  20324. }
  20325. pointMap[ id ].push( geometry.vertices.length - 1 );
  20326. }
  20327. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20328. this.camera = camera;
  20329. this.matrixWorld = camera.matrixWorld;
  20330. this.matrixAutoUpdate = false;
  20331. this.pointMap = pointMap;
  20332. this.update();
  20333. };
  20334. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20335. THREE.CameraHelper.prototype.update = function () {
  20336. var vector = new THREE.Vector3();
  20337. var camera = new THREE.Camera();
  20338. var projector = new THREE.Projector();
  20339. return function () {
  20340. var scope = this;
  20341. var w = 1, h = 1;
  20342. // we need just camera projection matrix
  20343. // world matrix must be identity
  20344. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20345. // center / target
  20346. setPoint( "c", 0, 0, -1 );
  20347. setPoint( "t", 0, 0, 1 );
  20348. // near
  20349. setPoint( "n1", -w, -h, -1 );
  20350. setPoint( "n2", w, -h, -1 );
  20351. setPoint( "n3", -w, h, -1 );
  20352. setPoint( "n4", w, h, -1 );
  20353. // far
  20354. setPoint( "f1", -w, -h, 1 );
  20355. setPoint( "f2", w, -h, 1 );
  20356. setPoint( "f3", -w, h, 1 );
  20357. setPoint( "f4", w, h, 1 );
  20358. // up
  20359. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20360. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20361. setPoint( "u3", 0, h * 2, -1 );
  20362. // cross
  20363. setPoint( "cf1", -w, 0, 1 );
  20364. setPoint( "cf2", w, 0, 1 );
  20365. setPoint( "cf3", 0, -h, 1 );
  20366. setPoint( "cf4", 0, h, 1 );
  20367. setPoint( "cn1", -w, 0, -1 );
  20368. setPoint( "cn2", w, 0, -1 );
  20369. setPoint( "cn3", 0, -h, -1 );
  20370. setPoint( "cn4", 0, h, -1 );
  20371. function setPoint( point, x, y, z ) {
  20372. vector.set( x, y, z );
  20373. projector.unprojectVector( vector, camera );
  20374. var points = scope.pointMap[ point ];
  20375. if ( points !== undefined ) {
  20376. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20377. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20378. }
  20379. }
  20380. }
  20381. this.geometry.verticesNeedUpdate = true;
  20382. };
  20383. }();
  20384. /**
  20385. * @author alteredq / http://alteredqualia.com/
  20386. * @author mrdoob / http://mrdoob.com/
  20387. */
  20388. THREE.DirectionalLightHelper = function ( light, size ) {
  20389. THREE.Object3D.call( this );
  20390. this.light = light;
  20391. this.light.updateMatrixWorld();
  20392. this.matrixWorld = light.matrixWorld;
  20393. this.matrixAutoUpdate = false;
  20394. var geometry = new THREE.PlaneGeometry( size, size );
  20395. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20396. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20397. this.lightPlane = new THREE.Mesh( geometry, material );
  20398. this.add( this.lightPlane );
  20399. geometry = new THREE.Geometry();
  20400. geometry.vertices.push( new THREE.Vector3() );
  20401. geometry.vertices.push( new THREE.Vector3() );
  20402. geometry.computeLineDistances();
  20403. material = new THREE.LineBasicMaterial( { fog: false } );
  20404. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20405. this.targetLine = new THREE.Line( geometry, material );
  20406. this.add( this.targetLine );
  20407. this.update();
  20408. };
  20409. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20410. THREE.DirectionalLightHelper.prototype.dispose = function () {
  20411. this.lightPlane.geometry.dispose();
  20412. this.lightPlane.material.dispose();
  20413. this.targetLine.geometry.dispose();
  20414. this.targetLine.material.dispose();
  20415. };
  20416. THREE.DirectionalLightHelper.prototype.update = function () {
  20417. var vector = new THREE.Vector3();
  20418. return function () {
  20419. vector.getPositionFromMatrix( this.light.matrixWorld ).negate();
  20420. this.lightPlane.lookAt( vector );
  20421. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20422. this.targetLine.geometry.vertices[ 1 ].copy( vector );
  20423. this.targetLine.geometry.verticesNeedUpdate = true;
  20424. this.targetLine.material.color.copy( this.lightPlane.material.color );
  20425. }
  20426. }();
  20427. /**
  20428. * @author mrdoob / http://mrdoob.com/
  20429. * @author WestLangley / http://github.com/WestLangley
  20430. */
  20431. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20432. this.object = object;
  20433. this.size = size || 1;
  20434. var color = hex || 0xffff00;
  20435. var width = linewidth || 1;
  20436. var geometry = new THREE.Geometry();
  20437. var faces = this.object.geometry.faces;
  20438. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20439. geometry.vertices.push( new THREE.Vector3() );
  20440. geometry.vertices.push( new THREE.Vector3() );
  20441. }
  20442. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20443. this.matrixAutoUpdate = false;
  20444. this.normalMatrix = new THREE.Matrix3();
  20445. this.update();
  20446. };
  20447. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20448. THREE.FaceNormalsHelper.prototype.update = ( function ( object ) {
  20449. var v1 = new THREE.Vector3();
  20450. return function ( object ) {
  20451. this.object.updateMatrixWorld( true );
  20452. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20453. var vertices = this.geometry.vertices;
  20454. var faces = this.object.geometry.faces;
  20455. var worldMatrix = this.object.matrixWorld;
  20456. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20457. var face = faces[ i ];
  20458. v1.copy( face.normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20459. var idx = 2 * i;
  20460. vertices[ idx ].copy( face.centroid ).applyMatrix4( worldMatrix );
  20461. vertices[ idx + 1 ].addVectors( vertices[ idx ], v1 );
  20462. }
  20463. this.geometry.verticesNeedUpdate = true;
  20464. return this;
  20465. }
  20466. }());
  20467. /**
  20468. * @author mrdoob / http://mrdoob.com/
  20469. */
  20470. THREE.GridHelper = function ( size, step ) {
  20471. var geometry = new THREE.Geometry();
  20472. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20473. this.color1 = new THREE.Color( 0x444444 );
  20474. this.color2 = new THREE.Color( 0x888888 );
  20475. for ( var i = - size; i <= size; i += step ) {
  20476. geometry.vertices.push(
  20477. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  20478. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  20479. );
  20480. var color = i === 0 ? this.color1 : this.color2;
  20481. geometry.colors.push( color, color, color, color );
  20482. }
  20483. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20484. };
  20485. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  20486. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  20487. this.color1.set( colorCenterLine );
  20488. this.color2.set( colorGrid );
  20489. this.geometry.colorsNeedUpdate = true;
  20490. }
  20491. /**
  20492. * @author alteredq / http://alteredqualia.com/
  20493. * @author mrdoob / http://mrdoob.com/
  20494. */
  20495. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20496. THREE.Object3D.call( this );
  20497. this.light = light;
  20498. this.light.updateMatrixWorld();
  20499. this.matrixWorld = light.matrixWorld;
  20500. this.matrixAutoUpdate = false;
  20501. this.colors = [ new THREE.Color(), new THREE.Color() ];
  20502. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20503. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20504. for ( var i = 0, il = 8; i < il; i ++ ) {
  20505. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  20506. }
  20507. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  20508. this.lightSphere = new THREE.Mesh( geometry, material );
  20509. this.add( this.lightSphere );
  20510. this.update();
  20511. };
  20512. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20513. THREE.HemisphereLightHelper.prototype.dispose = function () {
  20514. this.lightSphere.geometry.dispose();
  20515. this.lightSphere.material.dispose();
  20516. };
  20517. THREE.HemisphereLightHelper.prototype.update = function () {
  20518. var vector = new THREE.Vector3();
  20519. return function () {
  20520. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  20521. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  20522. this.lightSphere.lookAt( vector.getPositionFromMatrix( this.light.matrixWorld ).negate() );
  20523. this.lightSphere.geometry.colorsNeedUpdate = true;
  20524. }
  20525. }();
  20526. /**
  20527. * @author alteredq / http://alteredqualia.com/
  20528. * @author mrdoob / http://mrdoob.com/
  20529. */
  20530. THREE.PointLightHelper = function ( light, sphereSize ) {
  20531. this.light = light;
  20532. this.light.updateMatrixWorld();
  20533. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20534. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20535. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20536. THREE.Mesh.call( this, geometry, material );
  20537. this.matrixWorld = this.light.matrixWorld;
  20538. this.matrixAutoUpdate = false;
  20539. /*
  20540. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20541. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20542. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20543. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20544. var d = light.distance;
  20545. if ( d === 0.0 ) {
  20546. this.lightDistance.visible = false;
  20547. } else {
  20548. this.lightDistance.scale.set( d, d, d );
  20549. }
  20550. this.add( this.lightDistance );
  20551. */
  20552. };
  20553. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  20554. THREE.PointLightHelper.prototype.dispose = function () {
  20555. this.geometry.dispose();
  20556. this.material.dispose();
  20557. };
  20558. THREE.PointLightHelper.prototype.update = function () {
  20559. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20560. /*
  20561. var d = this.light.distance;
  20562. if ( d === 0.0 ) {
  20563. this.lightDistance.visible = false;
  20564. } else {
  20565. this.lightDistance.visible = true;
  20566. this.lightDistance.scale.set( d, d, d );
  20567. }
  20568. */
  20569. };
  20570. /**
  20571. * @author alteredq / http://alteredqualia.com/
  20572. * @author mrdoob / http://mrdoob.com/
  20573. * @author WestLangley / http://github.com/WestLangley
  20574. */
  20575. THREE.SpotLightHelper = function ( light ) {
  20576. THREE.Object3D.call( this );
  20577. this.light = light;
  20578. this.light.updateMatrixWorld();
  20579. this.matrixWorld = light.matrixWorld;
  20580. this.matrixAutoUpdate = false;
  20581. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  20582. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  20583. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20584. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20585. this.cone = new THREE.Mesh( geometry, material );
  20586. this.add( this.cone );
  20587. this.update();
  20588. };
  20589. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20590. THREE.SpotLightHelper.prototype.dispose = function () {
  20591. this.cone.geometry.dispose();
  20592. this.cone.material.dispose();
  20593. };
  20594. THREE.SpotLightHelper.prototype.update = function () {
  20595. var vector = new THREE.Vector3();
  20596. var vector2 = new THREE.Vector3();
  20597. return function () {
  20598. var coneLength = this.light.distance ? this.light.distance : 10000;
  20599. var coneWidth = coneLength * Math.tan( this.light.angle );
  20600. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20601. vector.getPositionFromMatrix( this.light.matrixWorld );
  20602. vector2.getPositionFromMatrix( this.light.target.matrixWorld );
  20603. this.cone.lookAt( vector2.sub( vector ) );
  20604. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20605. };
  20606. }();
  20607. /**
  20608. * @author mrdoob / http://mrdoob.com/
  20609. * @author WestLangley / http://github.com/WestLangley
  20610. */
  20611. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  20612. this.object = object;
  20613. this.size = size || 1;
  20614. var color = hex || 0xff0000;
  20615. var width = linewidth || 1;
  20616. var geometry = new THREE.Geometry();
  20617. var vertices = object.geometry.vertices;
  20618. var faces = object.geometry.faces;
  20619. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20620. var face = faces[ i ];
  20621. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20622. geometry.vertices.push( new THREE.Vector3() );
  20623. geometry.vertices.push( new THREE.Vector3() );
  20624. }
  20625. }
  20626. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20627. this.matrixAutoUpdate = false;
  20628. this.normalMatrix = new THREE.Matrix3();
  20629. this.update();
  20630. };
  20631. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20632. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  20633. var v1 = new THREE.Vector3();
  20634. return function( object ) {
  20635. var keys = [ 'a', 'b', 'c', 'd' ];
  20636. this.object.updateMatrixWorld( true );
  20637. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20638. var vertices = this.geometry.vertices;
  20639. var verts = this.object.geometry.vertices;
  20640. var faces = this.object.geometry.faces;
  20641. var worldMatrix = this.object.matrixWorld;
  20642. var idx = 0;
  20643. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20644. var face = faces[ i ];
  20645. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20646. var vertexId = face[ keys[ j ] ];
  20647. var vertex = verts[ vertexId ];
  20648. var normal = face.vertexNormals[ j ];
  20649. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20650. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20651. v1.add( vertices[ idx ] );
  20652. idx = idx + 1;
  20653. vertices[ idx ].copy( v1 );
  20654. idx = idx + 1;
  20655. }
  20656. }
  20657. this.geometry.verticesNeedUpdate = true;
  20658. return this;
  20659. }
  20660. }());
  20661. /**
  20662. * @author mrdoob / http://mrdoob.com/
  20663. * @author WestLangley / http://github.com/WestLangley
  20664. */
  20665. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  20666. this.object = object;
  20667. this.size = size || 1;
  20668. var color = hex || 0x0000ff;
  20669. var width = linewidth || 1;
  20670. var geometry = new THREE.Geometry();
  20671. var vertices = object.geometry.vertices;
  20672. var faces = object.geometry.faces;
  20673. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20674. var face = faces[ i ];
  20675. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20676. geometry.vertices.push( new THREE.Vector3() );
  20677. geometry.vertices.push( new THREE.Vector3() );
  20678. }
  20679. }
  20680. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20681. this.matrixAutoUpdate = false;
  20682. this.update();
  20683. };
  20684. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  20685. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  20686. var v1 = new THREE.Vector3();
  20687. return function( object ) {
  20688. var keys = [ 'a', 'b', 'c', 'd' ];
  20689. this.object.updateMatrixWorld( true );
  20690. var vertices = this.geometry.vertices;
  20691. var verts = this.object.geometry.vertices;
  20692. var faces = this.object.geometry.faces;
  20693. var worldMatrix = this.object.matrixWorld;
  20694. var idx = 0;
  20695. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20696. var face = faces[ i ];
  20697. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20698. var vertexId = face[ keys[ j ] ];
  20699. var vertex = verts[ vertexId ];
  20700. var tangent = face.vertexTangents[ j ];
  20701. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20702. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  20703. v1.add( vertices[ idx ] );
  20704. idx = idx + 1;
  20705. vertices[ idx ].copy( v1 );
  20706. idx = idx + 1;
  20707. }
  20708. }
  20709. this.geometry.verticesNeedUpdate = true;
  20710. return this;
  20711. }
  20712. }());
  20713. /**
  20714. * @author mrdoob / http://mrdoob.com/
  20715. */
  20716. THREE.WireframeHelper = function ( object ) {
  20717. var edge = [ 0, 0 ], hash = {};
  20718. var sortFunction = function ( a, b ) { return a - b };
  20719. var keys = [ 'a', 'b', 'c', 'd' ];
  20720. var geometry = new THREE.Geometry();
  20721. var vertices = object.geometry.vertices;
  20722. var faces = object.geometry.faces;
  20723. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20724. var face = faces[ i ];
  20725. for ( var j = 0; j < 3; j ++ ) {
  20726. edge[ 0 ] = face[ keys[ j ] ];
  20727. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20728. edge.sort( sortFunction );
  20729. var key = edge.toString();
  20730. if ( hash[ key ] === undefined ) {
  20731. geometry.vertices.push( vertices[ edge[ 0 ] ] );
  20732. geometry.vertices.push( vertices[ edge[ 1 ] ] );
  20733. hash[ key ] = true;
  20734. }
  20735. }
  20736. }
  20737. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffffff } ), THREE.LinePieces );
  20738. this.matrixAutoUpdate = false;
  20739. this.matrixWorld = object.matrixWorld;
  20740. };
  20741. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  20742. /**
  20743. * @author alteredq / http://alteredqualia.com/
  20744. */
  20745. THREE.ImmediateRenderObject = function () {
  20746. THREE.Object3D.call( this );
  20747. this.render = function ( renderCallback ) { };
  20748. };
  20749. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20750. /**
  20751. * @author mikael emtinger / http://gomo.se/
  20752. * @author alteredq / http://alteredqualia.com/
  20753. */
  20754. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20755. THREE.Object3D.call( this );
  20756. this.lensFlares = [];
  20757. this.positionScreen = new THREE.Vector3();
  20758. this.customUpdateCallback = undefined;
  20759. if( texture !== undefined ) {
  20760. this.add( texture, size, distance, blending, color );
  20761. }
  20762. };
  20763. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20764. /*
  20765. * Add: adds another flare
  20766. */
  20767. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20768. if( size === undefined ) size = -1;
  20769. if( distance === undefined ) distance = 0;
  20770. if( opacity === undefined ) opacity = 1;
  20771. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20772. if( blending === undefined ) blending = THREE.NormalBlending;
  20773. distance = Math.min( distance, Math.max( 0, distance ) );
  20774. this.lensFlares.push( { texture: texture, // THREE.Texture
  20775. size: size, // size in pixels (-1 = use texture.width)
  20776. distance: distance, // distance (0-1) from light source (0=at light source)
  20777. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20778. scale: 1, // scale
  20779. rotation: 1, // rotation
  20780. opacity: opacity, // opacity
  20781. color: color, // color
  20782. blending: blending } ); // blending
  20783. };
  20784. /*
  20785. * Update lens flares update positions on all flares based on the screen position
  20786. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20787. */
  20788. THREE.LensFlare.prototype.updateLensFlares = function () {
  20789. var f, fl = this.lensFlares.length;
  20790. var flare;
  20791. var vecX = -this.positionScreen.x * 2;
  20792. var vecY = -this.positionScreen.y * 2;
  20793. for( f = 0; f < fl; f ++ ) {
  20794. flare = this.lensFlares[ f ];
  20795. flare.x = this.positionScreen.x + vecX * flare.distance;
  20796. flare.y = this.positionScreen.y + vecY * flare.distance;
  20797. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20798. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20799. }
  20800. };
  20801. /**
  20802. * @author alteredq / http://alteredqualia.com/
  20803. */
  20804. THREE.MorphBlendMesh = function( geometry, material ) {
  20805. THREE.Mesh.call( this, geometry, material );
  20806. this.animationsMap = {};
  20807. this.animationsList = [];
  20808. // prepare default animation
  20809. // (all frames played together in 1 second)
  20810. var numFrames = this.geometry.morphTargets.length;
  20811. var name = "__default";
  20812. var startFrame = 0;
  20813. var endFrame = numFrames - 1;
  20814. var fps = numFrames / 1;
  20815. this.createAnimation( name, startFrame, endFrame, fps );
  20816. this.setAnimationWeight( name, 1 );
  20817. };
  20818. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20819. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20820. var animation = {
  20821. startFrame: start,
  20822. endFrame: end,
  20823. length: end - start + 1,
  20824. fps: fps,
  20825. duration: ( end - start ) / fps,
  20826. lastFrame: 0,
  20827. currentFrame: 0,
  20828. active: false,
  20829. time: 0,
  20830. direction: 1,
  20831. weight: 1,
  20832. directionBackwards: false,
  20833. mirroredLoop: false
  20834. };
  20835. this.animationsMap[ name ] = animation;
  20836. this.animationsList.push( animation );
  20837. };
  20838. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20839. var pattern = /([a-z]+)(\d+)/;
  20840. var firstAnimation, frameRanges = {};
  20841. var geometry = this.geometry;
  20842. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20843. var morph = geometry.morphTargets[ i ];
  20844. var chunks = morph.name.match( pattern );
  20845. if ( chunks && chunks.length > 1 ) {
  20846. var name = chunks[ 1 ];
  20847. var num = chunks[ 2 ];
  20848. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20849. var range = frameRanges[ name ];
  20850. if ( i < range.start ) range.start = i;
  20851. if ( i > range.end ) range.end = i;
  20852. if ( ! firstAnimation ) firstAnimation = name;
  20853. }
  20854. }
  20855. for ( var name in frameRanges ) {
  20856. var range = frameRanges[ name ];
  20857. this.createAnimation( name, range.start, range.end, fps );
  20858. }
  20859. this.firstAnimation = firstAnimation;
  20860. };
  20861. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20862. var animation = this.animationsMap[ name ];
  20863. if ( animation ) {
  20864. animation.direction = 1;
  20865. animation.directionBackwards = false;
  20866. }
  20867. };
  20868. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20869. var animation = this.animationsMap[ name ];
  20870. if ( animation ) {
  20871. animation.direction = -1;
  20872. animation.directionBackwards = true;
  20873. }
  20874. };
  20875. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20876. var animation = this.animationsMap[ name ];
  20877. if ( animation ) {
  20878. animation.fps = fps;
  20879. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20880. }
  20881. };
  20882. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20883. var animation = this.animationsMap[ name ];
  20884. if ( animation ) {
  20885. animation.duration = duration;
  20886. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20887. }
  20888. };
  20889. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20890. var animation = this.animationsMap[ name ];
  20891. if ( animation ) {
  20892. animation.weight = weight;
  20893. }
  20894. };
  20895. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20896. var animation = this.animationsMap[ name ];
  20897. if ( animation ) {
  20898. animation.time = time;
  20899. }
  20900. };
  20901. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20902. var time = 0;
  20903. var animation = this.animationsMap[ name ];
  20904. if ( animation ) {
  20905. time = animation.time;
  20906. }
  20907. return time;
  20908. };
  20909. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20910. var duration = -1;
  20911. var animation = this.animationsMap[ name ];
  20912. if ( animation ) {
  20913. duration = animation.duration;
  20914. }
  20915. return duration;
  20916. };
  20917. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20918. var animation = this.animationsMap[ name ];
  20919. if ( animation ) {
  20920. animation.time = 0;
  20921. animation.active = true;
  20922. } else {
  20923. console.warn( "animation[" + name + "] undefined" );
  20924. }
  20925. };
  20926. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20927. var animation = this.animationsMap[ name ];
  20928. if ( animation ) {
  20929. animation.active = false;
  20930. }
  20931. };
  20932. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20933. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20934. var animation = this.animationsList[ i ];
  20935. if ( ! animation.active ) continue;
  20936. var frameTime = animation.duration / animation.length;
  20937. animation.time += animation.direction * delta;
  20938. if ( animation.mirroredLoop ) {
  20939. if ( animation.time > animation.duration || animation.time < 0 ) {
  20940. animation.direction *= -1;
  20941. if ( animation.time > animation.duration ) {
  20942. animation.time = animation.duration;
  20943. animation.directionBackwards = true;
  20944. }
  20945. if ( animation.time < 0 ) {
  20946. animation.time = 0;
  20947. animation.directionBackwards = false;
  20948. }
  20949. }
  20950. } else {
  20951. animation.time = animation.time % animation.duration;
  20952. if ( animation.time < 0 ) animation.time += animation.duration;
  20953. }
  20954. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20955. var weight = animation.weight;
  20956. if ( keyframe !== animation.currentFrame ) {
  20957. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20958. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20959. this.morphTargetInfluences[ keyframe ] = 0;
  20960. animation.lastFrame = animation.currentFrame;
  20961. animation.currentFrame = keyframe;
  20962. }
  20963. var mix = ( animation.time % frameTime ) / frameTime;
  20964. if ( animation.directionBackwards ) mix = 1 - mix;
  20965. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20966. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20967. }
  20968. };
  20969. /**
  20970. * @author mikael emtinger / http://gomo.se/
  20971. * @author alteredq / http://alteredqualia.com/
  20972. */
  20973. THREE.LensFlarePlugin = function () {
  20974. var _gl, _renderer, _precision, _lensFlare = {};
  20975. this.init = function ( renderer ) {
  20976. _gl = renderer.context;
  20977. _renderer = renderer;
  20978. _precision = renderer.getPrecision();
  20979. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20980. _lensFlare.faces = new Uint16Array( 6 );
  20981. var i = 0;
  20982. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20983. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20984. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20985. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20986. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20987. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20988. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20989. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20990. i = 0;
  20991. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20992. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20993. // buffers
  20994. _lensFlare.vertexBuffer = _gl.createBuffer();
  20995. _lensFlare.elementBuffer = _gl.createBuffer();
  20996. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20997. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20998. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20999. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21000. // textures
  21001. _lensFlare.tempTexture = _gl.createTexture();
  21002. _lensFlare.occlusionTexture = _gl.createTexture();
  21003. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21004. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21005. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21006. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21007. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21008. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21009. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21010. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21011. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21012. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21013. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21014. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21015. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21016. _lensFlare.hasVertexTexture = false;
  21017. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21018. } else {
  21019. _lensFlare.hasVertexTexture = true;
  21020. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21021. }
  21022. _lensFlare.attributes = {};
  21023. _lensFlare.uniforms = {};
  21024. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21025. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21026. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21027. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21028. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21029. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21030. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21031. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21032. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21033. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21034. };
  21035. /*
  21036. * Render lens flares
  21037. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21038. * reads these back and calculates occlusion.
  21039. * Then _lensFlare.update_lensFlares() is called to re-position and
  21040. * update transparency of flares. Then they are rendered.
  21041. *
  21042. */
  21043. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21044. var flares = scene.__webglFlares,
  21045. nFlares = flares.length;
  21046. if ( ! nFlares ) return;
  21047. var tempPosition = new THREE.Vector3();
  21048. var invAspect = viewportHeight / viewportWidth,
  21049. halfViewportWidth = viewportWidth * 0.5,
  21050. halfViewportHeight = viewportHeight * 0.5;
  21051. var size = 16 / viewportHeight,
  21052. scale = new THREE.Vector2( size * invAspect, size );
  21053. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21054. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21055. var uniforms = _lensFlare.uniforms,
  21056. attributes = _lensFlare.attributes;
  21057. // set _lensFlare program and reset blending
  21058. _gl.useProgram( _lensFlare.program );
  21059. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21060. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21061. // loop through all lens flares to update their occlusion and positions
  21062. // setup gl and common used attribs/unforms
  21063. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21064. _gl.uniform1i( uniforms.map, 1 );
  21065. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21066. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21067. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21068. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21069. _gl.disable( _gl.CULL_FACE );
  21070. _gl.depthMask( false );
  21071. var i, j, jl, flare, sprite;
  21072. for ( i = 0; i < nFlares; i ++ ) {
  21073. size = 16 / viewportHeight;
  21074. scale.set( size * invAspect, size );
  21075. // calc object screen position
  21076. flare = flares[ i ];
  21077. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21078. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21079. tempPosition.applyProjection( camera.projectionMatrix );
  21080. // setup arrays for gl programs
  21081. screenPosition.copy( tempPosition )
  21082. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21083. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21084. // screen cull
  21085. if ( _lensFlare.hasVertexTexture || (
  21086. screenPositionPixels.x > 0 &&
  21087. screenPositionPixels.x < viewportWidth &&
  21088. screenPositionPixels.y > 0 &&
  21089. screenPositionPixels.y < viewportHeight ) ) {
  21090. // save current RGB to temp texture
  21091. _gl.activeTexture( _gl.TEXTURE1 );
  21092. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21093. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21094. // render pink quad
  21095. _gl.uniform1i( uniforms.renderType, 0 );
  21096. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21097. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21098. _gl.disable( _gl.BLEND );
  21099. _gl.enable( _gl.DEPTH_TEST );
  21100. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21101. // copy result to occlusionMap
  21102. _gl.activeTexture( _gl.TEXTURE0 );
  21103. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21104. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21105. // restore graphics
  21106. _gl.uniform1i( uniforms.renderType, 1 );
  21107. _gl.disable( _gl.DEPTH_TEST );
  21108. _gl.activeTexture( _gl.TEXTURE1 );
  21109. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21110. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21111. // update object positions
  21112. flare.positionScreen.copy( screenPosition )
  21113. if ( flare.customUpdateCallback ) {
  21114. flare.customUpdateCallback( flare );
  21115. } else {
  21116. flare.updateLensFlares();
  21117. }
  21118. // render flares
  21119. _gl.uniform1i( uniforms.renderType, 2 );
  21120. _gl.enable( _gl.BLEND );
  21121. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21122. sprite = flare.lensFlares[ j ];
  21123. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21124. screenPosition.x = sprite.x;
  21125. screenPosition.y = sprite.y;
  21126. screenPosition.z = sprite.z;
  21127. size = sprite.size * sprite.scale / viewportHeight;
  21128. scale.x = size * invAspect;
  21129. scale.y = size;
  21130. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21131. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21132. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21133. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21134. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21135. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21136. _renderer.setTexture( sprite.texture, 1 );
  21137. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21138. }
  21139. }
  21140. }
  21141. }
  21142. // restore gl
  21143. _gl.enable( _gl.CULL_FACE );
  21144. _gl.enable( _gl.DEPTH_TEST );
  21145. _gl.depthMask( true );
  21146. };
  21147. function createProgram ( shader, precision ) {
  21148. var program = _gl.createProgram();
  21149. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21150. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21151. var prefix = "precision " + precision + " float;\n";
  21152. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21153. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21154. _gl.compileShader( fragmentShader );
  21155. _gl.compileShader( vertexShader );
  21156. _gl.attachShader( program, fragmentShader );
  21157. _gl.attachShader( program, vertexShader );
  21158. _gl.linkProgram( program );
  21159. return program;
  21160. };
  21161. };
  21162. /**
  21163. * @author alteredq / http://alteredqualia.com/
  21164. */
  21165. THREE.ShadowMapPlugin = function () {
  21166. var _gl,
  21167. _renderer,
  21168. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21169. _frustum = new THREE.Frustum(),
  21170. _projScreenMatrix = new THREE.Matrix4(),
  21171. _min = new THREE.Vector3(),
  21172. _max = new THREE.Vector3(),
  21173. _matrixPosition = new THREE.Vector3();
  21174. this.init = function ( renderer ) {
  21175. _gl = renderer.context;
  21176. _renderer = renderer;
  21177. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21178. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21179. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21180. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21181. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21182. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21183. _depthMaterial._shadowPass = true;
  21184. _depthMaterialMorph._shadowPass = true;
  21185. _depthMaterialSkin._shadowPass = true;
  21186. _depthMaterialMorphSkin._shadowPass = true;
  21187. };
  21188. this.render = function ( scene, camera ) {
  21189. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21190. this.update( scene, camera );
  21191. };
  21192. this.update = function ( scene, camera ) {
  21193. var i, il, j, jl, n,
  21194. shadowMap, shadowMatrix, shadowCamera,
  21195. program, buffer, material,
  21196. webglObject, object, light,
  21197. renderList,
  21198. lights = [],
  21199. k = 0,
  21200. fog = null;
  21201. // set GL state for depth map
  21202. _gl.clearColor( 1, 1, 1, 1 );
  21203. _gl.disable( _gl.BLEND );
  21204. _gl.enable( _gl.CULL_FACE );
  21205. _gl.frontFace( _gl.CCW );
  21206. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21207. _gl.cullFace( _gl.FRONT );
  21208. } else {
  21209. _gl.cullFace( _gl.BACK );
  21210. }
  21211. _renderer.setDepthTest( true );
  21212. // preprocess lights
  21213. // - skip lights that are not casting shadows
  21214. // - create virtual lights for cascaded shadow maps
  21215. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21216. light = scene.__lights[ i ];
  21217. if ( ! light.castShadow ) continue;
  21218. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21219. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21220. var virtualLight;
  21221. if ( ! light.shadowCascadeArray[ n ] ) {
  21222. virtualLight = createVirtualLight( light, n );
  21223. virtualLight.originalCamera = camera;
  21224. var gyro = new THREE.Gyroscope();
  21225. gyro.position = light.shadowCascadeOffset;
  21226. gyro.add( virtualLight );
  21227. gyro.add( virtualLight.target );
  21228. camera.add( gyro );
  21229. light.shadowCascadeArray[ n ] = virtualLight;
  21230. console.log( "Created virtualLight", virtualLight );
  21231. } else {
  21232. virtualLight = light.shadowCascadeArray[ n ];
  21233. }
  21234. updateVirtualLight( light, n );
  21235. lights[ k ] = virtualLight;
  21236. k ++;
  21237. }
  21238. } else {
  21239. lights[ k ] = light;
  21240. k ++;
  21241. }
  21242. }
  21243. // render depth map
  21244. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21245. light = lights[ i ];
  21246. if ( ! light.shadowMap ) {
  21247. var shadowFilter = THREE.LinearFilter;
  21248. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21249. shadowFilter = THREE.NearestFilter;
  21250. }
  21251. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21252. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21253. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21254. light.shadowMatrix = new THREE.Matrix4();
  21255. }
  21256. if ( ! light.shadowCamera ) {
  21257. if ( light instanceof THREE.SpotLight ) {
  21258. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21259. } else if ( light instanceof THREE.DirectionalLight ) {
  21260. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21261. } else {
  21262. console.error( "Unsupported light type for shadow" );
  21263. continue;
  21264. }
  21265. scene.add( light.shadowCamera );
  21266. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21267. }
  21268. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21269. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21270. light.shadowCamera.add( light.cameraHelper );
  21271. }
  21272. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21273. updateShadowCamera( camera, light );
  21274. }
  21275. shadowMap = light.shadowMap;
  21276. shadowMatrix = light.shadowMatrix;
  21277. shadowCamera = light.shadowCamera;
  21278. shadowCamera.position.getPositionFromMatrix( light.matrixWorld );
  21279. _matrixPosition.getPositionFromMatrix( light.target.matrixWorld );
  21280. shadowCamera.lookAt( _matrixPosition );
  21281. shadowCamera.updateMatrixWorld();
  21282. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21283. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21284. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21285. // compute shadow matrix
  21286. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21287. 0.0, 0.5, 0.0, 0.5,
  21288. 0.0, 0.0, 0.5, 0.5,
  21289. 0.0, 0.0, 0.0, 1.0 );
  21290. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21291. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21292. // update camera matrices and frustum
  21293. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21294. _frustum.setFromMatrix( _projScreenMatrix );
  21295. // render shadow map
  21296. _renderer.setRenderTarget( shadowMap );
  21297. _renderer.clear();
  21298. // set object matrices & frustum culling
  21299. renderList = scene.__webglObjects;
  21300. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21301. webglObject = renderList[ j ];
  21302. object = webglObject.object;
  21303. webglObject.render = false;
  21304. if ( object.visible && object.castShadow ) {
  21305. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21306. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21307. webglObject.render = true;
  21308. }
  21309. }
  21310. }
  21311. // render regular objects
  21312. var objectMaterial, useMorphing, useSkinning;
  21313. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21314. webglObject = renderList[ j ];
  21315. if ( webglObject.render ) {
  21316. object = webglObject.object;
  21317. buffer = webglObject.buffer;
  21318. // culling is overriden globally for all objects
  21319. // while rendering depth map
  21320. // need to deal with MeshFaceMaterial somehow
  21321. // in that case just use the first of material.materials for now
  21322. // (proper solution would require to break objects by materials
  21323. // similarly to regular rendering and then set corresponding
  21324. // depth materials per each chunk instead of just once per object)
  21325. objectMaterial = getObjectMaterial( object );
  21326. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21327. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21328. if ( object.customDepthMaterial ) {
  21329. material = object.customDepthMaterial;
  21330. } else if ( useSkinning ) {
  21331. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21332. } else if ( useMorphing ) {
  21333. material = _depthMaterialMorph;
  21334. } else {
  21335. material = _depthMaterial;
  21336. }
  21337. if ( buffer instanceof THREE.BufferGeometry ) {
  21338. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21339. } else {
  21340. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21341. }
  21342. }
  21343. }
  21344. // set matrices and render immediate objects
  21345. renderList = scene.__webglObjectsImmediate;
  21346. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21347. webglObject = renderList[ j ];
  21348. object = webglObject.object;
  21349. if ( object.visible && object.castShadow ) {
  21350. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21351. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21352. }
  21353. }
  21354. }
  21355. // restore GL state
  21356. var clearColor = _renderer.getClearColor(),
  21357. clearAlpha = _renderer.getClearAlpha();
  21358. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21359. _gl.enable( _gl.BLEND );
  21360. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21361. _gl.cullFace( _gl.BACK );
  21362. }
  21363. };
  21364. function createVirtualLight( light, cascade ) {
  21365. var virtualLight = new THREE.DirectionalLight();
  21366. virtualLight.isVirtual = true;
  21367. virtualLight.onlyShadow = true;
  21368. virtualLight.castShadow = true;
  21369. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21370. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21371. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21372. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21373. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21374. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21375. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21376. virtualLight.shadowDarkness = light.shadowDarkness;
  21377. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21378. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21379. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21380. virtualLight.pointsWorld = [];
  21381. virtualLight.pointsFrustum = [];
  21382. var pointsWorld = virtualLight.pointsWorld,
  21383. pointsFrustum = virtualLight.pointsFrustum;
  21384. for ( var i = 0; i < 8; i ++ ) {
  21385. pointsWorld[ i ] = new THREE.Vector3();
  21386. pointsFrustum[ i ] = new THREE.Vector3();
  21387. }
  21388. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21389. var farZ = light.shadowCascadeFarZ[ cascade ];
  21390. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21391. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21392. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21393. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21394. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21395. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21396. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21397. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21398. return virtualLight;
  21399. }
  21400. // Synchronize virtual light with the original light
  21401. function updateVirtualLight( light, cascade ) {
  21402. var virtualLight = light.shadowCascadeArray[ cascade ];
  21403. virtualLight.position.copy( light.position );
  21404. virtualLight.target.position.copy( light.target.position );
  21405. virtualLight.lookAt( virtualLight.target );
  21406. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21407. virtualLight.shadowDarkness = light.shadowDarkness;
  21408. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21409. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21410. var farZ = light.shadowCascadeFarZ[ cascade ];
  21411. var pointsFrustum = virtualLight.pointsFrustum;
  21412. pointsFrustum[ 0 ].z = nearZ;
  21413. pointsFrustum[ 1 ].z = nearZ;
  21414. pointsFrustum[ 2 ].z = nearZ;
  21415. pointsFrustum[ 3 ].z = nearZ;
  21416. pointsFrustum[ 4 ].z = farZ;
  21417. pointsFrustum[ 5 ].z = farZ;
  21418. pointsFrustum[ 6 ].z = farZ;
  21419. pointsFrustum[ 7 ].z = farZ;
  21420. }
  21421. // Fit shadow camera's ortho frustum to camera frustum
  21422. function updateShadowCamera( camera, light ) {
  21423. var shadowCamera = light.shadowCamera,
  21424. pointsFrustum = light.pointsFrustum,
  21425. pointsWorld = light.pointsWorld;
  21426. _min.set( Infinity, Infinity, Infinity );
  21427. _max.set( -Infinity, -Infinity, -Infinity );
  21428. for ( var i = 0; i < 8; i ++ ) {
  21429. var p = pointsWorld[ i ];
  21430. p.copy( pointsFrustum[ i ] );
  21431. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21432. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21433. if ( p.x < _min.x ) _min.x = p.x;
  21434. if ( p.x > _max.x ) _max.x = p.x;
  21435. if ( p.y < _min.y ) _min.y = p.y;
  21436. if ( p.y > _max.y ) _max.y = p.y;
  21437. if ( p.z < _min.z ) _min.z = p.z;
  21438. if ( p.z > _max.z ) _max.z = p.z;
  21439. }
  21440. shadowCamera.left = _min.x;
  21441. shadowCamera.right = _max.x;
  21442. shadowCamera.top = _max.y;
  21443. shadowCamera.bottom = _min.y;
  21444. // can't really fit near/far
  21445. //shadowCamera.near = _min.z;
  21446. //shadowCamera.far = _max.z;
  21447. shadowCamera.updateProjectionMatrix();
  21448. }
  21449. // For the moment just ignore objects that have multiple materials with different animation methods
  21450. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21451. function getObjectMaterial( object ) {
  21452. return object.material instanceof THREE.MeshFaceMaterial
  21453. ? object.material.materials[ 0 ]
  21454. : object.material;
  21455. };
  21456. };
  21457. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21458. /**
  21459. * @author mikael emtinger / http://gomo.se/
  21460. * @author alteredq / http://alteredqualia.com/
  21461. */
  21462. THREE.SpritePlugin = function () {
  21463. var _gl, _renderer, _precision, _sprite = {};
  21464. this.init = function ( renderer ) {
  21465. _gl = renderer.context;
  21466. _renderer = renderer;
  21467. _precision = renderer.getPrecision();
  21468. _sprite.vertices = new Float32Array( 8 + 8 );
  21469. _sprite.faces = new Uint16Array( 6 );
  21470. var i = 0;
  21471. _sprite.vertices[ i++ ] = -0.5; _sprite.vertices[ i++ ] = -0.5; // vertex 0
  21472. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21473. _sprite.vertices[ i++ ] = 0.5; _sprite.vertices[ i++ ] = -0.5; // vertex 1
  21474. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21475. _sprite.vertices[ i++ ] = 0.5; _sprite.vertices[ i++ ] = 0.5; // vertex 2
  21476. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21477. _sprite.vertices[ i++ ] = -0.5; _sprite.vertices[ i++ ] = 0.5; // vertex 3
  21478. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21479. i = 0;
  21480. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21481. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21482. _sprite.vertexBuffer = _gl.createBuffer();
  21483. _sprite.elementBuffer = _gl.createBuffer();
  21484. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21485. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21486. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21487. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21488. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ], _precision );
  21489. _sprite.attributes = {};
  21490. _sprite.uniforms = {};
  21491. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21492. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21493. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21494. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21495. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21496. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21497. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21498. _sprite.uniforms.halfViewport = _gl.getUniformLocation( _sprite.program, "halfViewport" );
  21499. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21500. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21501. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21502. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21503. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  21504. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21505. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21506. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21507. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21508. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21509. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21510. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21511. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21512. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21513. };
  21514. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21515. var sprites = scene.__webglSprites,
  21516. nSprites = sprites.length;
  21517. if ( ! nSprites ) return;
  21518. var attributes = _sprite.attributes,
  21519. uniforms = _sprite.uniforms;
  21520. var halfViewportWidth = viewportWidth * 0.5,
  21521. halfViewportHeight = viewportHeight * 0.5;
  21522. // setup gl
  21523. _gl.useProgram( _sprite.program );
  21524. _gl.enableVertexAttribArray( attributes.position );
  21525. _gl.enableVertexAttribArray( attributes.uv );
  21526. _gl.disable( _gl.CULL_FACE );
  21527. _gl.enable( _gl.BLEND );
  21528. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21529. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21530. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21531. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21532. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21533. _gl.activeTexture( _gl.TEXTURE0 );
  21534. _gl.uniform1i( uniforms.map, 0 );
  21535. var oldFogType = 0;
  21536. var sceneFogType = 0;
  21537. var fog = scene.fog;
  21538. if ( fog ) {
  21539. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21540. if ( fog instanceof THREE.Fog ) {
  21541. _gl.uniform1f( uniforms.fogNear, fog.near );
  21542. _gl.uniform1f( uniforms.fogFar, fog.far );
  21543. _gl.uniform1i( uniforms.fogType, 1 );
  21544. oldFogType = 1;
  21545. sceneFogType = 1;
  21546. } else if ( fog instanceof THREE.FogExp2 ) {
  21547. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21548. _gl.uniform1i( uniforms.fogType, 2 );
  21549. oldFogType = 2;
  21550. sceneFogType = 2;
  21551. }
  21552. } else {
  21553. _gl.uniform1i( uniforms.fogType, 0 );
  21554. oldFogType = 0;
  21555. sceneFogType = 0;
  21556. }
  21557. // update positions and sort
  21558. var i, sprite, material, screenPosition, fogType, scale = [];
  21559. for( i = 0; i < nSprites; i ++ ) {
  21560. sprite = sprites[ i ];
  21561. material = sprite.material;
  21562. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21563. if ( ! material.useScreenCoordinates ) {
  21564. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21565. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21566. } else {
  21567. sprite.z = - sprite.position.z;
  21568. }
  21569. }
  21570. sprites.sort( painterSortStable );
  21571. // render all sprites
  21572. for( i = 0; i < nSprites; i ++ ) {
  21573. sprite = sprites[ i ];
  21574. material = sprite.material;
  21575. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21576. if ( material.map && material.map.image && material.map.image.width ) {
  21577. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21578. if ( material.useScreenCoordinates === true ) {
  21579. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21580. _gl.uniform3f(
  21581. uniforms.screenPosition,
  21582. ( ( sprite.position.x * _renderer.devicePixelRatio ) - halfViewportWidth ) / halfViewportWidth,
  21583. ( halfViewportHeight - ( sprite.position.y * _renderer.devicePixelRatio ) ) / halfViewportHeight,
  21584. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21585. );
  21586. scale[ 0 ] = _renderer.devicePixelRatio * sprite.scale.x;
  21587. scale[ 1 ] = _renderer.devicePixelRatio * sprite.scale.y;
  21588. } else {
  21589. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21590. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21591. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21592. scale[ 0 ] = sprite.scale.x;
  21593. scale[ 1 ] = sprite.scale.y;
  21594. }
  21595. if ( scene.fog && material.fog ) {
  21596. fogType = sceneFogType;
  21597. } else {
  21598. fogType = 0;
  21599. }
  21600. if ( oldFogType !== fogType ) {
  21601. _gl.uniform1i( uniforms.fogType, fogType );
  21602. oldFogType = fogType;
  21603. }
  21604. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21605. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21606. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21607. _gl.uniform1f( uniforms.opacity, material.opacity );
  21608. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21609. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21610. _gl.uniform2fv( uniforms.scale, scale );
  21611. _gl.uniform2f( uniforms.halfViewport, halfViewportWidth, halfViewportHeight );
  21612. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21613. _renderer.setDepthTest( material.depthTest );
  21614. _renderer.setDepthWrite( material.depthWrite );
  21615. _renderer.setTexture( material.map, 0 );
  21616. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21617. }
  21618. }
  21619. // restore gl
  21620. _gl.enable( _gl.CULL_FACE );
  21621. };
  21622. function createProgram ( shader, precision ) {
  21623. var program = _gl.createProgram();
  21624. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21625. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21626. var prefix = "precision " + precision + " float;\n";
  21627. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21628. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21629. _gl.compileShader( fragmentShader );
  21630. _gl.compileShader( vertexShader );
  21631. _gl.attachShader( program, fragmentShader );
  21632. _gl.attachShader( program, vertexShader );
  21633. _gl.linkProgram( program );
  21634. return program;
  21635. };
  21636. function painterSortStable ( a, b ) {
  21637. if ( a.z !== b.z ) {
  21638. return b.z - a.z;
  21639. } else {
  21640. return b.id - a.id;
  21641. }
  21642. };
  21643. };
  21644. /**
  21645. * @author alteredq / http://alteredqualia.com/
  21646. */
  21647. THREE.DepthPassPlugin = function () {
  21648. this.enabled = false;
  21649. this.renderTarget = null;
  21650. var _gl,
  21651. _renderer,
  21652. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21653. _frustum = new THREE.Frustum(),
  21654. _projScreenMatrix = new THREE.Matrix4();
  21655. this.init = function ( renderer ) {
  21656. _gl = renderer.context;
  21657. _renderer = renderer;
  21658. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21659. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21660. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21661. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21662. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21663. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21664. _depthMaterial._shadowPass = true;
  21665. _depthMaterialMorph._shadowPass = true;
  21666. _depthMaterialSkin._shadowPass = true;
  21667. _depthMaterialMorphSkin._shadowPass = true;
  21668. };
  21669. this.render = function ( scene, camera ) {
  21670. if ( ! this.enabled ) return;
  21671. this.update( scene, camera );
  21672. };
  21673. this.update = function ( scene, camera ) {
  21674. var i, il, j, jl, n,
  21675. program, buffer, material,
  21676. webglObject, object, light,
  21677. renderList,
  21678. fog = null;
  21679. // set GL state for depth map
  21680. _gl.clearColor( 1, 1, 1, 1 );
  21681. _gl.disable( _gl.BLEND );
  21682. _renderer.setDepthTest( true );
  21683. // update scene
  21684. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21685. // update camera matrices and frustum
  21686. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21687. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21688. _frustum.setFromMatrix( _projScreenMatrix );
  21689. // render depth map
  21690. _renderer.setRenderTarget( this.renderTarget );
  21691. _renderer.clear();
  21692. // set object matrices & frustum culling
  21693. renderList = scene.__webglObjects;
  21694. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21695. webglObject = renderList[ j ];
  21696. object = webglObject.object;
  21697. webglObject.render = false;
  21698. if ( object.visible ) {
  21699. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21700. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21701. webglObject.render = true;
  21702. }
  21703. }
  21704. }
  21705. // render regular objects
  21706. var objectMaterial, useMorphing, useSkinning;
  21707. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21708. webglObject = renderList[ j ];
  21709. if ( webglObject.render ) {
  21710. object = webglObject.object;
  21711. buffer = webglObject.buffer;
  21712. // todo: create proper depth material for particles
  21713. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21714. objectMaterial = getObjectMaterial( object );
  21715. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21716. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21717. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21718. if ( object.customDepthMaterial ) {
  21719. material = object.customDepthMaterial;
  21720. } else if ( useSkinning ) {
  21721. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21722. } else if ( useMorphing ) {
  21723. material = _depthMaterialMorph;
  21724. } else {
  21725. material = _depthMaterial;
  21726. }
  21727. if ( buffer instanceof THREE.BufferGeometry ) {
  21728. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21729. } else {
  21730. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21731. }
  21732. }
  21733. }
  21734. // set matrices and render immediate objects
  21735. renderList = scene.__webglObjectsImmediate;
  21736. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21737. webglObject = renderList[ j ];
  21738. object = webglObject.object;
  21739. if ( object.visible ) {
  21740. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21741. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21742. }
  21743. }
  21744. // restore GL state
  21745. var clearColor = _renderer.getClearColor(),
  21746. clearAlpha = _renderer.getClearAlpha();
  21747. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21748. _gl.enable( _gl.BLEND );
  21749. };
  21750. // For the moment just ignore objects that have multiple materials with different animation methods
  21751. // Only the first material will be taken into account for deciding which depth material to use
  21752. function getObjectMaterial( object ) {
  21753. return object.material instanceof THREE.MeshFaceMaterial
  21754. ? object.material.materials[ 0 ]
  21755. : object.material;
  21756. };
  21757. };
  21758. /**
  21759. * @author mikael emtinger / http://gomo.se/
  21760. */
  21761. THREE.ShaderFlares = {
  21762. 'lensFlareVertexTexture': {
  21763. vertexShader: [
  21764. "uniform lowp int renderType;",
  21765. "uniform vec3 screenPosition;",
  21766. "uniform vec2 scale;",
  21767. "uniform float rotation;",
  21768. "uniform sampler2D occlusionMap;",
  21769. "attribute vec2 position;",
  21770. "attribute vec2 uv;",
  21771. "varying vec2 vUV;",
  21772. "varying float vVisibility;",
  21773. "void main() {",
  21774. "vUV = uv;",
  21775. "vec2 pos = position;",
  21776. "if( renderType == 2 ) {",
  21777. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  21778. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  21779. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  21780. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  21781. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  21782. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  21783. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  21784. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  21785. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21786. "vVisibility = visibility.r / 9.0;",
  21787. "vVisibility *= 1.0 - visibility.g / 9.0;",
  21788. "vVisibility *= visibility.b / 9.0;",
  21789. "vVisibility *= 1.0 - visibility.a / 9.0;",
  21790. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21791. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21792. "}",
  21793. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21794. "}"
  21795. ].join( "\n" ),
  21796. fragmentShader: [
  21797. "uniform lowp int renderType;",
  21798. "uniform sampler2D map;",
  21799. "uniform float opacity;",
  21800. "uniform vec3 color;",
  21801. "varying vec2 vUV;",
  21802. "varying float vVisibility;",
  21803. "void main() {",
  21804. // pink square
  21805. "if( renderType == 0 ) {",
  21806. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21807. // restore
  21808. "} else if( renderType == 1 ) {",
  21809. "gl_FragColor = texture2D( map, vUV );",
  21810. // flare
  21811. "} else {",
  21812. "vec4 texture = texture2D( map, vUV );",
  21813. "texture.a *= opacity * vVisibility;",
  21814. "gl_FragColor = texture;",
  21815. "gl_FragColor.rgb *= color;",
  21816. "}",
  21817. "}"
  21818. ].join( "\n" )
  21819. },
  21820. 'lensFlare': {
  21821. vertexShader: [
  21822. "uniform lowp int renderType;",
  21823. "uniform vec3 screenPosition;",
  21824. "uniform vec2 scale;",
  21825. "uniform float rotation;",
  21826. "attribute vec2 position;",
  21827. "attribute vec2 uv;",
  21828. "varying vec2 vUV;",
  21829. "void main() {",
  21830. "vUV = uv;",
  21831. "vec2 pos = position;",
  21832. "if( renderType == 2 ) {",
  21833. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21834. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21835. "}",
  21836. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21837. "}"
  21838. ].join( "\n" ),
  21839. fragmentShader: [
  21840. "precision mediump float;",
  21841. "uniform lowp int renderType;",
  21842. "uniform sampler2D map;",
  21843. "uniform sampler2D occlusionMap;",
  21844. "uniform float opacity;",
  21845. "uniform vec3 color;",
  21846. "varying vec2 vUV;",
  21847. "void main() {",
  21848. // pink square
  21849. "if( renderType == 0 ) {",
  21850. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21851. // restore
  21852. "} else if( renderType == 1 ) {",
  21853. "gl_FragColor = texture2D( map, vUV );",
  21854. // flare
  21855. "} else {",
  21856. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  21857. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  21858. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  21859. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21860. "visibility = ( 1.0 - visibility / 4.0 );",
  21861. "vec4 texture = texture2D( map, vUV );",
  21862. "texture.a *= opacity * visibility;",
  21863. "gl_FragColor = texture;",
  21864. "gl_FragColor.rgb *= color;",
  21865. "}",
  21866. "}"
  21867. ].join( "\n" )
  21868. }
  21869. };
  21870. /**
  21871. * @author mikael emtinger / http://gomo.se/
  21872. * @author alteredq / http://alteredqualia.com/
  21873. *
  21874. */
  21875. THREE.ShaderSprite = {
  21876. 'sprite': {
  21877. vertexShader: [
  21878. "uniform int useScreenCoordinates;",
  21879. "uniform int sizeAttenuation;",
  21880. "uniform vec3 screenPosition;",
  21881. "uniform mat4 modelViewMatrix;",
  21882. "uniform mat4 projectionMatrix;",
  21883. "uniform float rotation;",
  21884. "uniform vec2 scale;",
  21885. "uniform vec2 alignment;",
  21886. "uniform vec2 uvOffset;",
  21887. "uniform vec2 uvScale;",
  21888. "uniform vec2 halfViewport;",
  21889. "attribute vec2 position;",
  21890. "attribute vec2 uv;",
  21891. "varying vec2 vUV;",
  21892. "void main() {",
  21893. "vUV = uvOffset + uv * uvScale;",
  21894. "vec2 alignedPosition = ( position + alignment ) * scale;",
  21895. "vec2 rotatedPosition;",
  21896. "rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;",
  21897. "rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;",
  21898. "vec4 finalPosition;",
  21899. "if( useScreenCoordinates != 0 ) {",
  21900. "finalPosition = vec4( screenPosition.xy + ( rotatedPosition / halfViewport ), screenPosition.z, 1.0 );",
  21901. "} else {",
  21902. "finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21903. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  21904. "finalPosition = projectionMatrix * finalPosition;",
  21905. "}",
  21906. "gl_Position = finalPosition;",
  21907. "}"
  21908. ].join( "\n" ),
  21909. fragmentShader: [
  21910. "uniform vec3 color;",
  21911. "uniform sampler2D map;",
  21912. "uniform float opacity;",
  21913. "uniform int fogType;",
  21914. "uniform vec3 fogColor;",
  21915. "uniform float fogDensity;",
  21916. "uniform float fogNear;",
  21917. "uniform float fogFar;",
  21918. "uniform float alphaTest;",
  21919. "varying vec2 vUV;",
  21920. "void main() {",
  21921. "vec4 texture = texture2D( map, vUV );",
  21922. "if ( texture.a < alphaTest ) discard;",
  21923. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21924. "if ( fogType > 0 ) {",
  21925. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  21926. "float fogFactor = 0.0;",
  21927. "if ( fogType == 1 ) {",
  21928. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  21929. "} else {",
  21930. "const float LOG2 = 1.442695;",
  21931. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  21932. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  21933. "}",
  21934. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  21935. "}",
  21936. "}"
  21937. ].join( "\n" )
  21938. }
  21939. };