three.js 804 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. */
  5. var THREE = THREE || { REVISION: '57dev' };
  6. self.console = self.console || {
  7. info: function () {},
  8. log: function () {},
  9. debug: function () {},
  10. warn: function () {},
  11. error: function () {}
  12. };
  13. self.Int32Array = self.Int32Array || Array;
  14. self.Float32Array = self.Float32Array || Array;
  15. String.prototype.trim = String.prototype.trim || function () {
  16. return this.replace( /^\s+|\s+$/g, '' );
  17. };
  18. // based on https://github.com/documentcloud/underscore/blob/bf657be243a075b5e72acc8a83e6f12a564d8f55/underscore.js#L767
  19. THREE.extend = function ( obj, source ) {
  20. // ECMAScript5 compatibility based on: http://www.nczonline.net/blog/2012/12/11/are-your-mixins-ecmascript-5-compatible/
  21. if ( Object.keys ) {
  22. var keys = Object.keys( source );
  23. for (var i = 0, il = keys.length; i < il; i++) {
  24. var prop = keys[i];
  25. Object.defineProperty( obj, prop, Object.getOwnPropertyDescriptor( source, prop ) );
  26. }
  27. } else {
  28. var safeHasOwnProperty = {}.hasOwnProperty;
  29. for ( var prop in source ) {
  30. if ( safeHasOwnProperty.call( source, prop ) ) {
  31. obj[prop] = source[prop];
  32. }
  33. }
  34. }
  35. return obj;
  36. };
  37. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  38. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  39. // requestAnimationFrame polyfill by Erik Möller
  40. // fixes from Paul Irish and Tino Zijdel
  41. ( function () {
  42. var lastTime = 0;
  43. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  44. for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) {
  45. window.requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ];
  46. window.cancelAnimationFrame = window[ vendors[ x ] + 'CancelAnimationFrame' ] || window[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  47. }
  48. if ( window.requestAnimationFrame === undefined ) {
  49. window.requestAnimationFrame = function ( callback ) {
  50. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  51. var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  52. lastTime = currTime + timeToCall;
  53. return id;
  54. };
  55. }
  56. window.cancelAnimationFrame = window.cancelAnimationFrame || function ( id ) { window.clearTimeout( id ) };
  57. }() );
  58. // GL STATE CONSTANTS
  59. THREE.CullFaceNone = 0;
  60. THREE.CullFaceBack = 1;
  61. THREE.CullFaceFront = 2;
  62. THREE.CullFaceFrontBack = 3;
  63. THREE.FrontFaceDirectionCW = 0;
  64. THREE.FrontFaceDirectionCCW = 1;
  65. // SHADOWING TYPES
  66. THREE.BasicShadowMap = 0;
  67. THREE.PCFShadowMap = 1;
  68. THREE.PCFSoftShadowMap = 2;
  69. // MATERIAL CONSTANTS
  70. // side
  71. THREE.FrontSide = 0;
  72. THREE.BackSide = 1;
  73. THREE.DoubleSide = 2;
  74. // shading
  75. THREE.NoShading = 0;
  76. THREE.FlatShading = 1;
  77. THREE.SmoothShading = 2;
  78. // colors
  79. THREE.NoColors = 0;
  80. THREE.FaceColors = 1;
  81. THREE.VertexColors = 2;
  82. // blending modes
  83. THREE.NoBlending = 0;
  84. THREE.NormalBlending = 1;
  85. THREE.AdditiveBlending = 2;
  86. THREE.SubtractiveBlending = 3;
  87. THREE.MultiplyBlending = 4;
  88. THREE.CustomBlending = 5;
  89. // custom blending equations
  90. // (numbers start from 100 not to clash with other
  91. // mappings to OpenGL constants defined in Texture.js)
  92. THREE.AddEquation = 100;
  93. THREE.SubtractEquation = 101;
  94. THREE.ReverseSubtractEquation = 102;
  95. // custom blending destination factors
  96. THREE.ZeroFactor = 200;
  97. THREE.OneFactor = 201;
  98. THREE.SrcColorFactor = 202;
  99. THREE.OneMinusSrcColorFactor = 203;
  100. THREE.SrcAlphaFactor = 204;
  101. THREE.OneMinusSrcAlphaFactor = 205;
  102. THREE.DstAlphaFactor = 206;
  103. THREE.OneMinusDstAlphaFactor = 207;
  104. // custom blending source factors
  105. //THREE.ZeroFactor = 200;
  106. //THREE.OneFactor = 201;
  107. //THREE.SrcAlphaFactor = 204;
  108. //THREE.OneMinusSrcAlphaFactor = 205;
  109. //THREE.DstAlphaFactor = 206;
  110. //THREE.OneMinusDstAlphaFactor = 207;
  111. THREE.DstColorFactor = 208;
  112. THREE.OneMinusDstColorFactor = 209;
  113. THREE.SrcAlphaSaturateFactor = 210;
  114. // TEXTURE CONSTANTS
  115. THREE.MultiplyOperation = 0;
  116. THREE.MixOperation = 1;
  117. THREE.AddOperation = 2;
  118. // Mapping modes
  119. THREE.UVMapping = function () {};
  120. THREE.CubeReflectionMapping = function () {};
  121. THREE.CubeRefractionMapping = function () {};
  122. THREE.SphericalReflectionMapping = function () {};
  123. THREE.SphericalRefractionMapping = function () {};
  124. // Wrapping modes
  125. THREE.RepeatWrapping = 1000;
  126. THREE.ClampToEdgeWrapping = 1001;
  127. THREE.MirroredRepeatWrapping = 1002;
  128. // Filters
  129. THREE.NearestFilter = 1003;
  130. THREE.NearestMipMapNearestFilter = 1004;
  131. THREE.NearestMipMapLinearFilter = 1005;
  132. THREE.LinearFilter = 1006;
  133. THREE.LinearMipMapNearestFilter = 1007;
  134. THREE.LinearMipMapLinearFilter = 1008;
  135. // Data types
  136. THREE.UnsignedByteType = 1009;
  137. THREE.ByteType = 1010;
  138. THREE.ShortType = 1011;
  139. THREE.UnsignedShortType = 1012;
  140. THREE.IntType = 1013;
  141. THREE.UnsignedIntType = 1014;
  142. THREE.FloatType = 1015;
  143. // Pixel types
  144. //THREE.UnsignedByteType = 1009;
  145. THREE.UnsignedShort4444Type = 1016;
  146. THREE.UnsignedShort5551Type = 1017;
  147. THREE.UnsignedShort565Type = 1018;
  148. // Pixel formats
  149. THREE.AlphaFormat = 1019;
  150. THREE.RGBFormat = 1020;
  151. THREE.RGBAFormat = 1021;
  152. THREE.LuminanceFormat = 1022;
  153. THREE.LuminanceAlphaFormat = 1023;
  154. // Compressed texture formats
  155. THREE.RGB_S3TC_DXT1_Format = 2001;
  156. THREE.RGBA_S3TC_DXT1_Format = 2002;
  157. THREE.RGBA_S3TC_DXT3_Format = 2003;
  158. THREE.RGBA_S3TC_DXT5_Format = 2004;
  159. /*
  160. // Potential future PVRTC compressed texture formats
  161. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  162. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  163. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  164. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  165. */
  166. /**
  167. * @author mrdoob / http://mrdoob.com/
  168. */
  169. THREE.Color = function ( value ) {
  170. if ( value !== undefined ) this.set( value );
  171. return this;
  172. };
  173. THREE.extend( THREE.Color.prototype, {
  174. r: 1, g: 1, b: 1,
  175. set: function ( value ) {
  176. switch ( typeof value ) {
  177. case "number":
  178. this.setHex( value );
  179. break;
  180. case "string":
  181. this.setStyle( value );
  182. break;
  183. }
  184. },
  185. setHex: function ( hex ) {
  186. hex = Math.floor( hex );
  187. this.r = ( hex >> 16 & 255 ) / 255;
  188. this.g = ( hex >> 8 & 255 ) / 255;
  189. this.b = ( hex & 255 ) / 255;
  190. return this;
  191. },
  192. setRGB: function ( r, g, b ) {
  193. this.r = r;
  194. this.g = g;
  195. this.b = b;
  196. return this;
  197. },
  198. setHSV: function ( h, s, v ) {
  199. console.log( 'DEPRECATED: Color\'s .setHSV() will be removed. Use .setHSL( h, s, l ) instead.' );
  200. return this.setHSL(h,s*v/((h=(2-s)*v)<1?h:2-h),h/2); // https://gist.github.com/xpansive/1337890
  201. },
  202. setHSL: function ( h, s, l ) {
  203. // h,s,l ranges are in 0.0 - 1.0
  204. if ( s === 0 ) {
  205. this.r = this.g = this.b = l;
  206. } else {
  207. var hue2rgb = function ( p, q, t ) {
  208. if ( t < 0 ) t += 1;
  209. if ( t > 1 ) t -= 1;
  210. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  211. if ( t < 1 / 2 ) return q;
  212. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  213. return p;
  214. };
  215. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  216. var q = ( 2 * l ) - p;
  217. this.r = hue2rgb( q, p, h + 1 / 3 );
  218. this.g = hue2rgb( q, p, h );
  219. this.b = hue2rgb( q, p, h - 1 / 3 );
  220. }
  221. return this;
  222. },
  223. setStyle: function ( style ) {
  224. // rgb(255,0,0)
  225. if ( /^rgb\((\d+),(\d+),(\d+)\)$/i.test( style ) ) {
  226. var color = /^rgb\((\d+),(\d+),(\d+)\)$/i.exec( style );
  227. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  228. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  229. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  230. return this;
  231. }
  232. // rgb(100%,0%,0%)
  233. if ( /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test( style ) ) {
  234. var color = /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec( style );
  235. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  236. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  237. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  238. return this;
  239. }
  240. // #ff0000
  241. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  242. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  243. this.setHex( parseInt( color[ 1 ], 16 ) );
  244. return this;
  245. }
  246. // #f00
  247. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  248. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  249. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  250. return this;
  251. }
  252. // red
  253. if ( /^(\w+)$/i.test( style ) ) {
  254. this.setHex( THREE.ColorKeywords[ style ] );
  255. return this;
  256. }
  257. },
  258. copy: function ( color ) {
  259. this.r = color.r;
  260. this.g = color.g;
  261. this.b = color.b;
  262. return this;
  263. },
  264. copyGammaToLinear: function ( color ) {
  265. this.r = color.r * color.r;
  266. this.g = color.g * color.g;
  267. this.b = color.b * color.b;
  268. return this;
  269. },
  270. copyLinearToGamma: function ( color ) {
  271. this.r = Math.sqrt( color.r );
  272. this.g = Math.sqrt( color.g );
  273. this.b = Math.sqrt( color.b );
  274. return this;
  275. },
  276. convertGammaToLinear: function () {
  277. var r = this.r, g = this.g, b = this.b;
  278. this.r = r * r;
  279. this.g = g * g;
  280. this.b = b * b;
  281. return this;
  282. },
  283. convertLinearToGamma: function () {
  284. this.r = Math.sqrt( this.r );
  285. this.g = Math.sqrt( this.g );
  286. this.b = Math.sqrt( this.b );
  287. return this;
  288. },
  289. getHex: function () {
  290. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  291. },
  292. getHexString: function () {
  293. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  294. },
  295. getHSL: function () {
  296. var hsl = { h: 0, s: 0, l: 0 };
  297. return function () {
  298. // h,s,l ranges are in 0.0 - 1.0
  299. var r = this.r, g = this.g, b = this.b;
  300. var max = Math.max( r, g, b );
  301. var min = Math.min( r, g, b );
  302. var hue, saturation;
  303. var lightness = ( min + max ) / 2.0;
  304. if ( min === max ) {
  305. hue = 0;
  306. saturation = 0;
  307. } else {
  308. var delta = max - min;
  309. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  310. switch ( max ) {
  311. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  312. case g: hue = ( b - r ) / delta + 2; break;
  313. case b: hue = ( r - g ) / delta + 4; break;
  314. }
  315. hue /= 6;
  316. }
  317. hsl.h = hue;
  318. hsl.s = saturation;
  319. hsl.l = lightness;
  320. return hsl;
  321. };
  322. }(),
  323. getStyle: function () {
  324. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  325. },
  326. offsetHSL: function ( h, s, l ) {
  327. var hsl = this.getHSL();
  328. hsl.h += h; hsl.s += s; hsl.l += l;
  329. this.setHSL( hsl.h, hsl.s, hsl.l );
  330. return this;
  331. },
  332. add: function ( color ) {
  333. this.r += color.r;
  334. this.g += color.g;
  335. this.b += color.b;
  336. return this;
  337. },
  338. addColors: function ( color1, color2 ) {
  339. this.r = color1.r + color2.r;
  340. this.g = color1.g + color2.g;
  341. this.b = color1.b + color2.b;
  342. return this;
  343. },
  344. addScalar: function ( s ) {
  345. this.r += s;
  346. this.g += s;
  347. this.b += s;
  348. return this;
  349. },
  350. multiply: function ( color ) {
  351. this.r *= color.r;
  352. this.g *= color.g;
  353. this.b *= color.b;
  354. return this;
  355. },
  356. multiplyScalar: function ( s ) {
  357. this.r *= s;
  358. this.g *= s;
  359. this.b *= s;
  360. return this;
  361. },
  362. lerp: function ( color, alpha ) {
  363. this.r += ( color.r - this.r ) * alpha;
  364. this.g += ( color.g - this.g ) * alpha;
  365. this.b += ( color.b - this.b ) * alpha;
  366. return this;
  367. },
  368. equals: function ( c ) {
  369. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  370. },
  371. clone: function () {
  372. return new THREE.Color().setRGB( this.r, this.g, this.b );
  373. }
  374. } );
  375. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  376. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  377. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  378. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  379. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  380. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  381. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  382. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  383. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  384. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  385. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  386. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  387. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  388. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  389. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  390. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  391. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  392. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  393. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  394. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  395. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  396. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  397. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  398. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  399. /**
  400. * @author mikael emtinger / http://gomo.se/
  401. * @author alteredq / http://alteredqualia.com/
  402. * @author WestLangley / http://github.com/WestLangley
  403. * @author bhouston / http://exocortex.com
  404. */
  405. THREE.Quaternion = function( x, y, z, w ) {
  406. this.x = x || 0;
  407. this.y = y || 0;
  408. this.z = z || 0;
  409. this.w = ( w !== undefined ) ? w : 1;
  410. };
  411. THREE.extend( THREE.Quaternion.prototype, {
  412. set: function ( x, y, z, w ) {
  413. this.x = x;
  414. this.y = y;
  415. this.z = z;
  416. this.w = w;
  417. return this;
  418. },
  419. copy: function ( q ) {
  420. this.x = q.x;
  421. this.y = q.y;
  422. this.z = q.z;
  423. this.w = q.w;
  424. return this;
  425. },
  426. setFromEuler: function ( v, order ) {
  427. // http://www.mathworks.com/matlabcentral/fileexchange/
  428. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  429. // content/SpinCalc.m
  430. var c1 = Math.cos( v.x / 2 );
  431. var c2 = Math.cos( v.y / 2 );
  432. var c3 = Math.cos( v.z / 2 );
  433. var s1 = Math.sin( v.x / 2 );
  434. var s2 = Math.sin( v.y / 2 );
  435. var s3 = Math.sin( v.z / 2 );
  436. if ( order === undefined || order === 'XYZ' ) {
  437. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  438. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  439. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  440. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  441. } else if ( order === 'YXZ' ) {
  442. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  443. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  444. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  445. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  446. } else if ( order === 'ZXY' ) {
  447. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  448. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  449. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  450. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  451. } else if ( order === 'ZYX' ) {
  452. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  453. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  454. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  455. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  456. } else if ( order === 'YZX' ) {
  457. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  458. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  459. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  460. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  461. } else if ( order === 'XZY' ) {
  462. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  463. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  464. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  465. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  466. }
  467. return this;
  468. },
  469. setFromAxisAngle: function ( axis, angle ) {
  470. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  471. // axis have to be normalized
  472. var halfAngle = angle / 2,
  473. s = Math.sin( halfAngle );
  474. this.x = axis.x * s;
  475. this.y = axis.y * s;
  476. this.z = axis.z * s;
  477. this.w = Math.cos( halfAngle );
  478. return this;
  479. },
  480. setFromRotationMatrix: function ( m ) {
  481. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  482. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  483. var te = m.elements,
  484. m11 = te[0], m12 = te[4], m13 = te[8],
  485. m21 = te[1], m22 = te[5], m23 = te[9],
  486. m31 = te[2], m32 = te[6], m33 = te[10],
  487. trace = m11 + m22 + m33,
  488. s;
  489. if ( trace > 0 ) {
  490. s = 0.5 / Math.sqrt( trace + 1.0 );
  491. this.w = 0.25 / s;
  492. this.x = ( m32 - m23 ) * s;
  493. this.y = ( m13 - m31 ) * s;
  494. this.z = ( m21 - m12 ) * s;
  495. } else if ( m11 > m22 && m11 > m33 ) {
  496. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  497. this.w = (m32 - m23 ) / s;
  498. this.x = 0.25 * s;
  499. this.y = (m12 + m21 ) / s;
  500. this.z = (m13 + m31 ) / s;
  501. } else if ( m22 > m33 ) {
  502. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  503. this.w = (m13 - m31 ) / s;
  504. this.x = (m12 + m21 ) / s;
  505. this.y = 0.25 * s;
  506. this.z = (m23 + m32 ) / s;
  507. } else {
  508. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  509. this.w = ( m21 - m12 ) / s;
  510. this.x = ( m13 + m31 ) / s;
  511. this.y = ( m23 + m32 ) / s;
  512. this.z = 0.25 * s;
  513. }
  514. return this;
  515. },
  516. inverse: function () {
  517. this.conjugate().normalize();
  518. return this;
  519. },
  520. conjugate: function () {
  521. this.x *= -1;
  522. this.y *= -1;
  523. this.z *= -1;
  524. return this;
  525. },
  526. lengthSq: function () {
  527. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  528. },
  529. length: function () {
  530. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  531. },
  532. normalize: function () {
  533. var l = this.length();
  534. if ( l === 0 ) {
  535. this.x = 0;
  536. this.y = 0;
  537. this.z = 0;
  538. this.w = 1;
  539. } else {
  540. l = 1 / l;
  541. this.x = this.x * l;
  542. this.y = this.y * l;
  543. this.z = this.z * l;
  544. this.w = this.w * l;
  545. }
  546. return this;
  547. },
  548. multiply: function ( q, p ) {
  549. if ( p !== undefined ) {
  550. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  551. return this.multiplyQuaternions( q, p );
  552. }
  553. return this.multiplyQuaternions( this, q );
  554. },
  555. multiplyQuaternions: function ( a, b ) {
  556. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  557. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w;
  558. var qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  559. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  560. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  561. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  562. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  563. return this;
  564. },
  565. multiplyVector3: function ( vector ) {
  566. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  567. return vector.applyQuaternion( this );
  568. },
  569. slerp: function ( qb, t ) {
  570. var x = this.x, y = this.y, z = this.z, w = this.w;
  571. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  572. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  573. if ( cosHalfTheta < 0 ) {
  574. this.w = -qb.w;
  575. this.x = -qb.x;
  576. this.y = -qb.y;
  577. this.z = -qb.z;
  578. cosHalfTheta = -cosHalfTheta;
  579. } else {
  580. this.copy( qb );
  581. }
  582. if ( cosHalfTheta >= 1.0 ) {
  583. this.w = w;
  584. this.x = x;
  585. this.y = y;
  586. this.z = z;
  587. return this;
  588. }
  589. var halfTheta = Math.acos( cosHalfTheta );
  590. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  591. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  592. this.w = 0.5 * ( w + this.w );
  593. this.x = 0.5 * ( x + this.x );
  594. this.y = 0.5 * ( y + this.y );
  595. this.z = 0.5 * ( z + this.z );
  596. return this;
  597. }
  598. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  599. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  600. this.w = ( w * ratioA + this.w * ratioB );
  601. this.x = ( x * ratioA + this.x * ratioB );
  602. this.y = ( y * ratioA + this.y * ratioB );
  603. this.z = ( z * ratioA + this.z * ratioB );
  604. return this;
  605. },
  606. equals: function ( v ) {
  607. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  608. },
  609. clone: function () {
  610. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  611. }
  612. } );
  613. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  614. return qm.copy( qa ).slerp( qb, t );
  615. }
  616. /**
  617. * @author mrdoob / http://mrdoob.com/
  618. * @author philogb / http://blog.thejit.org/
  619. * @author egraether / http://egraether.com/
  620. * @author zz85 / http://www.lab4games.net/zz85/blog
  621. */
  622. THREE.Vector2 = function ( x, y ) {
  623. this.x = x || 0;
  624. this.y = y || 0;
  625. };
  626. THREE.extend( THREE.Vector2.prototype, {
  627. set: function ( x, y ) {
  628. this.x = x;
  629. this.y = y;
  630. return this;
  631. },
  632. setX: function ( x ) {
  633. this.x = x;
  634. return this;
  635. },
  636. setY: function ( y ) {
  637. this.y = y;
  638. return this;
  639. },
  640. setComponent: function ( index, value ) {
  641. switch ( index ) {
  642. case 0: this.x = value; break;
  643. case 1: this.y = value; break;
  644. default: throw new Error( "index is out of range: " + index );
  645. }
  646. },
  647. getComponent: function ( index ) {
  648. switch ( index ) {
  649. case 0: return this.x;
  650. case 1: return this.y;
  651. default: throw new Error( "index is out of range: " + index );
  652. }
  653. },
  654. copy: function ( v ) {
  655. this.x = v.x;
  656. this.y = v.y;
  657. return this;
  658. },
  659. add: function ( v, w ) {
  660. if ( w !== undefined ) {
  661. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  662. return this.addVectors( v, w );
  663. }
  664. this.x += v.x;
  665. this.y += v.y;
  666. return this;
  667. },
  668. addVectors: function ( a, b ) {
  669. this.x = a.x + b.x;
  670. this.y = a.y + b.y;
  671. return this;
  672. },
  673. addScalar: function ( s ) {
  674. this.x += s;
  675. this.y += s;
  676. return this;
  677. },
  678. sub: function ( v, w ) {
  679. if ( w !== undefined ) {
  680. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  681. return this.subVectors( v, w );
  682. }
  683. this.x -= v.x;
  684. this.y -= v.y;
  685. return this;
  686. },
  687. subVectors: function ( a, b ) {
  688. this.x = a.x - b.x;
  689. this.y = a.y - b.y;
  690. return this;
  691. },
  692. multiplyScalar: function ( s ) {
  693. this.x *= s;
  694. this.y *= s;
  695. return this;
  696. },
  697. divideScalar: function ( s ) {
  698. if ( s !== 0 ) {
  699. this.x /= s;
  700. this.y /= s;
  701. } else {
  702. this.set( 0, 0 );
  703. }
  704. return this;
  705. },
  706. min: function ( v ) {
  707. if ( this.x > v.x ) {
  708. this.x = v.x;
  709. }
  710. if ( this.y > v.y ) {
  711. this.y = v.y;
  712. }
  713. return this;
  714. },
  715. max: function ( v ) {
  716. if ( this.x < v.x ) {
  717. this.x = v.x;
  718. }
  719. if ( this.y < v.y ) {
  720. this.y = v.y;
  721. }
  722. return this;
  723. },
  724. clamp: function ( min, max ) {
  725. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  726. if ( this.x < min.x ) {
  727. this.x = min.x;
  728. } else if ( this.x > max.x ) {
  729. this.x = max.x;
  730. }
  731. if ( this.y < min.y ) {
  732. this.y = min.y;
  733. } else if ( this.y > max.y ) {
  734. this.y = max.y;
  735. }
  736. return this;
  737. },
  738. negate: function() {
  739. return this.multiplyScalar( - 1 );
  740. },
  741. dot: function ( v ) {
  742. return this.x * v.x + this.y * v.y;
  743. },
  744. lengthSq: function () {
  745. return this.x * this.x + this.y * this.y;
  746. },
  747. length: function () {
  748. return Math.sqrt( this.x * this.x + this.y * this.y );
  749. },
  750. normalize: function () {
  751. return this.divideScalar( this.length() );
  752. },
  753. distanceTo: function ( v ) {
  754. return Math.sqrt( this.distanceToSquared( v ) );
  755. },
  756. distanceToSquared: function ( v ) {
  757. var dx = this.x - v.x, dy = this.y - v.y;
  758. return dx * dx + dy * dy;
  759. },
  760. setLength: function ( l ) {
  761. var oldLength = this.length();
  762. if ( oldLength !== 0 && l !== oldLength ) {
  763. this.multiplyScalar( l / oldLength );
  764. }
  765. return this;
  766. },
  767. lerp: function ( v, alpha ) {
  768. this.x += ( v.x - this.x ) * alpha;
  769. this.y += ( v.y - this.y ) * alpha;
  770. return this;
  771. },
  772. equals: function( v ) {
  773. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  774. },
  775. toArray: function () {
  776. return [ this.x, this.y ];
  777. },
  778. clone: function () {
  779. return new THREE.Vector2( this.x, this.y );
  780. }
  781. } );
  782. /**
  783. * @author mrdoob / http://mrdoob.com/
  784. * @author *kile / http://kile.stravaganza.org/
  785. * @author philogb / http://blog.thejit.org/
  786. * @author mikael emtinger / http://gomo.se/
  787. * @author egraether / http://egraether.com/
  788. * @author WestLangley / http://github.com/WestLangley
  789. */
  790. THREE.Vector3 = function ( x, y, z ) {
  791. this.x = x || 0;
  792. this.y = y || 0;
  793. this.z = z || 0;
  794. };
  795. THREE.extend( THREE.Vector3.prototype, {
  796. set: function ( x, y, z ) {
  797. this.x = x;
  798. this.y = y;
  799. this.z = z;
  800. return this;
  801. },
  802. setX: function ( x ) {
  803. this.x = x;
  804. return this;
  805. },
  806. setY: function ( y ) {
  807. this.y = y;
  808. return this;
  809. },
  810. setZ: function ( z ) {
  811. this.z = z;
  812. return this;
  813. },
  814. setComponent: function ( index, value ) {
  815. switch ( index ) {
  816. case 0: this.x = value; break;
  817. case 1: this.y = value; break;
  818. case 2: this.z = value; break;
  819. default: throw new Error( "index is out of range: " + index );
  820. }
  821. },
  822. getComponent: function ( index ) {
  823. switch ( index ) {
  824. case 0: return this.x;
  825. case 1: return this.y;
  826. case 2: return this.z;
  827. default: throw new Error( "index is out of range: " + index );
  828. }
  829. },
  830. copy: function ( v ) {
  831. this.x = v.x;
  832. this.y = v.y;
  833. this.z = v.z;
  834. return this;
  835. },
  836. add: function ( v, w ) {
  837. if ( w !== undefined ) {
  838. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  839. return this.addVectors( v, w );
  840. }
  841. this.x += v.x;
  842. this.y += v.y;
  843. this.z += v.z;
  844. return this;
  845. },
  846. addScalar: function ( s ) {
  847. this.x += s;
  848. this.y += s;
  849. this.z += s;
  850. return this;
  851. },
  852. addVectors: function ( a, b ) {
  853. this.x = a.x + b.x;
  854. this.y = a.y + b.y;
  855. this.z = a.z + b.z;
  856. return this;
  857. },
  858. sub: function ( v, w ) {
  859. if ( w !== undefined ) {
  860. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  861. return this.subVectors( v, w );
  862. }
  863. this.x -= v.x;
  864. this.y -= v.y;
  865. this.z -= v.z;
  866. return this;
  867. },
  868. subVectors: function ( a, b ) {
  869. this.x = a.x - b.x;
  870. this.y = a.y - b.y;
  871. this.z = a.z - b.z;
  872. return this;
  873. },
  874. multiply: function ( v, w ) {
  875. if ( w !== undefined ) {
  876. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  877. return this.multiplyVectors( v, w );
  878. }
  879. this.x *= v.x;
  880. this.y *= v.y;
  881. this.z *= v.z;
  882. return this;
  883. },
  884. multiplyScalar: function ( s ) {
  885. this.x *= s;
  886. this.y *= s;
  887. this.z *= s;
  888. return this;
  889. },
  890. multiplyVectors: function ( a, b ) {
  891. this.x = a.x * b.x;
  892. this.y = a.y * b.y;
  893. this.z = a.z * b.z;
  894. return this;
  895. },
  896. applyMatrix3: function ( m ) {
  897. var x = this.x;
  898. var y = this.y;
  899. var z = this.z;
  900. var e = m.elements;
  901. this.x = e[0] * x + e[3] * y + e[6] * z;
  902. this.y = e[1] * x + e[4] * y + e[7] * z;
  903. this.z = e[2] * x + e[5] * y + e[8] * z;
  904. return this;
  905. },
  906. applyMatrix4: function ( m ) {
  907. // input: THREE.Matrix4 affine matrix
  908. var x = this.x, y = this.y, z = this.z;
  909. var e = m.elements;
  910. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  911. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  912. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  913. return this;
  914. },
  915. applyProjection: function ( m ) {
  916. // input: THREE.Matrix4 projection matrix
  917. var x = this.x, y = this.y, z = this.z;
  918. var e = m.elements;
  919. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  920. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  921. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  922. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  923. return this;
  924. },
  925. applyQuaternion: function ( q ) {
  926. var x = this.x;
  927. var y = this.y;
  928. var z = this.z;
  929. var qx = q.x;
  930. var qy = q.y;
  931. var qz = q.z;
  932. var qw = q.w;
  933. // calculate quat * vector
  934. var ix = qw * x + qy * z - qz * y;
  935. var iy = qw * y + qz * x - qx * z;
  936. var iz = qw * z + qx * y - qy * x;
  937. var iw = -qx * x - qy * y - qz * z;
  938. // calculate result * inverse quat
  939. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  940. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  941. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  942. return this;
  943. },
  944. applyEuler: function () {
  945. var q1 = new THREE.Quaternion();
  946. return function ( v, eulerOrder ) {
  947. var quaternion = q1.setFromEuler( v, eulerOrder );
  948. this.applyQuaternion( quaternion );
  949. return this;
  950. };
  951. }(),
  952. applyAxisAngle: function () {
  953. var q1 = new THREE.Quaternion();
  954. return function ( axis, angle ) {
  955. var quaternion = q1.setFromAxisAngle( axis, angle );
  956. this.applyQuaternion( quaternion );
  957. return this;
  958. };
  959. }(),
  960. transformDirection: function ( m ) {
  961. // input: THREE.Matrix4 affine matrix
  962. // vector interpreted as a direction
  963. var x = this.x, y = this.y, z = this.z;
  964. var e = m.elements;
  965. this.x = e[0] * x + e[4] * y + e[8] * z;
  966. this.y = e[1] * x + e[5] * y + e[9] * z;
  967. this.z = e[2] * x + e[6] * y + e[10] * z;
  968. this.normalize();
  969. return this;
  970. },
  971. divide: function ( v ) {
  972. this.x /= v.x;
  973. this.y /= v.y;
  974. this.z /= v.z;
  975. return this;
  976. },
  977. divideScalar: function ( s ) {
  978. if ( s !== 0 ) {
  979. this.x /= s;
  980. this.y /= s;
  981. this.z /= s;
  982. } else {
  983. this.x = 0;
  984. this.y = 0;
  985. this.z = 0;
  986. }
  987. return this;
  988. },
  989. min: function ( v ) {
  990. if ( this.x > v.x ) {
  991. this.x = v.x;
  992. }
  993. if ( this.y > v.y ) {
  994. this.y = v.y;
  995. }
  996. if ( this.z > v.z ) {
  997. this.z = v.z;
  998. }
  999. return this;
  1000. },
  1001. max: function ( v ) {
  1002. if ( this.x < v.x ) {
  1003. this.x = v.x;
  1004. }
  1005. if ( this.y < v.y ) {
  1006. this.y = v.y;
  1007. }
  1008. if ( this.z < v.z ) {
  1009. this.z = v.z;
  1010. }
  1011. return this;
  1012. },
  1013. clamp: function ( min, max ) {
  1014. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1015. if ( this.x < min.x ) {
  1016. this.x = min.x;
  1017. } else if ( this.x > max.x ) {
  1018. this.x = max.x;
  1019. }
  1020. if ( this.y < min.y ) {
  1021. this.y = min.y;
  1022. } else if ( this.y > max.y ) {
  1023. this.y = max.y;
  1024. }
  1025. if ( this.z < min.z ) {
  1026. this.z = min.z;
  1027. } else if ( this.z > max.z ) {
  1028. this.z = max.z;
  1029. }
  1030. return this;
  1031. },
  1032. negate: function () {
  1033. return this.multiplyScalar( - 1 );
  1034. },
  1035. dot: function ( v ) {
  1036. return this.x * v.x + this.y * v.y + this.z * v.z;
  1037. },
  1038. lengthSq: function () {
  1039. return this.x * this.x + this.y * this.y + this.z * this.z;
  1040. },
  1041. length: function () {
  1042. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1043. },
  1044. lengthManhattan: function () {
  1045. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1046. },
  1047. normalize: function () {
  1048. return this.divideScalar( this.length() );
  1049. },
  1050. setLength: function ( l ) {
  1051. var oldLength = this.length();
  1052. if ( oldLength !== 0 && l !== oldLength ) {
  1053. this.multiplyScalar( l / oldLength );
  1054. }
  1055. return this;
  1056. },
  1057. lerp: function ( v, alpha ) {
  1058. this.x += ( v.x - this.x ) * alpha;
  1059. this.y += ( v.y - this.y ) * alpha;
  1060. this.z += ( v.z - this.z ) * alpha;
  1061. return this;
  1062. },
  1063. cross: function ( v, w ) {
  1064. if ( w !== undefined ) {
  1065. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1066. return this.crossVectors( v, w );
  1067. }
  1068. var x = this.x, y = this.y, z = this.z;
  1069. this.x = y * v.z - z * v.y;
  1070. this.y = z * v.x - x * v.z;
  1071. this.z = x * v.y - y * v.x;
  1072. return this;
  1073. },
  1074. crossVectors: function ( a, b ) {
  1075. this.x = a.y * b.z - a.z * b.y;
  1076. this.y = a.z * b.x - a.x * b.z;
  1077. this.z = a.x * b.y - a.y * b.x;
  1078. return this;
  1079. },
  1080. projectOnVector: function () {
  1081. var v1 = new THREE.Vector3();
  1082. return function( vector ) {
  1083. v1.copy( vector ).normalize();
  1084. var d = this.dot( v1 );
  1085. return this.copy( v1 ).multiplyScalar( d );
  1086. };
  1087. }(),
  1088. projectOnPlane: function () {
  1089. var v1 = new THREE.Vector3();
  1090. return function( planeNormal ) {
  1091. v1.copy( this ).projectOnVector( planeNormal );
  1092. return this.sub( v1 );
  1093. }
  1094. }(),
  1095. reflect: function () {
  1096. var v1 = new THREE.Vector3();
  1097. return function ( vector ) {
  1098. v1.copy( this ).projectOnVector( vector ).multiplyScalar( 2 );
  1099. return this.subVectors( v1, this );
  1100. }
  1101. }(),
  1102. angleTo: function ( v ) {
  1103. var theta = this.dot( v ) / ( this.length() * v.length() );
  1104. // clamp, to handle numerical problems
  1105. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1106. },
  1107. distanceTo: function ( v ) {
  1108. return Math.sqrt( this.distanceToSquared( v ) );
  1109. },
  1110. distanceToSquared: function ( v ) {
  1111. var dx = this.x - v.x;
  1112. var dy = this.y - v.y;
  1113. var dz = this.z - v.z;
  1114. return dx * dx + dy * dy + dz * dz;
  1115. },
  1116. setEulerFromRotationMatrix: function ( m, order ) {
  1117. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1118. // clamp, to handle numerical problems
  1119. function clamp( x ) {
  1120. return Math.min( Math.max( x, -1 ), 1 );
  1121. }
  1122. var te = m.elements;
  1123. var m11 = te[0], m12 = te[4], m13 = te[8];
  1124. var m21 = te[1], m22 = te[5], m23 = te[9];
  1125. var m31 = te[2], m32 = te[6], m33 = te[10];
  1126. if ( order === undefined || order === 'XYZ' ) {
  1127. this.y = Math.asin( clamp( m13 ) );
  1128. if ( Math.abs( m13 ) < 0.99999 ) {
  1129. this.x = Math.atan2( - m23, m33 );
  1130. this.z = Math.atan2( - m12, m11 );
  1131. } else {
  1132. this.x = Math.atan2( m32, m22 );
  1133. this.z = 0;
  1134. }
  1135. } else if ( order === 'YXZ' ) {
  1136. this.x = Math.asin( - clamp( m23 ) );
  1137. if ( Math.abs( m23 ) < 0.99999 ) {
  1138. this.y = Math.atan2( m13, m33 );
  1139. this.z = Math.atan2( m21, m22 );
  1140. } else {
  1141. this.y = Math.atan2( - m31, m11 );
  1142. this.z = 0;
  1143. }
  1144. } else if ( order === 'ZXY' ) {
  1145. this.x = Math.asin( clamp( m32 ) );
  1146. if ( Math.abs( m32 ) < 0.99999 ) {
  1147. this.y = Math.atan2( - m31, m33 );
  1148. this.z = Math.atan2( - m12, m22 );
  1149. } else {
  1150. this.y = 0;
  1151. this.z = Math.atan2( m21, m11 );
  1152. }
  1153. } else if ( order === 'ZYX' ) {
  1154. this.y = Math.asin( - clamp( m31 ) );
  1155. if ( Math.abs( m31 ) < 0.99999 ) {
  1156. this.x = Math.atan2( m32, m33 );
  1157. this.z = Math.atan2( m21, m11 );
  1158. } else {
  1159. this.x = 0;
  1160. this.z = Math.atan2( - m12, m22 );
  1161. }
  1162. } else if ( order === 'YZX' ) {
  1163. this.z = Math.asin( clamp( m21 ) );
  1164. if ( Math.abs( m21 ) < 0.99999 ) {
  1165. this.x = Math.atan2( - m23, m22 );
  1166. this.y = Math.atan2( - m31, m11 );
  1167. } else {
  1168. this.x = 0;
  1169. this.y = Math.atan2( m13, m33 );
  1170. }
  1171. } else if ( order === 'XZY' ) {
  1172. this.z = Math.asin( - clamp( m12 ) );
  1173. if ( Math.abs( m12 ) < 0.99999 ) {
  1174. this.x = Math.atan2( m32, m22 );
  1175. this.y = Math.atan2( m13, m11 );
  1176. } else {
  1177. this.x = Math.atan2( - m23, m33 );
  1178. this.y = 0;
  1179. }
  1180. }
  1181. return this;
  1182. },
  1183. setEulerFromQuaternion: function ( q, order ) {
  1184. // q is assumed to be normalized
  1185. // clamp, to handle numerical problems
  1186. function clamp( x ) {
  1187. return Math.min( Math.max( x, -1 ), 1 );
  1188. }
  1189. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1190. var sqx = q.x * q.x;
  1191. var sqy = q.y * q.y;
  1192. var sqz = q.z * q.z;
  1193. var sqw = q.w * q.w;
  1194. if ( order === undefined || order === 'XYZ' ) {
  1195. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1196. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1197. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1198. } else if ( order === 'YXZ' ) {
  1199. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1200. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1201. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1202. } else if ( order === 'ZXY' ) {
  1203. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1204. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1205. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1206. } else if ( order === 'ZYX' ) {
  1207. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1208. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1209. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1210. } else if ( order === 'YZX' ) {
  1211. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1212. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1213. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1214. } else if ( order === 'XZY' ) {
  1215. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1216. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1217. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1218. }
  1219. return this;
  1220. },
  1221. getPositionFromMatrix: function ( m ) {
  1222. this.x = m.elements[12];
  1223. this.y = m.elements[13];
  1224. this.z = m.elements[14];
  1225. return this;
  1226. },
  1227. getScaleFromMatrix: function ( m ) {
  1228. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  1229. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  1230. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  1231. this.x = sx;
  1232. this.y = sy;
  1233. this.z = sz;
  1234. return this;
  1235. },
  1236. getColumnFromMatrix: function ( index, matrix ) {
  1237. var offset = index * 4;
  1238. var me = matrix.elements;
  1239. this.x = me[ offset ];
  1240. this.y = me[ offset + 1 ];
  1241. this.z = me[ offset + 2 ];
  1242. return this;
  1243. },
  1244. equals: function ( v ) {
  1245. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1246. },
  1247. toArray: function () {
  1248. return [ this.x, this.y, this.z ];
  1249. },
  1250. clone: function () {
  1251. return new THREE.Vector3( this.x, this.y, this.z );
  1252. }
  1253. } );
  1254. /**
  1255. * @author supereggbert / http://www.paulbrunt.co.uk/
  1256. * @author philogb / http://blog.thejit.org/
  1257. * @author mikael emtinger / http://gomo.se/
  1258. * @author egraether / http://egraether.com/
  1259. * @author WestLangley / http://github.com/WestLangley
  1260. */
  1261. THREE.Vector4 = function ( x, y, z, w ) {
  1262. this.x = x || 0;
  1263. this.y = y || 0;
  1264. this.z = z || 0;
  1265. this.w = ( w !== undefined ) ? w : 1;
  1266. };
  1267. THREE.extend( THREE.Vector4.prototype, {
  1268. set: function ( x, y, z, w ) {
  1269. this.x = x;
  1270. this.y = y;
  1271. this.z = z;
  1272. this.w = w;
  1273. return this;
  1274. },
  1275. setX: function ( x ) {
  1276. this.x = x;
  1277. return this;
  1278. },
  1279. setY: function ( y ) {
  1280. this.y = y;
  1281. return this;
  1282. },
  1283. setZ: function ( z ) {
  1284. this.z = z;
  1285. return this;
  1286. },
  1287. setW: function ( w ) {
  1288. this.w = w;
  1289. return this;
  1290. },
  1291. setComponent: function ( index, value ) {
  1292. switch ( index ) {
  1293. case 0: this.x = value; break;
  1294. case 1: this.y = value; break;
  1295. case 2: this.z = value; break;
  1296. case 3: this.w = value; break;
  1297. default: throw new Error( "index is out of range: " + index );
  1298. }
  1299. },
  1300. getComponent: function ( index ) {
  1301. switch ( index ) {
  1302. case 0: return this.x;
  1303. case 1: return this.y;
  1304. case 2: return this.z;
  1305. case 3: return this.w;
  1306. default: throw new Error( "index is out of range: " + index );
  1307. }
  1308. },
  1309. copy: function ( v ) {
  1310. this.x = v.x;
  1311. this.y = v.y;
  1312. this.z = v.z;
  1313. this.w = ( v.w !== undefined ) ? v.w : 1;
  1314. return this;
  1315. },
  1316. add: function ( v, w ) {
  1317. if ( w !== undefined ) {
  1318. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1319. return this.addVectors( v, w );
  1320. }
  1321. this.x += v.x;
  1322. this.y += v.y;
  1323. this.z += v.z;
  1324. this.w += v.w;
  1325. return this;
  1326. },
  1327. addScalar: function ( s ) {
  1328. this.x += s;
  1329. this.y += s;
  1330. this.z += s;
  1331. this.w += s;
  1332. return this;
  1333. },
  1334. addVectors: function ( a, b ) {
  1335. this.x = a.x + b.x;
  1336. this.y = a.y + b.y;
  1337. this.z = a.z + b.z;
  1338. this.w = a.w + b.w;
  1339. return this;
  1340. },
  1341. sub: function ( v, w ) {
  1342. if ( w !== undefined ) {
  1343. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1344. return this.subVectors( v, w );
  1345. }
  1346. this.x -= v.x;
  1347. this.y -= v.y;
  1348. this.z -= v.z;
  1349. this.w -= v.w;
  1350. return this;
  1351. },
  1352. subVectors: function ( a, b ) {
  1353. this.x = a.x - b.x;
  1354. this.y = a.y - b.y;
  1355. this.z = a.z - b.z;
  1356. this.w = a.w - b.w;
  1357. return this;
  1358. },
  1359. multiplyScalar: function ( s ) {
  1360. this.x *= s;
  1361. this.y *= s;
  1362. this.z *= s;
  1363. this.w *= s;
  1364. return this;
  1365. },
  1366. applyMatrix4: function ( m ) {
  1367. var x = this.x;
  1368. var y = this.y;
  1369. var z = this.z;
  1370. var w = this.w;
  1371. var e = m.elements;
  1372. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1373. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1374. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1375. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1376. return this;
  1377. },
  1378. divideScalar: function ( s ) {
  1379. if ( s !== 0 ) {
  1380. this.x /= s;
  1381. this.y /= s;
  1382. this.z /= s;
  1383. this.w /= s;
  1384. } else {
  1385. this.x = 0;
  1386. this.y = 0;
  1387. this.z = 0;
  1388. this.w = 1;
  1389. }
  1390. return this;
  1391. },
  1392. setAxisAngleFromQuaternion: function ( q ) {
  1393. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1394. // q is assumed to be normalized
  1395. this.w = 2 * Math.acos( q.w );
  1396. var s = Math.sqrt( 1 - q.w * q.w );
  1397. if ( s < 0.0001 ) {
  1398. this.x = 1;
  1399. this.y = 0;
  1400. this.z = 0;
  1401. } else {
  1402. this.x = q.x / s;
  1403. this.y = q.y / s;
  1404. this.z = q.z / s;
  1405. }
  1406. return this;
  1407. },
  1408. setAxisAngleFromRotationMatrix: function ( m ) {
  1409. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1410. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1411. var angle, x, y, z, // variables for result
  1412. epsilon = 0.01, // margin to allow for rounding errors
  1413. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1414. te = m.elements,
  1415. m11 = te[0], m12 = te[4], m13 = te[8],
  1416. m21 = te[1], m22 = te[5], m23 = te[9],
  1417. m31 = te[2], m32 = te[6], m33 = te[10];
  1418. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1419. && ( Math.abs( m13 - m31 ) < epsilon )
  1420. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1421. // singularity found
  1422. // first check for identity matrix which must have +1 for all terms
  1423. // in leading diagonal and zero in other terms
  1424. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1425. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1426. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1427. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1428. // this singularity is identity matrix so angle = 0
  1429. this.set( 1, 0, 0, 0 );
  1430. return this; // zero angle, arbitrary axis
  1431. }
  1432. // otherwise this singularity is angle = 180
  1433. angle = Math.PI;
  1434. var xx = ( m11 + 1 ) / 2;
  1435. var yy = ( m22 + 1 ) / 2;
  1436. var zz = ( m33 + 1 ) / 2;
  1437. var xy = ( m12 + m21 ) / 4;
  1438. var xz = ( m13 + m31 ) / 4;
  1439. var yz = ( m23 + m32 ) / 4;
  1440. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1441. if ( xx < epsilon ) {
  1442. x = 0;
  1443. y = 0.707106781;
  1444. z = 0.707106781;
  1445. } else {
  1446. x = Math.sqrt( xx );
  1447. y = xy / x;
  1448. z = xz / x;
  1449. }
  1450. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1451. if ( yy < epsilon ) {
  1452. x = 0.707106781;
  1453. y = 0;
  1454. z = 0.707106781;
  1455. } else {
  1456. y = Math.sqrt( yy );
  1457. x = xy / y;
  1458. z = yz / y;
  1459. }
  1460. } else { // m33 is the largest diagonal term so base result on this
  1461. if ( zz < epsilon ) {
  1462. x = 0.707106781;
  1463. y = 0.707106781;
  1464. z = 0;
  1465. } else {
  1466. z = Math.sqrt( zz );
  1467. x = xz / z;
  1468. y = yz / z;
  1469. }
  1470. }
  1471. this.set( x, y, z, angle );
  1472. return this; // return 180 deg rotation
  1473. }
  1474. // as we have reached here there are no singularities so we can handle normally
  1475. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1476. + ( m13 - m31 ) * ( m13 - m31 )
  1477. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1478. if ( Math.abs( s ) < 0.001 ) s = 1;
  1479. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1480. // caught by singularity test above, but I've left it in just in case
  1481. this.x = ( m32 - m23 ) / s;
  1482. this.y = ( m13 - m31 ) / s;
  1483. this.z = ( m21 - m12 ) / s;
  1484. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1485. return this;
  1486. },
  1487. min: function ( v ) {
  1488. if ( this.x > v.x ) {
  1489. this.x = v.x;
  1490. }
  1491. if ( this.y > v.y ) {
  1492. this.y = v.y;
  1493. }
  1494. if ( this.z > v.z ) {
  1495. this.z = v.z;
  1496. }
  1497. if ( this.w > v.w ) {
  1498. this.w = v.w;
  1499. }
  1500. return this;
  1501. },
  1502. max: function ( v ) {
  1503. if ( this.x < v.x ) {
  1504. this.x = v.x;
  1505. }
  1506. if ( this.y < v.y ) {
  1507. this.y = v.y;
  1508. }
  1509. if ( this.z < v.z ) {
  1510. this.z = v.z;
  1511. }
  1512. if ( this.w < v.w ) {
  1513. this.w = v.w;
  1514. }
  1515. return this;
  1516. },
  1517. clamp: function ( min, max ) {
  1518. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1519. if ( this.x < min.x ) {
  1520. this.x = min.x;
  1521. } else if ( this.x > max.x ) {
  1522. this.x = max.x;
  1523. }
  1524. if ( this.y < min.y ) {
  1525. this.y = min.y;
  1526. } else if ( this.y > max.y ) {
  1527. this.y = max.y;
  1528. }
  1529. if ( this.z < min.z ) {
  1530. this.z = min.z;
  1531. } else if ( this.z > max.z ) {
  1532. this.z = max.z;
  1533. }
  1534. if ( this.w < min.w ) {
  1535. this.w = min.w;
  1536. } else if ( this.w > max.w ) {
  1537. this.w = max.w;
  1538. }
  1539. return this;
  1540. },
  1541. negate: function() {
  1542. return this.multiplyScalar( -1 );
  1543. },
  1544. dot: function ( v ) {
  1545. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1546. },
  1547. lengthSq: function () {
  1548. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1549. },
  1550. length: function () {
  1551. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1552. },
  1553. lengthManhattan: function () {
  1554. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1555. },
  1556. normalize: function () {
  1557. return this.divideScalar( this.length() );
  1558. },
  1559. setLength: function ( l ) {
  1560. var oldLength = this.length();
  1561. if ( oldLength !== 0 && l !== oldLength ) {
  1562. this.multiplyScalar( l / oldLength );
  1563. }
  1564. return this;
  1565. },
  1566. lerp: function ( v, alpha ) {
  1567. this.x += ( v.x - this.x ) * alpha;
  1568. this.y += ( v.y - this.y ) * alpha;
  1569. this.z += ( v.z - this.z ) * alpha;
  1570. this.w += ( v.w - this.w ) * alpha;
  1571. return this;
  1572. },
  1573. equals: function ( v ) {
  1574. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1575. },
  1576. toArray: function () {
  1577. return [ this.x, this.y, this.z, this.w ];
  1578. },
  1579. clone: function () {
  1580. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1581. }
  1582. } );
  1583. /**
  1584. * @author bhouston / http://exocortex.com
  1585. */
  1586. THREE.Box2 = function ( min, max ) {
  1587. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1588. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1589. };
  1590. THREE.extend( THREE.Box2.prototype, {
  1591. set: function ( min, max ) {
  1592. this.min.copy( min );
  1593. this.max.copy( max );
  1594. return this;
  1595. },
  1596. setFromPoints: function ( points ) {
  1597. if ( points.length > 0 ) {
  1598. var point = points[ 0 ];
  1599. this.min.copy( point );
  1600. this.max.copy( point );
  1601. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1602. point = points[ i ];
  1603. if ( point.x < this.min.x ) {
  1604. this.min.x = point.x;
  1605. } else if ( point.x > this.max.x ) {
  1606. this.max.x = point.x;
  1607. }
  1608. if ( point.y < this.min.y ) {
  1609. this.min.y = point.y;
  1610. } else if ( point.y > this.max.y ) {
  1611. this.max.y = point.y;
  1612. }
  1613. }
  1614. } else {
  1615. this.makeEmpty();
  1616. }
  1617. return this;
  1618. },
  1619. setFromCenterAndSize: function() {
  1620. var v1 = new THREE.Vector2();
  1621. return function ( center, size ) {
  1622. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1623. this.min.copy( center ).sub( halfSize );
  1624. this.max.copy( center ).add( halfSize );
  1625. return this;
  1626. };
  1627. }(),
  1628. copy: function ( box ) {
  1629. this.min.copy( box.min );
  1630. this.max.copy( box.max );
  1631. return this;
  1632. },
  1633. makeEmpty: function () {
  1634. this.min.x = this.min.y = Infinity;
  1635. this.max.x = this.max.y = -Infinity;
  1636. return this;
  1637. },
  1638. empty: function () {
  1639. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1640. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1641. },
  1642. center: function ( optionalTarget ) {
  1643. var result = optionalTarget || new THREE.Vector2();
  1644. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1645. },
  1646. size: function ( optionalTarget ) {
  1647. var result = optionalTarget || new THREE.Vector2();
  1648. return result.subVectors( this.max, this.min );
  1649. },
  1650. expandByPoint: function ( point ) {
  1651. this.min.min( point );
  1652. this.max.max( point );
  1653. return this;
  1654. },
  1655. expandByVector: function ( vector ) {
  1656. this.min.sub( vector );
  1657. this.max.add( vector );
  1658. return this;
  1659. },
  1660. expandByScalar: function ( scalar ) {
  1661. this.min.addScalar( -scalar );
  1662. this.max.addScalar( scalar );
  1663. return this;
  1664. },
  1665. containsPoint: function ( point ) {
  1666. if ( point.x < this.min.x || point.x > this.max.x ||
  1667. point.y < this.min.y || point.y > this.max.y ) {
  1668. return false;
  1669. }
  1670. return true;
  1671. },
  1672. containsBox: function ( box ) {
  1673. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1674. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1675. return true;
  1676. }
  1677. return false;
  1678. },
  1679. getParameter: function ( point ) {
  1680. // This can potentially have a divide by zero if the box
  1681. // has a size dimension of 0.
  1682. return new THREE.Vector2(
  1683. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1684. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1685. );
  1686. },
  1687. isIntersectionBox: function ( box ) {
  1688. // using 6 splitting planes to rule out intersections.
  1689. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1690. box.max.y < this.min.y || box.min.y > this.max.y ) {
  1691. return false;
  1692. }
  1693. return true;
  1694. },
  1695. clampPoint: function ( point, optionalTarget ) {
  1696. var result = optionalTarget || new THREE.Vector2();
  1697. return result.copy( point ).clamp( this.min, this.max );
  1698. },
  1699. distanceToPoint: function() {
  1700. var v1 = new THREE.Vector2();
  1701. return function ( point ) {
  1702. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1703. return clampedPoint.sub( point ).length();
  1704. };
  1705. }(),
  1706. intersect: function ( box ) {
  1707. this.min.max( box.min );
  1708. this.max.min( box.max );
  1709. return this;
  1710. },
  1711. union: function ( box ) {
  1712. this.min.min( box.min );
  1713. this.max.max( box.max );
  1714. return this;
  1715. },
  1716. translate: function ( offset ) {
  1717. this.min.add( offset );
  1718. this.max.add( offset );
  1719. return this;
  1720. },
  1721. equals: function ( box ) {
  1722. return box.min.equals( this.min ) && box.max.equals( this.max );
  1723. },
  1724. clone: function () {
  1725. return new THREE.Box2().copy( this );
  1726. }
  1727. } );
  1728. /**
  1729. * @author bhouston / http://exocortex.com
  1730. */
  1731. THREE.Box3 = function ( min, max ) {
  1732. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  1733. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  1734. };
  1735. THREE.extend( THREE.Box3.prototype, {
  1736. set: function ( min, max ) {
  1737. this.min.copy( min );
  1738. this.max.copy( max );
  1739. return this;
  1740. },
  1741. setFromPoints: function ( points ) {
  1742. if ( points.length > 0 ) {
  1743. var point = points[ 0 ];
  1744. this.min.copy( point );
  1745. this.max.copy( point );
  1746. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1747. point = points[ i ];
  1748. if ( point.x < this.min.x ) {
  1749. this.min.x = point.x;
  1750. } else if ( point.x > this.max.x ) {
  1751. this.max.x = point.x;
  1752. }
  1753. if ( point.y < this.min.y ) {
  1754. this.min.y = point.y;
  1755. } else if ( point.y > this.max.y ) {
  1756. this.max.y = point.y;
  1757. }
  1758. if ( point.z < this.min.z ) {
  1759. this.min.z = point.z;
  1760. } else if ( point.z > this.max.z ) {
  1761. this.max.z = point.z;
  1762. }
  1763. }
  1764. } else {
  1765. this.makeEmpty();
  1766. }
  1767. return this;
  1768. },
  1769. setFromCenterAndSize: function() {
  1770. var v1 = new THREE.Vector3();
  1771. return function ( center, size ) {
  1772. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1773. this.min.copy( center ).sub( halfSize );
  1774. this.max.copy( center ).add( halfSize );
  1775. return this;
  1776. };
  1777. }(),
  1778. copy: function ( box ) {
  1779. this.min.copy( box.min );
  1780. this.max.copy( box.max );
  1781. return this;
  1782. },
  1783. makeEmpty: function () {
  1784. this.min.x = this.min.y = this.min.z = Infinity;
  1785. this.max.x = this.max.y = this.max.z = -Infinity;
  1786. return this;
  1787. },
  1788. empty: function () {
  1789. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1790. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  1791. },
  1792. center: function ( optionalTarget ) {
  1793. var result = optionalTarget || new THREE.Vector3();
  1794. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1795. },
  1796. size: function ( optionalTarget ) {
  1797. var result = optionalTarget || new THREE.Vector3();
  1798. return result.subVectors( this.max, this.min );
  1799. },
  1800. expandByPoint: function ( point ) {
  1801. this.min.min( point );
  1802. this.max.max( point );
  1803. return this;
  1804. },
  1805. expandByVector: function ( vector ) {
  1806. this.min.sub( vector );
  1807. this.max.add( vector );
  1808. return this;
  1809. },
  1810. expandByScalar: function ( scalar ) {
  1811. this.min.addScalar( -scalar );
  1812. this.max.addScalar( scalar );
  1813. return this;
  1814. },
  1815. containsPoint: function ( point ) {
  1816. if ( point.x < this.min.x || point.x > this.max.x ||
  1817. point.y < this.min.y || point.y > this.max.y ||
  1818. point.z < this.min.z || point.z > this.max.z ) {
  1819. return false;
  1820. }
  1821. return true;
  1822. },
  1823. containsBox: function ( box ) {
  1824. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1825. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  1826. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  1827. return true;
  1828. }
  1829. return false;
  1830. },
  1831. getParameter: function ( point ) {
  1832. // This can potentially have a divide by zero if the box
  1833. // has a size dimension of 0.
  1834. return new THREE.Vector3(
  1835. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1836. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  1837. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  1838. );
  1839. },
  1840. isIntersectionBox: function ( box ) {
  1841. // using 6 splitting planes to rule out intersections.
  1842. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1843. box.max.y < this.min.y || box.min.y > this.max.y ||
  1844. box.max.z < this.min.z || box.min.z > this.max.z ) {
  1845. return false;
  1846. }
  1847. return true;
  1848. },
  1849. clampPoint: function ( point, optionalTarget ) {
  1850. var result = optionalTarget || new THREE.Vector3();
  1851. return result.copy( point ).clamp( this.min, this.max );
  1852. },
  1853. distanceToPoint: function() {
  1854. var v1 = new THREE.Vector3();
  1855. return function ( point ) {
  1856. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1857. return clampedPoint.sub( point ).length();
  1858. };
  1859. }(),
  1860. getBoundingSphere: function() {
  1861. var v1 = new THREE.Vector3();
  1862. return function ( optionalTarget ) {
  1863. var result = optionalTarget || new THREE.Sphere();
  1864. result.center = this.center();
  1865. result.radius = this.size( v1 ).length() * 0.5;
  1866. return result;
  1867. };
  1868. }(),
  1869. intersect: function ( box ) {
  1870. this.min.max( box.min );
  1871. this.max.min( box.max );
  1872. return this;
  1873. },
  1874. union: function ( box ) {
  1875. this.min.min( box.min );
  1876. this.max.max( box.max );
  1877. return this;
  1878. },
  1879. applyMatrix4: function() {
  1880. var points = [
  1881. new THREE.Vector3(),
  1882. new THREE.Vector3(),
  1883. new THREE.Vector3(),
  1884. new THREE.Vector3(),
  1885. new THREE.Vector3(),
  1886. new THREE.Vector3(),
  1887. new THREE.Vector3(),
  1888. new THREE.Vector3()
  1889. ];
  1890. return function ( matrix ) {
  1891. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  1892. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  1893. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  1894. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  1895. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  1896. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  1897. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  1898. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  1899. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  1900. this.makeEmpty();
  1901. this.setFromPoints( points );
  1902. return this;
  1903. };
  1904. }(),
  1905. translate: function ( offset ) {
  1906. this.min.add( offset );
  1907. this.max.add( offset );
  1908. return this;
  1909. },
  1910. equals: function ( box ) {
  1911. return box.min.equals( this.min ) && box.max.equals( this.max );
  1912. },
  1913. clone: function () {
  1914. return new THREE.Box3().copy( this );
  1915. }
  1916. } );
  1917. /**
  1918. * @author alteredq / http://alteredqualia.com/
  1919. * @author WestLangley / http://github.com/WestLangley
  1920. * @author bhouston / http://exocortex.com
  1921. */
  1922. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1923. this.elements = new Float32Array(9);
  1924. this.set(
  1925. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  1926. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  1927. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  1928. );
  1929. };
  1930. THREE.extend( THREE.Matrix3.prototype, {
  1931. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1932. var te = this.elements;
  1933. te[0] = n11; te[3] = n12; te[6] = n13;
  1934. te[1] = n21; te[4] = n22; te[7] = n23;
  1935. te[2] = n31; te[5] = n32; te[8] = n33;
  1936. return this;
  1937. },
  1938. identity: function () {
  1939. this.set(
  1940. 1, 0, 0,
  1941. 0, 1, 0,
  1942. 0, 0, 1
  1943. );
  1944. return this;
  1945. },
  1946. copy: function ( m ) {
  1947. var me = m.elements;
  1948. this.set(
  1949. me[0], me[3], me[6],
  1950. me[1], me[4], me[7],
  1951. me[2], me[5], me[8]
  1952. );
  1953. return this;
  1954. },
  1955. multiplyVector3: function ( vector ) {
  1956. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  1957. return vector.applyMatrix3( this );
  1958. },
  1959. multiplyVector3Array: function() {
  1960. var v1 = new THREE.Vector3();
  1961. return function ( a ) {
  1962. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1963. v1.x = a[ i ];
  1964. v1.y = a[ i + 1 ];
  1965. v1.z = a[ i + 2 ];
  1966. v1.applyMatrix3(this);
  1967. a[ i ] = v1.x;
  1968. a[ i + 1 ] = v1.y;
  1969. a[ i + 2 ] = v1.z;
  1970. }
  1971. return a;
  1972. };
  1973. }(),
  1974. multiplyScalar: function ( s ) {
  1975. var te = this.elements;
  1976. te[0] *= s; te[3] *= s; te[6] *= s;
  1977. te[1] *= s; te[4] *= s; te[7] *= s;
  1978. te[2] *= s; te[5] *= s; te[8] *= s;
  1979. return this;
  1980. },
  1981. determinant: function () {
  1982. var te = this.elements;
  1983. var a = te[0], b = te[1], c = te[2],
  1984. d = te[3], e = te[4], f = te[5],
  1985. g = te[6], h = te[7], i = te[8];
  1986. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  1987. },
  1988. getInverse: function ( matrix, throwOnInvertible ) {
  1989. // input: THREE.Matrix4
  1990. // ( based on http://code.google.com/p/webgl-mjs/ )
  1991. var me = matrix.elements;
  1992. var te = this.elements;
  1993. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  1994. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  1995. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  1996. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  1997. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  1998. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  1999. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2000. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2001. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2002. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2003. // no inverse
  2004. if ( det === 0 ) {
  2005. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2006. if ( throwOnInvertible || false ) {
  2007. throw new Error( msg );
  2008. } else {
  2009. console.warn( msg );
  2010. }
  2011. this.identity();
  2012. return this;
  2013. }
  2014. this.multiplyScalar( 1.0 / det );
  2015. return this;
  2016. },
  2017. transpose: function () {
  2018. var tmp, m = this.elements;
  2019. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2020. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2021. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2022. return this;
  2023. },
  2024. getNormalMatrix: function ( m ) {
  2025. // input: THREE.Matrix4
  2026. this.getInverse( m ).transpose();
  2027. return this;
  2028. },
  2029. transposeIntoArray: function ( r ) {
  2030. var m = this.elements;
  2031. r[ 0 ] = m[ 0 ];
  2032. r[ 1 ] = m[ 3 ];
  2033. r[ 2 ] = m[ 6 ];
  2034. r[ 3 ] = m[ 1 ];
  2035. r[ 4 ] = m[ 4 ];
  2036. r[ 5 ] = m[ 7 ];
  2037. r[ 6 ] = m[ 2 ];
  2038. r[ 7 ] = m[ 5 ];
  2039. r[ 8 ] = m[ 8 ];
  2040. return this;
  2041. },
  2042. clone: function () {
  2043. var te = this.elements;
  2044. return new THREE.Matrix3(
  2045. te[0], te[3], te[6],
  2046. te[1], te[4], te[7],
  2047. te[2], te[5], te[8]
  2048. );
  2049. }
  2050. } );
  2051. /**
  2052. * @author mrdoob / http://mrdoob.com/
  2053. * @author supereggbert / http://www.paulbrunt.co.uk/
  2054. * @author philogb / http://blog.thejit.org/
  2055. * @author jordi_ros / http://plattsoft.com
  2056. * @author D1plo1d / http://github.com/D1plo1d
  2057. * @author alteredq / http://alteredqualia.com/
  2058. * @author mikael emtinger / http://gomo.se/
  2059. * @author timknip / http://www.floorplanner.com/
  2060. * @author bhouston / http://exocortex.com
  2061. * @author WestLangley / http://github.com/WestLangley
  2062. */
  2063. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2064. var te = this.elements = new Float32Array( 16 );
  2065. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2066. // we should not support semi specification of Matrix4, it is just weird.
  2067. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2068. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2069. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2070. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2071. };
  2072. THREE.extend( THREE.Matrix4.prototype, {
  2073. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2074. var te = this.elements;
  2075. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2076. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2077. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2078. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2079. return this;
  2080. },
  2081. identity: function () {
  2082. this.set(
  2083. 1, 0, 0, 0,
  2084. 0, 1, 0, 0,
  2085. 0, 0, 1, 0,
  2086. 0, 0, 0, 1
  2087. );
  2088. return this;
  2089. },
  2090. copy: function ( m ) {
  2091. var me = m.elements;
  2092. this.set(
  2093. me[0], me[4], me[8], me[12],
  2094. me[1], me[5], me[9], me[13],
  2095. me[2], me[6], me[10], me[14],
  2096. me[3], me[7], me[11], me[15]
  2097. );
  2098. return this;
  2099. },
  2100. setRotationFromEuler: function ( v, order ) {
  2101. var te = this.elements;
  2102. var x = v.x, y = v.y, z = v.z;
  2103. var a = Math.cos( x ), b = Math.sin( x );
  2104. var c = Math.cos( y ), d = Math.sin( y );
  2105. var e = Math.cos( z ), f = Math.sin( z );
  2106. if ( order === undefined || order === 'XYZ' ) {
  2107. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2108. te[0] = c * e;
  2109. te[4] = - c * f;
  2110. te[8] = d;
  2111. te[1] = af + be * d;
  2112. te[5] = ae - bf * d;
  2113. te[9] = - b * c;
  2114. te[2] = bf - ae * d;
  2115. te[6] = be + af * d;
  2116. te[10] = a * c;
  2117. } else if ( order === 'YXZ' ) {
  2118. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2119. te[0] = ce + df * b;
  2120. te[4] = de * b - cf;
  2121. te[8] = a * d;
  2122. te[1] = a * f;
  2123. te[5] = a * e;
  2124. te[9] = - b;
  2125. te[2] = cf * b - de;
  2126. te[6] = df + ce * b;
  2127. te[10] = a * c;
  2128. } else if ( order === 'ZXY' ) {
  2129. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2130. te[0] = ce - df * b;
  2131. te[4] = - a * f;
  2132. te[8] = de + cf * b;
  2133. te[1] = cf + de * b;
  2134. te[5] = a * e;
  2135. te[9] = df - ce * b;
  2136. te[2] = - a * d;
  2137. te[6] = b;
  2138. te[10] = a * c;
  2139. } else if ( order === 'ZYX' ) {
  2140. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2141. te[0] = c * e;
  2142. te[4] = be * d - af;
  2143. te[8] = ae * d + bf;
  2144. te[1] = c * f;
  2145. te[5] = bf * d + ae;
  2146. te[9] = af * d - be;
  2147. te[2] = - d;
  2148. te[6] = b * c;
  2149. te[10] = a * c;
  2150. } else if ( order === 'YZX' ) {
  2151. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2152. te[0] = c * e;
  2153. te[4] = bd - ac * f;
  2154. te[8] = bc * f + ad;
  2155. te[1] = f;
  2156. te[5] = a * e;
  2157. te[9] = - b * e;
  2158. te[2] = - d * e;
  2159. te[6] = ad * f + bc;
  2160. te[10] = ac - bd * f;
  2161. } else if ( order === 'XZY' ) {
  2162. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2163. te[0] = c * e;
  2164. te[4] = - f;
  2165. te[8] = d * e;
  2166. te[1] = ac * f + bd;
  2167. te[5] = a * e;
  2168. te[9] = ad * f - bc;
  2169. te[2] = bc * f - ad;
  2170. te[6] = b * e;
  2171. te[10] = bd * f + ac;
  2172. }
  2173. return this;
  2174. },
  2175. setRotationFromQuaternion: function ( q ) {
  2176. var te = this.elements;
  2177. var x = q.x, y = q.y, z = q.z, w = q.w;
  2178. var x2 = x + x, y2 = y + y, z2 = z + z;
  2179. var xx = x * x2, xy = x * y2, xz = x * z2;
  2180. var yy = y * y2, yz = y * z2, zz = z * z2;
  2181. var wx = w * x2, wy = w * y2, wz = w * z2;
  2182. te[0] = 1 - ( yy + zz );
  2183. te[4] = xy - wz;
  2184. te[8] = xz + wy;
  2185. te[1] = xy + wz;
  2186. te[5] = 1 - ( xx + zz );
  2187. te[9] = yz - wx;
  2188. te[2] = xz - wy;
  2189. te[6] = yz + wx;
  2190. te[10] = 1 - ( xx + yy );
  2191. return this;
  2192. },
  2193. lookAt: function() {
  2194. var x = new THREE.Vector3();
  2195. var y = new THREE.Vector3();
  2196. var z = new THREE.Vector3();
  2197. return function ( eye, target, up ) {
  2198. var te = this.elements;
  2199. z.subVectors( eye, target ).normalize();
  2200. if ( z.length() === 0 ) {
  2201. z.z = 1;
  2202. }
  2203. x.crossVectors( up, z ).normalize();
  2204. if ( x.length() === 0 ) {
  2205. z.x += 0.0001;
  2206. x.crossVectors( up, z ).normalize();
  2207. }
  2208. y.crossVectors( z, x );
  2209. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2210. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2211. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2212. return this;
  2213. };
  2214. }(),
  2215. multiply: function ( m, n ) {
  2216. if ( n !== undefined ) {
  2217. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2218. return this.multiplyMatrices( m, n );
  2219. }
  2220. return this.multiplyMatrices( this, m );
  2221. },
  2222. multiplyMatrices: function ( a, b ) {
  2223. var ae = a.elements;
  2224. var be = b.elements;
  2225. var te = this.elements;
  2226. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2227. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2228. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2229. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2230. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2231. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2232. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2233. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2234. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2235. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2236. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2237. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2238. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2239. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2240. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2241. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2242. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2243. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2244. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2245. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2246. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2247. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2248. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2249. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2250. return this;
  2251. },
  2252. multiplyToArray: function ( a, b, r ) {
  2253. var te = this.elements;
  2254. this.multiplyMatrices( a, b );
  2255. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2256. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2257. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2258. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2259. return this;
  2260. },
  2261. multiplyScalar: function ( s ) {
  2262. var te = this.elements;
  2263. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2264. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2265. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2266. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2267. return this;
  2268. },
  2269. multiplyVector3: function ( vector ) {
  2270. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2271. return vector.applyProjection( this );
  2272. },
  2273. multiplyVector4: function ( vector ) {
  2274. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2275. return vector.applyMatrix4( this );
  2276. },
  2277. multiplyVector3Array: function() {
  2278. var v1 = new THREE.Vector3();
  2279. return function ( a ) {
  2280. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2281. v1.x = a[ i ];
  2282. v1.y = a[ i + 1 ];
  2283. v1.z = a[ i + 2 ];
  2284. v1.applyProjection( this );
  2285. a[ i ] = v1.x;
  2286. a[ i + 1 ] = v1.y;
  2287. a[ i + 2 ] = v1.z;
  2288. }
  2289. return a;
  2290. };
  2291. }(),
  2292. rotateAxis: function ( v ) {
  2293. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2294. v.transformDirection( this );
  2295. },
  2296. crossVector: function ( a ) {
  2297. var te = this.elements;
  2298. var v = new THREE.Vector4();
  2299. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  2300. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  2301. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  2302. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  2303. return v;
  2304. },
  2305. determinant: function () {
  2306. var te = this.elements;
  2307. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2308. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2309. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2310. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2311. //TODO: make this more efficient
  2312. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2313. return (
  2314. n41 * (
  2315. +n14 * n23 * n32
  2316. -n13 * n24 * n32
  2317. -n14 * n22 * n33
  2318. +n12 * n24 * n33
  2319. +n13 * n22 * n34
  2320. -n12 * n23 * n34
  2321. ) +
  2322. n42 * (
  2323. +n11 * n23 * n34
  2324. -n11 * n24 * n33
  2325. +n14 * n21 * n33
  2326. -n13 * n21 * n34
  2327. +n13 * n24 * n31
  2328. -n14 * n23 * n31
  2329. ) +
  2330. n43 * (
  2331. +n11 * n24 * n32
  2332. -n11 * n22 * n34
  2333. -n14 * n21 * n32
  2334. +n12 * n21 * n34
  2335. +n14 * n22 * n31
  2336. -n12 * n24 * n31
  2337. ) +
  2338. n44 * (
  2339. -n13 * n22 * n31
  2340. -n11 * n23 * n32
  2341. +n11 * n22 * n33
  2342. +n13 * n21 * n32
  2343. -n12 * n21 * n33
  2344. +n12 * n23 * n31
  2345. )
  2346. );
  2347. },
  2348. transpose: function () {
  2349. var te = this.elements;
  2350. var tmp;
  2351. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2352. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2353. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2354. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2355. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2356. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2357. return this;
  2358. },
  2359. flattenToArray: function ( flat ) {
  2360. var te = this.elements;
  2361. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2362. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2363. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2364. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2365. return flat;
  2366. },
  2367. flattenToArrayOffset: function( flat, offset ) {
  2368. var te = this.elements;
  2369. flat[ offset ] = te[0];
  2370. flat[ offset + 1 ] = te[1];
  2371. flat[ offset + 2 ] = te[2];
  2372. flat[ offset + 3 ] = te[3];
  2373. flat[ offset + 4 ] = te[4];
  2374. flat[ offset + 5 ] = te[5];
  2375. flat[ offset + 6 ] = te[6];
  2376. flat[ offset + 7 ] = te[7];
  2377. flat[ offset + 8 ] = te[8];
  2378. flat[ offset + 9 ] = te[9];
  2379. flat[ offset + 10 ] = te[10];
  2380. flat[ offset + 11 ] = te[11];
  2381. flat[ offset + 12 ] = te[12];
  2382. flat[ offset + 13 ] = te[13];
  2383. flat[ offset + 14 ] = te[14];
  2384. flat[ offset + 15 ] = te[15];
  2385. return flat;
  2386. },
  2387. getPosition: function() {
  2388. var v1 = new THREE.Vector3();
  2389. return function () {
  2390. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.getPositionFromMatrix( matrix ) instead.' );
  2391. var te = this.elements;
  2392. return v1.set( te[12], te[13], te[14] );
  2393. };
  2394. }(),
  2395. setPosition: function ( v ) {
  2396. var te = this.elements;
  2397. te[12] = v.x;
  2398. te[13] = v.y;
  2399. te[14] = v.z;
  2400. return this;
  2401. },
  2402. getInverse: function ( m, throwOnInvertible ) {
  2403. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2404. var te = this.elements;
  2405. var me = m.elements;
  2406. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2407. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2408. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2409. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2410. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2411. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2412. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2413. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2414. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2415. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2416. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2417. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2418. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2419. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2420. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2421. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2422. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2423. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2424. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2425. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2426. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 4 ] + me[ 2 ] * te[ 8 ] + me[ 3 ] * te[ 12 ];
  2427. if ( det == 0 ) {
  2428. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2429. if ( throwOnInvertible || false ) {
  2430. throw new Error( msg );
  2431. } else {
  2432. console.warn( msg );
  2433. }
  2434. this.identity();
  2435. return this;
  2436. }
  2437. this.multiplyScalar( 1 / det );
  2438. return this;
  2439. },
  2440. compose: function() {
  2441. var mRotation = new THREE.Matrix4();
  2442. var mScale = new THREE.Matrix4();
  2443. return function ( position, quaternion, scale ) {
  2444. var te = this.elements;
  2445. mRotation.identity();
  2446. mRotation.setRotationFromQuaternion( quaternion );
  2447. mScale.makeScale( scale.x, scale.y, scale.z );
  2448. this.multiplyMatrices( mRotation, mScale );
  2449. te[12] = position.x;
  2450. te[13] = position.y;
  2451. te[14] = position.z;
  2452. return this;
  2453. };
  2454. }(),
  2455. decompose: function() {
  2456. var x = new THREE.Vector3(),
  2457. y = new THREE.Vector3(),
  2458. z = new THREE.Vector3(),
  2459. matrix = new THREE.Matrix4();
  2460. return function ( position, quaternion, scale ) {
  2461. var te = this.elements;
  2462. // grab the axis vectors
  2463. x.set( te[0], te[1], te[2] );
  2464. y.set( te[4], te[5], te[6] );
  2465. z.set( te[8], te[9], te[10] );
  2466. position = ( position instanceof THREE.Vector3 ) ? position : new THREE.Vector3();
  2467. quaternion = ( quaternion instanceof THREE.Quaternion ) ? quaternion : new THREE.Quaternion();
  2468. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  2469. scale.x = x.length();
  2470. scale.y = y.length();
  2471. scale.z = z.length();
  2472. position.x = te[12];
  2473. position.y = te[13];
  2474. position.z = te[14];
  2475. // scale the rotation part
  2476. matrix.copy( this );
  2477. matrix.elements[0] /= scale.x;
  2478. matrix.elements[1] /= scale.x;
  2479. matrix.elements[2] /= scale.x;
  2480. matrix.elements[4] /= scale.y;
  2481. matrix.elements[5] /= scale.y;
  2482. matrix.elements[6] /= scale.y;
  2483. matrix.elements[8] /= scale.z;
  2484. matrix.elements[9] /= scale.z;
  2485. matrix.elements[10] /= scale.z;
  2486. quaternion.setFromRotationMatrix( matrix );
  2487. return [ position, quaternion, scale ];
  2488. };
  2489. }(),
  2490. extractPosition: function ( m ) {
  2491. var te = this.elements;
  2492. var me = m.elements;
  2493. te[12] = me[12];
  2494. te[13] = me[13];
  2495. te[14] = me[14];
  2496. return this;
  2497. },
  2498. extractRotation: function() {
  2499. var v1 = new THREE.Vector3();
  2500. return function ( m ) {
  2501. var te = this.elements;
  2502. var me = m.elements;
  2503. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2504. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2505. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2506. te[0] = me[0] * scaleX;
  2507. te[1] = me[1] * scaleX;
  2508. te[2] = me[2] * scaleX;
  2509. te[4] = me[4] * scaleY;
  2510. te[5] = me[5] * scaleY;
  2511. te[6] = me[6] * scaleY;
  2512. te[8] = me[8] * scaleZ;
  2513. te[9] = me[9] * scaleZ;
  2514. te[10] = me[10] * scaleZ;
  2515. return this;
  2516. };
  2517. }(),
  2518. translate: function ( v ) {
  2519. var te = this.elements;
  2520. var x = v.x, y = v.y, z = v.z;
  2521. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  2522. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  2523. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  2524. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  2525. return this;
  2526. },
  2527. rotateX: function ( angle ) {
  2528. var te = this.elements;
  2529. var m12 = te[4];
  2530. var m22 = te[5];
  2531. var m32 = te[6];
  2532. var m42 = te[7];
  2533. var m13 = te[8];
  2534. var m23 = te[9];
  2535. var m33 = te[10];
  2536. var m43 = te[11];
  2537. var c = Math.cos( angle );
  2538. var s = Math.sin( angle );
  2539. te[4] = c * m12 + s * m13;
  2540. te[5] = c * m22 + s * m23;
  2541. te[6] = c * m32 + s * m33;
  2542. te[7] = c * m42 + s * m43;
  2543. te[8] = c * m13 - s * m12;
  2544. te[9] = c * m23 - s * m22;
  2545. te[10] = c * m33 - s * m32;
  2546. te[11] = c * m43 - s * m42;
  2547. return this;
  2548. },
  2549. rotateY: function ( angle ) {
  2550. var te = this.elements;
  2551. var m11 = te[0];
  2552. var m21 = te[1];
  2553. var m31 = te[2];
  2554. var m41 = te[3];
  2555. var m13 = te[8];
  2556. var m23 = te[9];
  2557. var m33 = te[10];
  2558. var m43 = te[11];
  2559. var c = Math.cos( angle );
  2560. var s = Math.sin( angle );
  2561. te[0] = c * m11 - s * m13;
  2562. te[1] = c * m21 - s * m23;
  2563. te[2] = c * m31 - s * m33;
  2564. te[3] = c * m41 - s * m43;
  2565. te[8] = c * m13 + s * m11;
  2566. te[9] = c * m23 + s * m21;
  2567. te[10] = c * m33 + s * m31;
  2568. te[11] = c * m43 + s * m41;
  2569. return this;
  2570. },
  2571. rotateZ: function ( angle ) {
  2572. var te = this.elements;
  2573. var m11 = te[0];
  2574. var m21 = te[1];
  2575. var m31 = te[2];
  2576. var m41 = te[3];
  2577. var m12 = te[4];
  2578. var m22 = te[5];
  2579. var m32 = te[6];
  2580. var m42 = te[7];
  2581. var c = Math.cos( angle );
  2582. var s = Math.sin( angle );
  2583. te[0] = c * m11 + s * m12;
  2584. te[1] = c * m21 + s * m22;
  2585. te[2] = c * m31 + s * m32;
  2586. te[3] = c * m41 + s * m42;
  2587. te[4] = c * m12 - s * m11;
  2588. te[5] = c * m22 - s * m21;
  2589. te[6] = c * m32 - s * m31;
  2590. te[7] = c * m42 - s * m41;
  2591. return this;
  2592. },
  2593. rotateByAxis: function ( axis, angle ) {
  2594. var te = this.elements;
  2595. // optimize by checking axis
  2596. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  2597. return this.rotateX( angle );
  2598. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  2599. return this.rotateY( angle );
  2600. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  2601. return this.rotateZ( angle );
  2602. }
  2603. var x = axis.x, y = axis.y, z = axis.z;
  2604. var n = Math.sqrt(x * x + y * y + z * z);
  2605. x /= n;
  2606. y /= n;
  2607. z /= n;
  2608. var xx = x * x, yy = y * y, zz = z * z;
  2609. var c = Math.cos( angle );
  2610. var s = Math.sin( angle );
  2611. var oneMinusCosine = 1 - c;
  2612. var xy = x * y * oneMinusCosine;
  2613. var xz = x * z * oneMinusCosine;
  2614. var yz = y * z * oneMinusCosine;
  2615. var xs = x * s;
  2616. var ys = y * s;
  2617. var zs = z * s;
  2618. var r11 = xx + (1 - xx) * c;
  2619. var r21 = xy + zs;
  2620. var r31 = xz - ys;
  2621. var r12 = xy - zs;
  2622. var r22 = yy + (1 - yy) * c;
  2623. var r32 = yz + xs;
  2624. var r13 = xz + ys;
  2625. var r23 = yz - xs;
  2626. var r33 = zz + (1 - zz) * c;
  2627. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  2628. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  2629. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  2630. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  2631. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  2632. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  2633. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  2634. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  2635. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  2636. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  2637. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  2638. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  2639. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  2640. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  2641. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  2642. return this;
  2643. },
  2644. scale: function ( v ) {
  2645. var te = this.elements;
  2646. var x = v.x, y = v.y, z = v.z;
  2647. te[0] *= x; te[4] *= y; te[8] *= z;
  2648. te[1] *= x; te[5] *= y; te[9] *= z;
  2649. te[2] *= x; te[6] *= y; te[10] *= z;
  2650. te[3] *= x; te[7] *= y; te[11] *= z;
  2651. return this;
  2652. },
  2653. getMaxScaleOnAxis: function () {
  2654. var te = this.elements;
  2655. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2656. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2657. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2658. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2659. },
  2660. makeTranslation: function ( x, y, z ) {
  2661. this.set(
  2662. 1, 0, 0, x,
  2663. 0, 1, 0, y,
  2664. 0, 0, 1, z,
  2665. 0, 0, 0, 1
  2666. );
  2667. return this;
  2668. },
  2669. makeRotationX: function ( theta ) {
  2670. var c = Math.cos( theta ), s = Math.sin( theta );
  2671. this.set(
  2672. 1, 0, 0, 0,
  2673. 0, c, -s, 0,
  2674. 0, s, c, 0,
  2675. 0, 0, 0, 1
  2676. );
  2677. return this;
  2678. },
  2679. makeRotationY: function ( theta ) {
  2680. var c = Math.cos( theta ), s = Math.sin( theta );
  2681. this.set(
  2682. c, 0, s, 0,
  2683. 0, 1, 0, 0,
  2684. -s, 0, c, 0,
  2685. 0, 0, 0, 1
  2686. );
  2687. return this;
  2688. },
  2689. makeRotationZ: function ( theta ) {
  2690. var c = Math.cos( theta ), s = Math.sin( theta );
  2691. this.set(
  2692. c, -s, 0, 0,
  2693. s, c, 0, 0,
  2694. 0, 0, 1, 0,
  2695. 0, 0, 0, 1
  2696. );
  2697. return this;
  2698. },
  2699. makeRotationAxis: function ( axis, angle ) {
  2700. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2701. var c = Math.cos( angle );
  2702. var s = Math.sin( angle );
  2703. var t = 1 - c;
  2704. var x = axis.x, y = axis.y, z = axis.z;
  2705. var tx = t * x, ty = t * y;
  2706. this.set(
  2707. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2708. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2709. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2710. 0, 0, 0, 1
  2711. );
  2712. return this;
  2713. },
  2714. makeScale: function ( x, y, z ) {
  2715. this.set(
  2716. x, 0, 0, 0,
  2717. 0, y, 0, 0,
  2718. 0, 0, z, 0,
  2719. 0, 0, 0, 1
  2720. );
  2721. return this;
  2722. },
  2723. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2724. var te = this.elements;
  2725. var x = 2 * near / ( right - left );
  2726. var y = 2 * near / ( top - bottom );
  2727. var a = ( right + left ) / ( right - left );
  2728. var b = ( top + bottom ) / ( top - bottom );
  2729. var c = - ( far + near ) / ( far - near );
  2730. var d = - 2 * far * near / ( far - near );
  2731. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2732. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2733. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2734. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2735. return this;
  2736. },
  2737. makePerspective: function ( fov, aspect, near, far ) {
  2738. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2739. var ymin = - ymax;
  2740. var xmin = ymin * aspect;
  2741. var xmax = ymax * aspect;
  2742. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2743. },
  2744. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2745. var te = this.elements;
  2746. var w = right - left;
  2747. var h = top - bottom;
  2748. var p = far - near;
  2749. var x = ( right + left ) / w;
  2750. var y = ( top + bottom ) / h;
  2751. var z = ( far + near ) / p;
  2752. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2753. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2754. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2755. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2756. return this;
  2757. },
  2758. clone: function () {
  2759. var te = this.elements;
  2760. return new THREE.Matrix4(
  2761. te[0], te[4], te[8], te[12],
  2762. te[1], te[5], te[9], te[13],
  2763. te[2], te[6], te[10], te[14],
  2764. te[3], te[7], te[11], te[15]
  2765. );
  2766. }
  2767. } );
  2768. /**
  2769. * @author bhouston / http://exocortex.com
  2770. */
  2771. THREE.Ray = function ( origin, direction ) {
  2772. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  2773. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  2774. };
  2775. THREE.extend( THREE.Ray.prototype, {
  2776. set: function ( origin, direction ) {
  2777. this.origin.copy( origin );
  2778. this.direction.copy( direction );
  2779. return this;
  2780. },
  2781. copy: function ( ray ) {
  2782. this.origin.copy( ray.origin );
  2783. this.direction.copy( ray.direction );
  2784. return this;
  2785. },
  2786. at: function( t, optionalTarget ) {
  2787. var result = optionalTarget || new THREE.Vector3();
  2788. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2789. },
  2790. recast: function() {
  2791. var v1 = new THREE.Vector3();
  2792. return function ( t ) {
  2793. this.origin.copy( this.at( t, v1 ) );
  2794. return this;
  2795. };
  2796. }(),
  2797. closestPointToPoint: function ( point, optionalTarget ) {
  2798. var result = optionalTarget || new THREE.Vector3();
  2799. result.subVectors( point, this.origin );
  2800. var directionDistance = result.dot( this.direction );
  2801. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2802. },
  2803. distanceToPoint: function() {
  2804. var v1 = new THREE.Vector3();
  2805. return function ( point ) {
  2806. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  2807. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2808. return v1.distanceTo( point );
  2809. };
  2810. }(),
  2811. isIntersectionSphere: function( sphere ) {
  2812. return ( this.distanceToPoint( sphere.center ) <= sphere.radius );
  2813. },
  2814. isIntersectionPlane: function ( plane ) {
  2815. // check if the line and plane are non-perpendicular, if they
  2816. // eventually they will intersect.
  2817. var denominator = plane.normal.dot( this.direction );
  2818. if ( denominator != 0 ) {
  2819. return true;
  2820. }
  2821. // line is coplanar, return origin
  2822. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2823. return true;
  2824. }
  2825. return false;
  2826. },
  2827. distanceToPlane: function ( plane ) {
  2828. var denominator = plane.normal.dot( this.direction );
  2829. if ( denominator == 0 ) {
  2830. // line is coplanar, return origin
  2831. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2832. return 0;
  2833. }
  2834. // Unsure if this is the correct method to handle this case.
  2835. return undefined;
  2836. }
  2837. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  2838. return t;
  2839. },
  2840. intersectPlane: function ( plane, optionalTarget ) {
  2841. var t = this.distanceToPlane( plane );
  2842. if ( t === undefined ) {
  2843. return undefined;
  2844. }
  2845. return this.at( t, optionalTarget );
  2846. },
  2847. applyMatrix4: function ( matrix4 ) {
  2848. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  2849. this.origin.applyMatrix4( matrix4 );
  2850. this.direction.sub( this.origin );
  2851. return this;
  2852. },
  2853. equals: function ( ray ) {
  2854. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  2855. },
  2856. clone: function () {
  2857. return new THREE.Ray().copy( this );
  2858. }
  2859. } );
  2860. /**
  2861. * @author bhouston / http://exocortex.com
  2862. * @author mrdoob / http://mrdoob.com/
  2863. */
  2864. THREE.Sphere = function ( center, radius ) {
  2865. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  2866. this.radius = ( radius !== undefined ) ? radius : 0;
  2867. };
  2868. THREE.extend( THREE.Sphere.prototype, {
  2869. set: function ( center, radius ) {
  2870. this.center.copy( center );
  2871. this.radius = radius;
  2872. return this;
  2873. },
  2874. setFromCenterAndPoints: function ( center, points ) {
  2875. var maxRadiusSq = 0;
  2876. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2877. var radiusSq = center.distanceToSquared( points[ i ] );
  2878. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  2879. }
  2880. this.center = center;
  2881. this.radius = Math.sqrt( maxRadiusSq );
  2882. return this;
  2883. },
  2884. copy: function ( sphere ) {
  2885. this.center.copy( sphere.center );
  2886. this.radius = sphere.radius;
  2887. return this;
  2888. },
  2889. empty: function () {
  2890. return ( this.radius <= 0 );
  2891. },
  2892. containsPoint: function ( point ) {
  2893. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2894. },
  2895. distanceToPoint: function ( point ) {
  2896. return ( point.distanceTo( this.center ) - this.radius );
  2897. },
  2898. intersectsSphere: function ( sphere ) {
  2899. var radiusSum = this.radius + sphere.radius;
  2900. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  2901. },
  2902. clampPoint: function ( point, optionalTarget ) {
  2903. var deltaLengthSq = this.center.distanceToSquared( point );
  2904. var result = optionalTarget || new THREE.Vector3();
  2905. result.copy( point );
  2906. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2907. result.sub( this.center ).normalize();
  2908. result.multiplyScalar( this.radius ).add( this.center );
  2909. }
  2910. return result;
  2911. },
  2912. getBoundingBox: function ( optionalTarget ) {
  2913. var box = optionalTarget || new THREE.Box3();
  2914. box.set( this.center, this.center );
  2915. box.expandByScalar( this.radius );
  2916. return box;
  2917. },
  2918. applyMatrix4: function ( matrix ) {
  2919. this.center.applyMatrix4( matrix );
  2920. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2921. return this;
  2922. },
  2923. translate: function ( offset ) {
  2924. this.center.add( offset );
  2925. return this;
  2926. },
  2927. equals: function ( sphere ) {
  2928. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2929. },
  2930. clone: function () {
  2931. return new THREE.Sphere().copy( this );
  2932. }
  2933. } );
  2934. /**
  2935. * @author mrdoob / http://mrdoob.com/
  2936. * @author alteredq / http://alteredqualia.com/
  2937. * @author bhouston / http://exocortex.com
  2938. */
  2939. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  2940. this.planes = [
  2941. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  2942. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  2943. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  2944. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  2945. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  2946. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  2947. ];
  2948. };
  2949. THREE.extend( THREE.Frustum.prototype, {
  2950. set: function ( p0, p1, p2, p3, p4, p5 ) {
  2951. var planes = this.planes;
  2952. planes[0].copy( p0 );
  2953. planes[1].copy( p1 );
  2954. planes[2].copy( p2 );
  2955. planes[3].copy( p3 );
  2956. planes[4].copy( p4 );
  2957. planes[5].copy( p5 );
  2958. return this;
  2959. },
  2960. copy: function ( frustum ) {
  2961. var planes = this.planes;
  2962. for( var i = 0; i < 6; i ++ ) {
  2963. planes[i].copy( frustum.planes[i] );
  2964. }
  2965. return this;
  2966. },
  2967. setFromMatrix: function ( m ) {
  2968. var planes = this.planes;
  2969. var me = m.elements;
  2970. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  2971. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  2972. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  2973. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  2974. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  2975. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  2976. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  2977. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  2978. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  2979. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  2980. return this;
  2981. },
  2982. intersectsObject: function () {
  2983. var center = new THREE.Vector3();
  2984. return function ( object ) {
  2985. // this method is expanded inlined for performance reasons.
  2986. var matrix = object.matrixWorld;
  2987. var planes = this.planes;
  2988. var negRadius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  2989. center.getPositionFromMatrix( matrix );
  2990. for ( var i = 0; i < 6; i ++ ) {
  2991. var distance = planes[ i ].distanceToPoint( center );
  2992. if ( distance < negRadius ) {
  2993. return false;
  2994. }
  2995. }
  2996. return true;
  2997. };
  2998. }(),
  2999. intersectsSphere: function ( sphere ) {
  3000. var planes = this.planes;
  3001. var center = sphere.center;
  3002. var negRadius = -sphere.radius;
  3003. for ( var i = 0; i < 6; i ++ ) {
  3004. var distance = planes[ i ].distanceToPoint( center );
  3005. if ( distance < negRadius ) {
  3006. return false;
  3007. }
  3008. }
  3009. return true;
  3010. },
  3011. containsPoint: function ( point ) {
  3012. var planes = this.planes;
  3013. for ( var i = 0; i < 6; i ++ ) {
  3014. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3015. return false;
  3016. }
  3017. }
  3018. return true;
  3019. },
  3020. clone: function () {
  3021. return new THREE.Frustum().copy( this );
  3022. }
  3023. } );
  3024. /**
  3025. * @author bhouston / http://exocortex.com
  3026. */
  3027. THREE.Plane = function ( normal, constant ) {
  3028. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3029. this.constant = ( constant !== undefined ) ? constant : 0;
  3030. };
  3031. THREE.extend( THREE.Plane.prototype, {
  3032. set: function ( normal, constant ) {
  3033. this.normal.copy( normal );
  3034. this.constant = constant;
  3035. return this;
  3036. },
  3037. setComponents: function ( x, y, z, w ) {
  3038. this.normal.set( x, y, z );
  3039. this.constant = w;
  3040. return this;
  3041. },
  3042. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3043. this.normal.copy( normal );
  3044. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3045. return this;
  3046. },
  3047. setFromCoplanarPoints: function() {
  3048. var v1 = new THREE.Vector3();
  3049. var v2 = new THREE.Vector3();
  3050. return function ( a, b, c ) {
  3051. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3052. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3053. this.setFromNormalAndCoplanarPoint( normal, a );
  3054. return this;
  3055. };
  3056. }(),
  3057. copy: function ( plane ) {
  3058. this.normal.copy( plane.normal );
  3059. this.constant = plane.constant;
  3060. return this;
  3061. },
  3062. normalize: function () {
  3063. // Note: will lead to a divide by zero if the plane is invalid.
  3064. var inverseNormalLength = 1.0 / this.normal.length();
  3065. this.normal.multiplyScalar( inverseNormalLength );
  3066. this.constant *= inverseNormalLength;
  3067. return this;
  3068. },
  3069. negate: function () {
  3070. this.constant *= -1;
  3071. this.normal.negate();
  3072. return this;
  3073. },
  3074. distanceToPoint: function ( point ) {
  3075. return this.normal.dot( point ) + this.constant;
  3076. },
  3077. distanceToSphere: function ( sphere ) {
  3078. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3079. },
  3080. projectPoint: function ( point, optionalTarget ) {
  3081. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3082. },
  3083. orthoPoint: function ( point, optionalTarget ) {
  3084. var perpendicularMagnitude = this.distanceToPoint( point );
  3085. var result = optionalTarget || new THREE.Vector3();
  3086. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3087. },
  3088. isIntersectionLine: function ( line ) {
  3089. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3090. var startSign = this.distanceToPoint( line.start );
  3091. var endSign = this.distanceToPoint( line.end );
  3092. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3093. },
  3094. intersectLine: function() {
  3095. var v1 = new THREE.Vector3();
  3096. return function ( line, optionalTarget ) {
  3097. var result = optionalTarget || new THREE.Vector3();
  3098. var direction = line.delta( v1 );
  3099. var denominator = this.normal.dot( direction );
  3100. if ( denominator == 0 ) {
  3101. // line is coplanar, return origin
  3102. if( this.distanceToPoint( line.start ) == 0 ) {
  3103. return result.copy( line.start );
  3104. }
  3105. // Unsure if this is the correct method to handle this case.
  3106. return undefined;
  3107. }
  3108. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3109. if( t < 0 || t > 1 ) {
  3110. return undefined;
  3111. }
  3112. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3113. };
  3114. }(),
  3115. coplanarPoint: function ( optionalTarget ) {
  3116. var result = optionalTarget || new THREE.Vector3();
  3117. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3118. },
  3119. applyMatrix4: function() {
  3120. var v1 = new THREE.Vector3();
  3121. var v2 = new THREE.Vector3();
  3122. return function ( matrix, optionalNormalMatrix ) {
  3123. // compute new normal based on theory here:
  3124. // http://www.songho.ca/opengl/gl_normaltransform.html
  3125. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getInverse( matrix ).transpose();
  3126. var newNormal = v1.copy( this.normal ).applyMatrix3( optionalNormalMatrix );
  3127. var newCoplanarPoint = this.coplanarPoint( v2 );
  3128. newCoplanarPoint.applyMatrix4( matrix );
  3129. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3130. return this;
  3131. };
  3132. }(),
  3133. translate: function ( offset ) {
  3134. this.constant = this.constant - offset.dot( this.normal );
  3135. return this;
  3136. },
  3137. equals: function ( plane ) {
  3138. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3139. },
  3140. clone: function () {
  3141. return new THREE.Plane().copy( this );
  3142. }
  3143. } );
  3144. /**
  3145. * @author alteredq / http://alteredqualia.com/
  3146. */
  3147. THREE.Math = {
  3148. // Clamp value to range <a, b>
  3149. clamp: function ( x, a, b ) {
  3150. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3151. },
  3152. // Clamp value to range <a, inf)
  3153. clampBottom: function ( x, a ) {
  3154. return x < a ? a : x;
  3155. },
  3156. // Linear mapping from range <a1, a2> to range <b1, b2>
  3157. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3158. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3159. },
  3160. // http://en.wikipedia.org/wiki/Smoothstep
  3161. smoothstep: function ( x, min, max ) {
  3162. if ( x <= min ) return 0;
  3163. if ( x >= max ) return 1;
  3164. x = ( x - min )/( max - min );
  3165. return x*x*(3 - 2*x);
  3166. },
  3167. smootherstep: function ( x, min, max ) {
  3168. if ( x <= min ) return 0;
  3169. if ( x >= max ) return 1;
  3170. x = ( x - min )/( max - min );
  3171. return x*x*x*(x*(x*6 - 15) + 10);
  3172. },
  3173. // Random float from <0, 1> with 16 bits of randomness
  3174. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3175. random16: function () {
  3176. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3177. },
  3178. // Random integer from <low, high> interval
  3179. randInt: function ( low, high ) {
  3180. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3181. },
  3182. // Random float from <low, high> interval
  3183. randFloat: function ( low, high ) {
  3184. return low + Math.random() * ( high - low );
  3185. },
  3186. // Random float from <-range/2, range/2> interval
  3187. randFloatSpread: function ( range ) {
  3188. return range * ( 0.5 - Math.random() );
  3189. },
  3190. sign: function ( x ) {
  3191. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  3192. },
  3193. degToRad: function() {
  3194. var degreeToRadiansFactor = Math.PI / 180;
  3195. return function ( degrees ) {
  3196. return degrees * degreeToRadiansFactor;
  3197. };
  3198. }(),
  3199. radToDeg: function() {
  3200. var radianToDegreesFactor = 180 / Math.PI;
  3201. return function ( radians ) {
  3202. return radians * radianToDegreesFactor;
  3203. };
  3204. }()
  3205. };
  3206. /**
  3207. * Spline from Tween.js, slightly optimized (and trashed)
  3208. * http://sole.github.com/tween.js/examples/05_spline.html
  3209. *
  3210. * @author mrdoob / http://mrdoob.com/
  3211. * @author alteredq / http://alteredqualia.com/
  3212. */
  3213. THREE.Spline = function ( points ) {
  3214. this.points = points;
  3215. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3216. point, intPoint, weight, w2, w3,
  3217. pa, pb, pc, pd;
  3218. this.initFromArray = function( a ) {
  3219. this.points = [];
  3220. for ( var i = 0; i < a.length; i++ ) {
  3221. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3222. }
  3223. };
  3224. this.getPoint = function ( k ) {
  3225. point = ( this.points.length - 1 ) * k;
  3226. intPoint = Math.floor( point );
  3227. weight = point - intPoint;
  3228. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3229. c[ 1 ] = intPoint;
  3230. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3231. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3232. pa = this.points[ c[ 0 ] ];
  3233. pb = this.points[ c[ 1 ] ];
  3234. pc = this.points[ c[ 2 ] ];
  3235. pd = this.points[ c[ 3 ] ];
  3236. w2 = weight * weight;
  3237. w3 = weight * w2;
  3238. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3239. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3240. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3241. return v3;
  3242. };
  3243. this.getControlPointsArray = function () {
  3244. var i, p, l = this.points.length,
  3245. coords = [];
  3246. for ( i = 0; i < l; i ++ ) {
  3247. p = this.points[ i ];
  3248. coords[ i ] = [ p.x, p.y, p.z ];
  3249. }
  3250. return coords;
  3251. };
  3252. // approximate length by summing linear segments
  3253. this.getLength = function ( nSubDivisions ) {
  3254. var i, index, nSamples, position,
  3255. point = 0, intPoint = 0, oldIntPoint = 0,
  3256. oldPosition = new THREE.Vector3(),
  3257. tmpVec = new THREE.Vector3(),
  3258. chunkLengths = [],
  3259. totalLength = 0;
  3260. // first point has 0 length
  3261. chunkLengths[ 0 ] = 0;
  3262. if ( !nSubDivisions ) nSubDivisions = 100;
  3263. nSamples = this.points.length * nSubDivisions;
  3264. oldPosition.copy( this.points[ 0 ] );
  3265. for ( i = 1; i < nSamples; i ++ ) {
  3266. index = i / nSamples;
  3267. position = this.getPoint( index );
  3268. tmpVec.copy( position );
  3269. totalLength += tmpVec.distanceTo( oldPosition );
  3270. oldPosition.copy( position );
  3271. point = ( this.points.length - 1 ) * index;
  3272. intPoint = Math.floor( point );
  3273. if ( intPoint != oldIntPoint ) {
  3274. chunkLengths[ intPoint ] = totalLength;
  3275. oldIntPoint = intPoint;
  3276. }
  3277. }
  3278. // last point ends with total length
  3279. chunkLengths[ chunkLengths.length ] = totalLength;
  3280. return { chunks: chunkLengths, total: totalLength };
  3281. };
  3282. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3283. var i, j,
  3284. index, indexCurrent, indexNext,
  3285. linearDistance, realDistance,
  3286. sampling, position,
  3287. newpoints = [],
  3288. tmpVec = new THREE.Vector3(),
  3289. sl = this.getLength();
  3290. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3291. for ( i = 1; i < this.points.length; i++ ) {
  3292. //tmpVec.copy( this.points[ i - 1 ] );
  3293. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3294. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3295. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3296. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3297. indexNext = i / ( this.points.length - 1 );
  3298. for ( j = 1; j < sampling - 1; j++ ) {
  3299. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3300. position = this.getPoint( index );
  3301. newpoints.push( tmpVec.copy( position ).clone() );
  3302. }
  3303. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3304. }
  3305. this.points = newpoints;
  3306. };
  3307. // Catmull-Rom
  3308. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3309. var v0 = ( p2 - p0 ) * 0.5,
  3310. v1 = ( p3 - p1 ) * 0.5;
  3311. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3312. };
  3313. };
  3314. /**
  3315. * @author bhouston / http://exocortex.com
  3316. * @author mrdoob / http://mrdoob.com/
  3317. */
  3318. THREE.Triangle = function ( a, b, c ) {
  3319. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3320. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3321. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3322. };
  3323. THREE.Triangle.normal = function() {
  3324. var v0 = new THREE.Vector3();
  3325. return function( a, b, c, optionalTarget ) {
  3326. var result = optionalTarget || new THREE.Vector3();
  3327. result.subVectors( c, b );
  3328. v0.subVectors( a, b );
  3329. result.cross( v0 );
  3330. var resultLengthSq = result.lengthSq();
  3331. if( resultLengthSq > 0 ) {
  3332. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3333. }
  3334. return result.set( 0, 0, 0 );
  3335. };
  3336. }();
  3337. // static/instance method to calculate barycoordinates
  3338. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3339. THREE.Triangle.barycoordFromPoint = function() {
  3340. var v0 = new THREE.Vector3(),
  3341. v1 = new THREE.Vector3(),
  3342. v2 = new THREE.Vector3();
  3343. return function ( point, a, b, c, optionalTarget ) {
  3344. v0.subVectors( c, a );
  3345. v1.subVectors( b, a );
  3346. v2.subVectors( point, a );
  3347. var dot00 = v0.dot( v0 );
  3348. var dot01 = v0.dot( v1 );
  3349. var dot02 = v0.dot( v2 );
  3350. var dot11 = v1.dot( v1 );
  3351. var dot12 = v1.dot( v2 );
  3352. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3353. var result = optionalTarget || new THREE.Vector3();
  3354. // colinear or singular triangle
  3355. if( denom == 0 ) {
  3356. // arbitrary location outside of triangle?
  3357. // not sure if this is the best idea, maybe should be returning undefined
  3358. return result.set( -2, -1, -1 );
  3359. }
  3360. var invDenom = 1 / denom;
  3361. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3362. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3363. // barycoordinates must always sum to 1
  3364. return result.set( 1 - u - v, v, u );
  3365. };
  3366. }();
  3367. THREE.Triangle.containsPoint = function() {
  3368. var v1 = new THREE.Vector3();
  3369. return function ( point, a, b, c ) {
  3370. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3371. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3372. };
  3373. }();
  3374. THREE.extend( THREE.Triangle.prototype, {
  3375. constructor: THREE.Triangle,
  3376. set: function ( a, b, c ) {
  3377. this.a.copy( a );
  3378. this.b.copy( b );
  3379. this.c.copy( c );
  3380. return this;
  3381. },
  3382. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3383. this.a.copy( points[i0] );
  3384. this.b.copy( points[i1] );
  3385. this.c.copy( points[i2] );
  3386. return this;
  3387. },
  3388. copy: function ( triangle ) {
  3389. this.a.copy( triangle.a );
  3390. this.b.copy( triangle.b );
  3391. this.c.copy( triangle.c );
  3392. return this;
  3393. },
  3394. area: function() {
  3395. var v0 = new THREE.Vector3();
  3396. var v1 = new THREE.Vector3();
  3397. return function () {
  3398. v0.subVectors( this.c, this.b );
  3399. v1.subVectors( this.a, this.b );
  3400. return v0.cross( v1 ).length() * 0.5;
  3401. };
  3402. }(),
  3403. midpoint: function ( optionalTarget ) {
  3404. var result = optionalTarget || new THREE.Vector3();
  3405. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3406. },
  3407. normal: function ( optionalTarget ) {
  3408. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3409. },
  3410. plane: function ( optionalTarget ) {
  3411. var result = optionalTarget || new THREE.Plane();
  3412. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3413. },
  3414. barycoordFromPoint: function ( point, optionalTarget ) {
  3415. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3416. },
  3417. containsPoint: function ( point ) {
  3418. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3419. },
  3420. equals: function ( triangle ) {
  3421. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3422. },
  3423. clone: function () {
  3424. return new THREE.Triangle().copy( this );
  3425. }
  3426. } );
  3427. /**
  3428. * @author mrdoob / http://mrdoob.com/
  3429. */
  3430. THREE.Vertex = function ( v ) {
  3431. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3432. return v;
  3433. };
  3434. /**
  3435. * @author mrdoob / http://mrdoob.com/
  3436. */
  3437. THREE.UV = function ( u, v ) {
  3438. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3439. return new THREE.Vector2( u, v );
  3440. };
  3441. /**
  3442. * @author alteredq / http://alteredqualia.com/
  3443. */
  3444. THREE.Clock = function ( autoStart ) {
  3445. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3446. this.startTime = 0;
  3447. this.oldTime = 0;
  3448. this.elapsedTime = 0;
  3449. this.running = false;
  3450. };
  3451. THREE.extend( THREE.Clock.prototype, {
  3452. start: function () {
  3453. this.startTime = window.performance !== undefined && window.performance.now !== undefined
  3454. ? window.performance.now()
  3455. : Date.now();
  3456. this.oldTime = this.startTime;
  3457. this.running = true;
  3458. },
  3459. stop: function () {
  3460. this.getElapsedTime();
  3461. this.running = false;
  3462. },
  3463. getElapsedTime: function () {
  3464. this.getDelta();
  3465. return this.elapsedTime;
  3466. },
  3467. getDelta: function () {
  3468. var diff = 0;
  3469. if ( this.autoStart && ! this.running ) {
  3470. this.start();
  3471. }
  3472. if ( this.running ) {
  3473. var newTime = window.performance !== undefined && window.performance.now !== undefined
  3474. ? window.performance.now()
  3475. : Date.now();
  3476. diff = 0.001 * ( newTime - this.oldTime );
  3477. this.oldTime = newTime;
  3478. this.elapsedTime += diff;
  3479. }
  3480. return diff;
  3481. }
  3482. } );
  3483. /**
  3484. * https://github.com/mrdoob/eventdispatcher.js/
  3485. */
  3486. THREE.EventDispatcher = function () {
  3487. var listeners = {};
  3488. this.addEventListener = function ( type, listener ) {
  3489. if ( listeners[ type ] === undefined ) {
  3490. listeners[ type ] = [];
  3491. }
  3492. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3493. listeners[ type ].push( listener );
  3494. }
  3495. };
  3496. this.removeEventListener = function ( type, listener ) {
  3497. var index = listeners[ type ].indexOf( listener );
  3498. if ( index !== - 1 ) {
  3499. listeners[ type ].splice( index, 1 );
  3500. }
  3501. };
  3502. this.dispatchEvent = function ( event ) {
  3503. var listenerArray = listeners[ event.type ];
  3504. if ( listenerArray !== undefined ) {
  3505. event.target = this;
  3506. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  3507. listenerArray[ i ].call( this, event );
  3508. }
  3509. }
  3510. };
  3511. };
  3512. /**
  3513. * @author mrdoob / http://mrdoob.com/
  3514. * @author bhouston / http://exocortex.com/
  3515. */
  3516. ( function ( THREE ) {
  3517. THREE.Raycaster = function ( origin, direction, near, far ) {
  3518. this.ray = new THREE.Ray( origin, direction );
  3519. // normalized ray.direction required for accurate distance calculations
  3520. if( this.ray.direction.lengthSq() > 0 ) {
  3521. this.ray.direction.normalize();
  3522. }
  3523. this.near = near || 0;
  3524. this.far = far || Infinity;
  3525. };
  3526. var sphere = new THREE.Sphere();
  3527. var localRay = new THREE.Ray();
  3528. var facePlane = new THREE.Plane();
  3529. var intersectPoint = new THREE.Vector3();
  3530. var matrixPosition = new THREE.Vector3();
  3531. var inverseMatrix = new THREE.Matrix4();
  3532. var descSort = function ( a, b ) {
  3533. return a.distance - b.distance;
  3534. };
  3535. var intersectObject = function ( object, raycaster, intersects ) {
  3536. if ( object instanceof THREE.Particle ) {
  3537. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3538. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  3539. if ( distance > object.scale.x ) {
  3540. return intersects;
  3541. }
  3542. intersects.push( {
  3543. distance: distance,
  3544. point: object.position,
  3545. face: null,
  3546. object: object
  3547. } );
  3548. } else if ( object instanceof THREE.Mesh ) {
  3549. // Checking boundingSphere distance to ray
  3550. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3551. sphere.set(
  3552. matrixPosition,
  3553. object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() );
  3554. if ( ! raycaster.ray.isIntersectionSphere( sphere ) ) {
  3555. return intersects;
  3556. }
  3557. // Checking faces
  3558. var geometry = object.geometry;
  3559. var vertices = geometry.vertices;
  3560. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3561. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3562. var side = object.material.side;
  3563. var a, b, c, d;
  3564. var precision = raycaster.precision;
  3565. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  3566. inverseMatrix.getInverse( object.matrixWorld );
  3567. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  3568. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  3569. var face = geometry.faces[ f ];
  3570. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  3571. if ( material === undefined ) continue;
  3572. facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] );
  3573. var planeDistance = localRay.distanceToPlane( facePlane );
  3574. // bail if raycaster and plane are parallel
  3575. if ( Math.abs( planeDistance ) < precision ) continue;
  3576. // if negative distance, then plane is behind raycaster
  3577. if ( planeDistance < 0 ) continue;
  3578. // check if we hit the wrong side of a single sided face
  3579. side = material.side;
  3580. if( side !== THREE.DoubleSide ) {
  3581. var planeSign = localRay.direction.dot( facePlane.normal );
  3582. if( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3583. }
  3584. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3585. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3586. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3587. if ( face instanceof THREE.Face3 ) {
  3588. a = vertices[ face.a ];
  3589. b = vertices[ face.b ];
  3590. c = vertices[ face.c ];
  3591. if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue;
  3592. } else if ( face instanceof THREE.Face4 ) {
  3593. a = vertices[ face.a ];
  3594. b = vertices[ face.b ];
  3595. c = vertices[ face.c ];
  3596. d = vertices[ face.d ];
  3597. if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) &&
  3598. ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue;
  3599. } else {
  3600. // This is added because if we call out of this if/else group when none of the cases
  3601. // match it will add a point to the intersection list erroneously.
  3602. throw Error( "face type not supported" );
  3603. }
  3604. intersects.push( {
  3605. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3606. point: raycaster.ray.at( planeDistance ),
  3607. face: face,
  3608. faceIndex: f,
  3609. object: object
  3610. } );
  3611. }
  3612. }
  3613. };
  3614. var intersectDescendants = function ( object, raycaster, intersects ) {
  3615. var descendants = object.getDescendants();
  3616. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  3617. intersectObject( descendants[ i ], raycaster, intersects );
  3618. }
  3619. };
  3620. //
  3621. THREE.Raycaster.prototype.precision = 0.0001;
  3622. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  3623. this.ray.set( origin, direction );
  3624. // normalized ray.direction required for accurate distance calculations
  3625. if( this.ray.direction.length() > 0 ) {
  3626. this.ray.direction.normalize();
  3627. }
  3628. };
  3629. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  3630. var intersects = [];
  3631. if ( recursive === true ) {
  3632. intersectDescendants( object, this, intersects );
  3633. }
  3634. intersectObject( object, this, intersects );
  3635. intersects.sort( descSort );
  3636. return intersects;
  3637. };
  3638. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  3639. var intersects = [];
  3640. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  3641. intersectObject( objects[ i ], this, intersects );
  3642. if ( recursive === true ) {
  3643. intersectDescendants( objects[ i ], this, intersects );
  3644. }
  3645. }
  3646. intersects.sort( descSort );
  3647. return intersects;
  3648. };
  3649. }( THREE ) );
  3650. /**
  3651. * @author mrdoob / http://mrdoob.com/
  3652. * @author mikael emtinger / http://gomo.se/
  3653. * @author alteredq / http://alteredqualia.com/
  3654. * @author WestLangley / http://github.com/WestLangley
  3655. */
  3656. THREE.Object3D = function () {
  3657. this.id = THREE.Object3DIdCount ++;
  3658. this.name = '';
  3659. this.parent = undefined;
  3660. this.children = [];
  3661. this.up = new THREE.Vector3( 0, 1, 0 );
  3662. this.position = new THREE.Vector3();
  3663. this.rotation = new THREE.Vector3();
  3664. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  3665. this.scale = new THREE.Vector3( 1, 1, 1 );
  3666. this.renderDepth = null;
  3667. this.rotationAutoUpdate = true;
  3668. this.matrix = new THREE.Matrix4();
  3669. this.matrixWorld = new THREE.Matrix4();
  3670. this.matrixRotationWorld = new THREE.Matrix4();
  3671. this.matrixAutoUpdate = true;
  3672. this.matrixWorldNeedsUpdate = true;
  3673. this.quaternion = new THREE.Quaternion();
  3674. this.useQuaternion = false;
  3675. this.visible = true;
  3676. this.castShadow = false;
  3677. this.receiveShadow = false;
  3678. this.frustumCulled = true;
  3679. this.userData = {};
  3680. };
  3681. THREE.Object3D.prototype = {
  3682. constructor: THREE.Object3D,
  3683. applyMatrix: function () {
  3684. var m1 = new THREE.Matrix4();
  3685. return function ( matrix ) {
  3686. this.matrix.multiplyMatrices( matrix, this.matrix );
  3687. this.position.getPositionFromMatrix( this.matrix );
  3688. this.scale.getScaleFromMatrix( this.matrix );
  3689. m1.extractRotation( this.matrix );
  3690. if ( this.useQuaternion === true ) {
  3691. this.quaternion.setFromRotationMatrix( m1 );
  3692. } else {
  3693. this.rotation.setEulerFromRotationMatrix( m1, this.eulerOrder );
  3694. }
  3695. }
  3696. }(),
  3697. translate: function () {
  3698. var v1 = new THREE.Vector3();
  3699. return function ( distance, axis ) {
  3700. // axis is assumed to be normalized
  3701. v1.copy( axis );
  3702. if ( this.useQuaternion === true ) {
  3703. v1.applyQuaternion( this.quaternion );
  3704. } else {
  3705. v1.applyEuler( this.rotation, this.eulerOrder );
  3706. }
  3707. v1.multiplyScalar( distance );
  3708. this.position.add( v1 );
  3709. return this;
  3710. };
  3711. }(),
  3712. translateX: function () {
  3713. var v1 = new THREE.Vector3( 1, 0, 0 );
  3714. return function ( distance ) {
  3715. return this.translate( distance, v1 );
  3716. };
  3717. }(),
  3718. translateY: function () {
  3719. var v1 = new THREE.Vector3( 0, 1, 0 );
  3720. return function ( distance ) {
  3721. return this.translate( distance, v1 );
  3722. };
  3723. }(),
  3724. translateZ: function () {
  3725. var v1 = new THREE.Vector3( 0, 0, 1 );
  3726. return function ( distance ) {
  3727. return this.translate( distance, v1 );
  3728. };
  3729. }(),
  3730. localToWorld: function ( vector ) {
  3731. return vector.applyMatrix4( this.matrixWorld );
  3732. },
  3733. worldToLocal: function () {
  3734. var m1 = new THREE.Matrix4();
  3735. return function ( vector ) {
  3736. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  3737. };
  3738. }(),
  3739. lookAt: function () {
  3740. // This routine does not support objects with rotated and/or translated parent(s)
  3741. var m1 = new THREE.Matrix4();
  3742. return function ( vector ) {
  3743. m1.lookAt( vector, this.position, this.up );
  3744. if ( this.useQuaternion === true ) {
  3745. this.quaternion.setFromRotationMatrix( m1 );
  3746. } else {
  3747. this.rotation.setEulerFromRotationMatrix( m1, this.eulerOrder );
  3748. }
  3749. };
  3750. }(),
  3751. add: function ( object ) {
  3752. if ( object === this ) {
  3753. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  3754. return;
  3755. }
  3756. if ( object instanceof THREE.Object3D ) {
  3757. if ( object.parent !== undefined ) {
  3758. object.parent.remove( object );
  3759. }
  3760. object.parent = this;
  3761. this.children.push( object );
  3762. // add to scene
  3763. var scene = this;
  3764. while ( scene.parent !== undefined ) {
  3765. scene = scene.parent;
  3766. }
  3767. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3768. scene.__addObject( object );
  3769. }
  3770. }
  3771. },
  3772. remove: function ( object ) {
  3773. var index = this.children.indexOf( object );
  3774. if ( index !== - 1 ) {
  3775. object.parent = undefined;
  3776. this.children.splice( index, 1 );
  3777. // remove from scene
  3778. var scene = this;
  3779. while ( scene.parent !== undefined ) {
  3780. scene = scene.parent;
  3781. }
  3782. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3783. scene.__removeObject( object );
  3784. }
  3785. }
  3786. },
  3787. traverse: function ( callback ) {
  3788. callback( this );
  3789. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3790. this.children[ i ].traverse( callback );
  3791. }
  3792. },
  3793. getChildByName: function ( name, recursive ) {
  3794. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3795. var child = this.children[ i ];
  3796. if ( child.name === name ) {
  3797. return child;
  3798. }
  3799. if ( recursive === true ) {
  3800. child = child.getChildByName( name, recursive );
  3801. if ( child !== undefined ) {
  3802. return child;
  3803. }
  3804. }
  3805. }
  3806. return undefined;
  3807. },
  3808. getDescendants: function ( array ) {
  3809. if ( array === undefined ) array = [];
  3810. Array.prototype.push.apply( array, this.children );
  3811. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3812. this.children[ i ].getDescendants( array );
  3813. }
  3814. return array;
  3815. },
  3816. updateMatrix: function () {
  3817. this.matrix.setPosition( this.position );
  3818. if ( this.useQuaternion === false ) {
  3819. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  3820. } else {
  3821. this.matrix.setRotationFromQuaternion( this.quaternion );
  3822. }
  3823. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  3824. this.matrix.scale( this.scale );
  3825. }
  3826. this.matrixWorldNeedsUpdate = true;
  3827. },
  3828. updateMatrixWorld: function ( force ) {
  3829. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  3830. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  3831. if ( this.parent === undefined ) {
  3832. this.matrixWorld.copy( this.matrix );
  3833. } else {
  3834. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  3835. }
  3836. this.matrixWorldNeedsUpdate = false;
  3837. force = true;
  3838. }
  3839. // update children
  3840. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3841. this.children[ i ].updateMatrixWorld( force );
  3842. }
  3843. },
  3844. clone: function ( object ) {
  3845. if ( object === undefined ) object = new THREE.Object3D();
  3846. object.name = this.name;
  3847. object.up.copy( this.up );
  3848. object.position.copy( this.position );
  3849. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  3850. object.eulerOrder = this.eulerOrder;
  3851. object.scale.copy( this.scale );
  3852. object.renderDepth = this.renderDepth;
  3853. object.rotationAutoUpdate = this.rotationAutoUpdate;
  3854. object.matrix.copy( this.matrix );
  3855. object.matrixWorld.copy( this.matrixWorld );
  3856. object.matrixRotationWorld.copy( this.matrixRotationWorld );
  3857. object.matrixAutoUpdate = this.matrixAutoUpdate;
  3858. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  3859. object.quaternion.copy( this.quaternion );
  3860. object.useQuaternion = this.useQuaternion;
  3861. object.visible = this.visible;
  3862. object.castShadow = this.castShadow;
  3863. object.receiveShadow = this.receiveShadow;
  3864. object.frustumCulled = this.frustumCulled;
  3865. for ( var i = 0; i < this.children.length; i ++ ) {
  3866. var child = this.children[ i ];
  3867. object.add( child.clone() );
  3868. }
  3869. return object;
  3870. }
  3871. };
  3872. THREE.Object3D.defaultEulerOrder = 'XYZ',
  3873. THREE.Object3DIdCount = 0;
  3874. /**
  3875. * @author mrdoob / http://mrdoob.com/
  3876. * @author supereggbert / http://www.paulbrunt.co.uk/
  3877. * @author julianwa / https://github.com/julianwa
  3878. */
  3879. THREE.Projector = function () {
  3880. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  3881. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  3882. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  3883. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  3884. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  3885. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  3886. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  3887. _vector3 = new THREE.Vector3(),
  3888. _vector4 = new THREE.Vector4(),
  3889. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  3890. _boundingBox = new THREE.Box3(),
  3891. _points3 = new Array( 3 ),
  3892. _points4 = new Array( 4 ),
  3893. _viewMatrix = new THREE.Matrix4(),
  3894. _viewProjectionMatrix = new THREE.Matrix4(),
  3895. _modelMatrix,
  3896. _modelViewProjectionMatrix = new THREE.Matrix4(),
  3897. _normalMatrix = new THREE.Matrix3(),
  3898. _normalViewMatrix = new THREE.Matrix3(),
  3899. _centroid = new THREE.Vector3(),
  3900. _frustum = new THREE.Frustum(),
  3901. _clippedVertex1PositionScreen = new THREE.Vector4(),
  3902. _clippedVertex2PositionScreen = new THREE.Vector4();
  3903. this.projectVector = function ( vector, camera ) {
  3904. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  3905. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  3906. return vector.applyProjection( _viewProjectionMatrix );
  3907. };
  3908. this.unprojectVector = function ( vector, camera ) {
  3909. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  3910. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  3911. return vector.applyProjection( _viewProjectionMatrix );
  3912. };
  3913. this.pickingRay = function ( vector, camera ) {
  3914. // set two vectors with opposing z values
  3915. vector.z = -1.0;
  3916. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  3917. this.unprojectVector( vector, camera );
  3918. this.unprojectVector( end, camera );
  3919. // find direction from vector to end
  3920. end.sub( vector ).normalize();
  3921. return new THREE.Raycaster( vector, end );
  3922. };
  3923. var projectGraph = function ( root, sortObjects ) {
  3924. _objectCount = 0;
  3925. _renderData.objects.length = 0;
  3926. _renderData.sprites.length = 0;
  3927. _renderData.lights.length = 0;
  3928. var projectObject = function ( parent ) {
  3929. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  3930. var object = parent.children[ c ];
  3931. if ( object.visible === false ) continue;
  3932. if ( object instanceof THREE.Light ) {
  3933. _renderData.lights.push( object );
  3934. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  3935. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  3936. _object = getNextObjectInPool();
  3937. _object.object = object;
  3938. if ( object.renderDepth !== null ) {
  3939. _object.z = object.renderDepth;
  3940. } else {
  3941. _vector3.getPositionFromMatrix( object.matrixWorld );
  3942. _vector3.applyProjection( _viewProjectionMatrix );
  3943. _object.z = _vector3.z;
  3944. }
  3945. _renderData.objects.push( _object );
  3946. }
  3947. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  3948. _object = getNextObjectInPool();
  3949. _object.object = object;
  3950. // TODO: Find an elegant and performant solution and remove this dupe code.
  3951. if ( object.renderDepth !== null ) {
  3952. _object.z = object.renderDepth;
  3953. } else {
  3954. _vector3.getPositionFromMatrix( object.matrixWorld );
  3955. _vector3.applyProjection( _viewProjectionMatrix );
  3956. _object.z = _vector3.z;
  3957. }
  3958. _renderData.sprites.push( _object );
  3959. } else {
  3960. _object = getNextObjectInPool();
  3961. _object.object = object;
  3962. if ( object.renderDepth !== null ) {
  3963. _object.z = object.renderDepth;
  3964. } else {
  3965. _vector3.getPositionFromMatrix( object.matrixWorld );
  3966. _vector3.applyProjection( _viewProjectionMatrix );
  3967. _object.z = _vector3.z;
  3968. }
  3969. _renderData.objects.push( _object );
  3970. }
  3971. projectObject( object );
  3972. }
  3973. };
  3974. projectObject( root );
  3975. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  3976. return _renderData;
  3977. };
  3978. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  3979. var visible = false,
  3980. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  3981. geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  3982. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  3983. _face3Count = 0;
  3984. _face4Count = 0;
  3985. _lineCount = 0;
  3986. _particleCount = 0;
  3987. _renderData.elements.length = 0;
  3988. scene.updateMatrixWorld();
  3989. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  3990. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  3991. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  3992. _normalViewMatrix.getInverse( _viewMatrix );
  3993. _normalViewMatrix.transpose();
  3994. _frustum.setFromMatrix( _viewProjectionMatrix );
  3995. _renderData = projectGraph( scene, sortObjects );
  3996. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  3997. object = _renderData.objects[ o ].object;
  3998. _modelMatrix = object.matrixWorld;
  3999. _vertexCount = 0;
  4000. if ( object instanceof THREE.Mesh ) {
  4001. geometry = object.geometry;
  4002. vertices = geometry.vertices;
  4003. faces = geometry.faces;
  4004. faceVertexUvs = geometry.faceVertexUvs;
  4005. _normalMatrix.getInverse( _modelMatrix );
  4006. _normalMatrix.transpose();
  4007. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4008. objectMaterials = isFaceMaterial === true ? object.material : null;
  4009. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  4010. _vertex = getNextVertexInPool();
  4011. _vertex.positionWorld.copy( vertices[ v ] ).applyMatrix4( _modelMatrix );
  4012. _vertex.positionScreen.copy( _vertex.positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4013. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  4014. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  4015. _vertex.positionScreen.z /= _vertex.positionScreen.w;
  4016. _vertex.visible = ! ( _vertex.positionScreen.x < -1 || _vertex.positionScreen.x > 1 ||
  4017. _vertex.positionScreen.y < -1 || _vertex.positionScreen.y > 1 ||
  4018. _vertex.positionScreen.z < -1 || _vertex.positionScreen.z > 1 );
  4019. }
  4020. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  4021. face = faces[ f ];
  4022. var material = isFaceMaterial === true
  4023. ? objectMaterials.materials[ face.materialIndex ]
  4024. : object.material;
  4025. if ( material === undefined ) continue;
  4026. var side = material.side;
  4027. if ( face instanceof THREE.Face3 ) {
  4028. v1 = _vertexPool[ face.a ];
  4029. v2 = _vertexPool[ face.b ];
  4030. v3 = _vertexPool[ face.c ];
  4031. _points3[ 0 ] = v1.positionScreen;
  4032. _points3[ 1 ] = v2.positionScreen;
  4033. _points3[ 2 ] = v3.positionScreen;
  4034. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4035. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4036. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4037. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4038. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4039. _face = getNextFace3InPool();
  4040. _face.v1.copy( v1 );
  4041. _face.v2.copy( v2 );
  4042. _face.v3.copy( v3 );
  4043. } else {
  4044. continue;
  4045. }
  4046. } else {
  4047. continue;
  4048. }
  4049. } else if ( face instanceof THREE.Face4 ) {
  4050. v1 = _vertexPool[ face.a ];
  4051. v2 = _vertexPool[ face.b ];
  4052. v3 = _vertexPool[ face.c ];
  4053. v4 = _vertexPool[ face.d ];
  4054. _points4[ 0 ] = v1.positionScreen;
  4055. _points4[ 1 ] = v2.positionScreen;
  4056. _points4[ 2 ] = v3.positionScreen;
  4057. _points4[ 3 ] = v4.positionScreen;
  4058. if ( v1.visible === true || v2.visible === true || v3.visible === true || v4.visible === true ||
  4059. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points4 ) ) ) {
  4060. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4061. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  4062. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  4063. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  4064. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4065. _face = getNextFace4InPool();
  4066. _face.v1.copy( v1 );
  4067. _face.v2.copy( v2 );
  4068. _face.v3.copy( v3 );
  4069. _face.v4.copy( v4 );
  4070. } else {
  4071. continue;
  4072. }
  4073. } else {
  4074. continue;
  4075. }
  4076. }
  4077. _face.normalModel.copy( face.normal );
  4078. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4079. _face.normalModel.negate();
  4080. }
  4081. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4082. _face.normalModelView.copy( _face.normalModel ).applyMatrix3( _normalViewMatrix );
  4083. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4084. faceVertexNormals = face.vertexNormals;
  4085. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  4086. var normalModel = _face.vertexNormalsModel[ n ];
  4087. normalModel.copy( faceVertexNormals[ n ] );
  4088. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4089. normalModel.negate();
  4090. }
  4091. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4092. var normalModelView = _face.vertexNormalsModelView[ n ];
  4093. normalModelView.copy( normalModel ).applyMatrix3( _normalViewMatrix );
  4094. }
  4095. _face.vertexNormalsLength = faceVertexNormals.length;
  4096. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  4097. uvs = faceVertexUvs[ c ][ f ];
  4098. if ( uvs === undefined ) continue;
  4099. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  4100. _face.uvs[ c ][ u ] = uvs[ u ];
  4101. }
  4102. }
  4103. _face.color = face.color;
  4104. _face.material = material;
  4105. _centroid.copy( _face.centroidModel ).applyProjection( _viewProjectionMatrix );
  4106. _face.z = _centroid.z;
  4107. _renderData.elements.push( _face );
  4108. }
  4109. } else if ( object instanceof THREE.Line ) {
  4110. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4111. vertices = object.geometry.vertices;
  4112. v1 = getNextVertexInPool();
  4113. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4114. // Handle LineStrip and LinePieces
  4115. var step = object.type === THREE.LinePieces ? 2 : 1;
  4116. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  4117. v1 = getNextVertexInPool();
  4118. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4119. if ( ( v + 1 ) % step > 0 ) continue;
  4120. v2 = _vertexPool[ _vertexCount - 2 ];
  4121. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4122. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4123. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4124. // Perform the perspective divide
  4125. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4126. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4127. _line = getNextLineInPool();
  4128. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4129. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4130. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4131. _line.material = object.material;
  4132. _renderData.elements.push( _line );
  4133. }
  4134. }
  4135. }
  4136. }
  4137. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  4138. object = _renderData.sprites[ o ].object;
  4139. _modelMatrix = object.matrixWorld;
  4140. if ( object instanceof THREE.Particle ) {
  4141. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4142. _vector4.applyMatrix4( _viewProjectionMatrix );
  4143. _vector4.z /= _vector4.w;
  4144. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  4145. _particle = getNextParticleInPool();
  4146. _particle.object = object;
  4147. _particle.x = _vector4.x / _vector4.w;
  4148. _particle.y = _vector4.y / _vector4.w;
  4149. _particle.z = _vector4.z;
  4150. _particle.rotation = object.rotation.z;
  4151. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4152. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4153. _particle.material = object.material;
  4154. _renderData.elements.push( _particle );
  4155. }
  4156. }
  4157. }
  4158. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4159. return _renderData;
  4160. };
  4161. // Pools
  4162. function getNextObjectInPool() {
  4163. if ( _objectCount === _objectPoolLength ) {
  4164. var object = new THREE.RenderableObject();
  4165. _objectPool.push( object );
  4166. _objectPoolLength ++;
  4167. _objectCount ++;
  4168. return object;
  4169. }
  4170. return _objectPool[ _objectCount ++ ];
  4171. }
  4172. function getNextVertexInPool() {
  4173. if ( _vertexCount === _vertexPoolLength ) {
  4174. var vertex = new THREE.RenderableVertex();
  4175. _vertexPool.push( vertex );
  4176. _vertexPoolLength ++;
  4177. _vertexCount ++;
  4178. return vertex;
  4179. }
  4180. return _vertexPool[ _vertexCount ++ ];
  4181. }
  4182. function getNextFace3InPool() {
  4183. if ( _face3Count === _face3PoolLength ) {
  4184. var face = new THREE.RenderableFace3();
  4185. _face3Pool.push( face );
  4186. _face3PoolLength ++;
  4187. _face3Count ++;
  4188. return face;
  4189. }
  4190. return _face3Pool[ _face3Count ++ ];
  4191. }
  4192. function getNextFace4InPool() {
  4193. if ( _face4Count === _face4PoolLength ) {
  4194. var face = new THREE.RenderableFace4();
  4195. _face4Pool.push( face );
  4196. _face4PoolLength ++;
  4197. _face4Count ++;
  4198. return face;
  4199. }
  4200. return _face4Pool[ _face4Count ++ ];
  4201. }
  4202. function getNextLineInPool() {
  4203. if ( _lineCount === _linePoolLength ) {
  4204. var line = new THREE.RenderableLine();
  4205. _linePool.push( line );
  4206. _linePoolLength ++;
  4207. _lineCount ++
  4208. return line;
  4209. }
  4210. return _linePool[ _lineCount ++ ];
  4211. }
  4212. function getNextParticleInPool() {
  4213. if ( _particleCount === _particlePoolLength ) {
  4214. var particle = new THREE.RenderableParticle();
  4215. _particlePool.push( particle );
  4216. _particlePoolLength ++;
  4217. _particleCount ++
  4218. return particle;
  4219. }
  4220. return _particlePool[ _particleCount ++ ];
  4221. }
  4222. //
  4223. function painterSort( a, b ) {
  4224. return b.z - a.z;
  4225. }
  4226. function clipLine( s1, s2 ) {
  4227. var alpha1 = 0, alpha2 = 1,
  4228. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4229. // Z = -1 and Z = +1, respectively.
  4230. bc1near = s1.z + s1.w,
  4231. bc2near = s2.z + s2.w,
  4232. bc1far = - s1.z + s1.w,
  4233. bc2far = - s2.z + s2.w;
  4234. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4235. // Both vertices lie entirely within all clip planes.
  4236. return true;
  4237. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4238. // Both vertices lie entirely outside one of the clip planes.
  4239. return false;
  4240. } else {
  4241. // The line segment spans at least one clip plane.
  4242. if ( bc1near < 0 ) {
  4243. // v1 lies outside the near plane, v2 inside
  4244. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4245. } else if ( bc2near < 0 ) {
  4246. // v2 lies outside the near plane, v1 inside
  4247. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4248. }
  4249. if ( bc1far < 0 ) {
  4250. // v1 lies outside the far plane, v2 inside
  4251. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4252. } else if ( bc2far < 0 ) {
  4253. // v2 lies outside the far plane, v2 inside
  4254. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4255. }
  4256. if ( alpha2 < alpha1 ) {
  4257. // The line segment spans two boundaries, but is outside both of them.
  4258. // (This can't happen when we're only clipping against just near/far but good
  4259. // to leave the check here for future usage if other clip planes are added.)
  4260. return false;
  4261. } else {
  4262. // Update the s1 and s2 vertices to match the clipped line segment.
  4263. s1.lerp( s2, alpha1 );
  4264. s2.lerp( s1, 1 - alpha2 );
  4265. return true;
  4266. }
  4267. }
  4268. }
  4269. };
  4270. /**
  4271. * @author mrdoob / http://mrdoob.com/
  4272. * @author alteredq / http://alteredqualia.com/
  4273. */
  4274. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4275. this.a = a;
  4276. this.b = b;
  4277. this.c = c;
  4278. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4279. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4280. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4281. this.vertexColors = color instanceof Array ? color : [];
  4282. this.vertexTangents = [];
  4283. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4284. this.centroid = new THREE.Vector3();
  4285. };
  4286. THREE.Face3.prototype = {
  4287. constructor: THREE.Face3,
  4288. clone: function () {
  4289. var face = new THREE.Face3( this.a, this.b, this.c );
  4290. face.normal.copy( this.normal );
  4291. face.color.copy( this.color );
  4292. face.centroid.copy( this.centroid );
  4293. face.materialIndex = this.materialIndex;
  4294. var i, il;
  4295. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4296. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4297. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4298. return face;
  4299. }
  4300. };
  4301. /**
  4302. * @author mrdoob / http://mrdoob.com/
  4303. * @author alteredq / http://alteredqualia.com/
  4304. */
  4305. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4306. this.a = a;
  4307. this.b = b;
  4308. this.c = c;
  4309. this.d = d;
  4310. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4311. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4312. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4313. this.vertexColors = color instanceof Array ? color : [];
  4314. this.vertexTangents = [];
  4315. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4316. this.centroid = new THREE.Vector3();
  4317. };
  4318. THREE.Face4.prototype = {
  4319. constructor: THREE.Face4,
  4320. clone: function () {
  4321. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  4322. face.normal.copy( this.normal );
  4323. face.color.copy( this.color );
  4324. face.centroid.copy( this.centroid );
  4325. face.materialIndex = this.materialIndex;
  4326. var i, il;
  4327. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4328. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4329. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4330. return face;
  4331. }
  4332. };
  4333. /**
  4334. * @author mrdoob / http://mrdoob.com/
  4335. * @author kile / http://kile.stravaganza.org/
  4336. * @author alteredq / http://alteredqualia.com/
  4337. * @author mikael emtinger / http://gomo.se/
  4338. * @author zz85 / http://www.lab4games.net/zz85/blog
  4339. * @author bhouston / http://exocortex.com
  4340. */
  4341. THREE.Geometry = function () {
  4342. THREE.EventDispatcher.call( this );
  4343. this.id = THREE.GeometryIdCount ++;
  4344. this.name = '';
  4345. this.vertices = [];
  4346. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  4347. this.normals = []; // one-to-one vertex normals, used in Ribbon
  4348. this.faces = [];
  4349. this.faceUvs = [[]];
  4350. this.faceVertexUvs = [[]];
  4351. this.morphTargets = [];
  4352. this.morphColors = [];
  4353. this.morphNormals = [];
  4354. this.skinWeights = [];
  4355. this.skinIndices = [];
  4356. this.lineDistances = [];
  4357. this.boundingBox = null;
  4358. this.boundingSphere = null;
  4359. this.hasTangents = false;
  4360. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4361. // update flags
  4362. this.verticesNeedUpdate = false;
  4363. this.elementsNeedUpdate = false;
  4364. this.uvsNeedUpdate = false;
  4365. this.normalsNeedUpdate = false;
  4366. this.tangentsNeedUpdate = false;
  4367. this.colorsNeedUpdate = false;
  4368. this.lineDistancesNeedUpdate = false;
  4369. this.buffersNeedUpdate = false;
  4370. };
  4371. THREE.Geometry.prototype = {
  4372. constructor: THREE.Geometry,
  4373. applyMatrix: function ( matrix ) {
  4374. var normalMatrix = new THREE.Matrix3().getInverse( matrix ).transpose();
  4375. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4376. var vertex = this.vertices[ i ];
  4377. vertex.applyMatrix4( matrix );
  4378. }
  4379. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4380. var face = this.faces[ i ];
  4381. face.normal.applyMatrix3( normalMatrix ).normalize();
  4382. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4383. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4384. }
  4385. face.centroid.applyMatrix4( matrix );
  4386. }
  4387. },
  4388. computeCentroids: function () {
  4389. var f, fl, face;
  4390. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4391. face = this.faces[ f ];
  4392. face.centroid.set( 0, 0, 0 );
  4393. if ( face instanceof THREE.Face3 ) {
  4394. face.centroid.add( this.vertices[ face.a ] );
  4395. face.centroid.add( this.vertices[ face.b ] );
  4396. face.centroid.add( this.vertices[ face.c ] );
  4397. face.centroid.divideScalar( 3 );
  4398. } else if ( face instanceof THREE.Face4 ) {
  4399. face.centroid.add( this.vertices[ face.a ] );
  4400. face.centroid.add( this.vertices[ face.b ] );
  4401. face.centroid.add( this.vertices[ face.c ] );
  4402. face.centroid.add( this.vertices[ face.d ] );
  4403. face.centroid.divideScalar( 4 );
  4404. }
  4405. }
  4406. },
  4407. computeFaceNormals: function () {
  4408. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  4409. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4410. var face = this.faces[ f ];
  4411. var vA = this.vertices[ face.a ];
  4412. var vB = this.vertices[ face.b ];
  4413. var vC = this.vertices[ face.c ];
  4414. cb.subVectors( vC, vB );
  4415. ab.subVectors( vA, vB );
  4416. cb.cross( ab );
  4417. cb.normalize();
  4418. face.normal.copy( cb );
  4419. }
  4420. },
  4421. computeVertexNormals: function ( areaWeighted ) {
  4422. var v, vl, f, fl, face, vertices;
  4423. // create internal buffers for reuse when calling this method repeatedly
  4424. // (otherwise memory allocation / deallocation every frame is big resource hog)
  4425. if ( this.__tmpVertices === undefined ) {
  4426. this.__tmpVertices = new Array( this.vertices.length );
  4427. vertices = this.__tmpVertices;
  4428. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4429. vertices[ v ] = new THREE.Vector3();
  4430. }
  4431. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4432. face = this.faces[ f ];
  4433. if ( face instanceof THREE.Face3 ) {
  4434. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4435. } else if ( face instanceof THREE.Face4 ) {
  4436. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4437. }
  4438. }
  4439. } else {
  4440. vertices = this.__tmpVertices;
  4441. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4442. vertices[ v ].set( 0, 0, 0 );
  4443. }
  4444. }
  4445. if ( areaWeighted ) {
  4446. // vertex normals weighted by triangle areas
  4447. // http://www.iquilezles.org/www/articles/normals/normals.htm
  4448. var vA, vB, vC, vD;
  4449. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  4450. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  4451. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4452. face = this.faces[ f ];
  4453. if ( face instanceof THREE.Face3 ) {
  4454. vA = this.vertices[ face.a ];
  4455. vB = this.vertices[ face.b ];
  4456. vC = this.vertices[ face.c ];
  4457. cb.subVectors( vC, vB );
  4458. ab.subVectors( vA, vB );
  4459. cb.cross( ab );
  4460. vertices[ face.a ].add( cb );
  4461. vertices[ face.b ].add( cb );
  4462. vertices[ face.c ].add( cb );
  4463. } else if ( face instanceof THREE.Face4 ) {
  4464. vA = this.vertices[ face.a ];
  4465. vB = this.vertices[ face.b ];
  4466. vC = this.vertices[ face.c ];
  4467. vD = this.vertices[ face.d ];
  4468. // abd
  4469. db.subVectors( vD, vB );
  4470. ab.subVectors( vA, vB );
  4471. db.cross( ab );
  4472. vertices[ face.a ].add( db );
  4473. vertices[ face.b ].add( db );
  4474. vertices[ face.d ].add( db );
  4475. // bcd
  4476. dc.subVectors( vD, vC );
  4477. bc.subVectors( vB, vC );
  4478. dc.cross( bc );
  4479. vertices[ face.b ].add( dc );
  4480. vertices[ face.c ].add( dc );
  4481. vertices[ face.d ].add( dc );
  4482. }
  4483. }
  4484. } else {
  4485. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4486. face = this.faces[ f ];
  4487. if ( face instanceof THREE.Face3 ) {
  4488. vertices[ face.a ].add( face.normal );
  4489. vertices[ face.b ].add( face.normal );
  4490. vertices[ face.c ].add( face.normal );
  4491. } else if ( face instanceof THREE.Face4 ) {
  4492. vertices[ face.a ].add( face.normal );
  4493. vertices[ face.b ].add( face.normal );
  4494. vertices[ face.c ].add( face.normal );
  4495. vertices[ face.d ].add( face.normal );
  4496. }
  4497. }
  4498. }
  4499. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4500. vertices[ v ].normalize();
  4501. }
  4502. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4503. face = this.faces[ f ];
  4504. if ( face instanceof THREE.Face3 ) {
  4505. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4506. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4507. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4508. } else if ( face instanceof THREE.Face4 ) {
  4509. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4510. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4511. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4512. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  4513. }
  4514. }
  4515. },
  4516. computeMorphNormals: function () {
  4517. var i, il, f, fl, face;
  4518. // save original normals
  4519. // - create temp variables on first access
  4520. // otherwise just copy (for faster repeated calls)
  4521. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4522. face = this.faces[ f ];
  4523. if ( ! face.__originalFaceNormal ) {
  4524. face.__originalFaceNormal = face.normal.clone();
  4525. } else {
  4526. face.__originalFaceNormal.copy( face.normal );
  4527. }
  4528. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  4529. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  4530. if ( ! face.__originalVertexNormals[ i ] ) {
  4531. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  4532. } else {
  4533. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  4534. }
  4535. }
  4536. }
  4537. // use temp geometry to compute face and vertex normals for each morph
  4538. var tmpGeo = new THREE.Geometry();
  4539. tmpGeo.faces = this.faces;
  4540. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  4541. // create on first access
  4542. if ( ! this.morphNormals[ i ] ) {
  4543. this.morphNormals[ i ] = {};
  4544. this.morphNormals[ i ].faceNormals = [];
  4545. this.morphNormals[ i ].vertexNormals = [];
  4546. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  4547. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  4548. var faceNormal, vertexNormals;
  4549. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4550. face = this.faces[ f ];
  4551. faceNormal = new THREE.Vector3();
  4552. if ( face instanceof THREE.Face3 ) {
  4553. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  4554. } else {
  4555. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  4556. }
  4557. dstNormalsFace.push( faceNormal );
  4558. dstNormalsVertex.push( vertexNormals );
  4559. }
  4560. }
  4561. var morphNormals = this.morphNormals[ i ];
  4562. // set vertices to morph target
  4563. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  4564. // compute morph normals
  4565. tmpGeo.computeFaceNormals();
  4566. tmpGeo.computeVertexNormals();
  4567. // store morph normals
  4568. var faceNormal, vertexNormals;
  4569. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4570. face = this.faces[ f ];
  4571. faceNormal = morphNormals.faceNormals[ f ];
  4572. vertexNormals = morphNormals.vertexNormals[ f ];
  4573. faceNormal.copy( face.normal );
  4574. if ( face instanceof THREE.Face3 ) {
  4575. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4576. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4577. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4578. } else {
  4579. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4580. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4581. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4582. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  4583. }
  4584. }
  4585. }
  4586. // restore original normals
  4587. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4588. face = this.faces[ f ];
  4589. face.normal = face.__originalFaceNormal;
  4590. face.vertexNormals = face.__originalVertexNormals;
  4591. }
  4592. },
  4593. computeTangents: function () {
  4594. // based on http://www.terathon.com/code/tangent.html
  4595. // tangents go to vertices
  4596. var f, fl, v, vl, i, il, vertexIndex,
  4597. face, uv, vA, vB, vC, uvA, uvB, uvC,
  4598. x1, x2, y1, y2, z1, z2,
  4599. s1, s2, t1, t2, r, t, test,
  4600. tan1 = [], tan2 = [],
  4601. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  4602. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  4603. n = new THREE.Vector3(), w;
  4604. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4605. tan1[ v ] = new THREE.Vector3();
  4606. tan2[ v ] = new THREE.Vector3();
  4607. }
  4608. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  4609. vA = context.vertices[ a ];
  4610. vB = context.vertices[ b ];
  4611. vC = context.vertices[ c ];
  4612. uvA = uv[ ua ];
  4613. uvB = uv[ ub ];
  4614. uvC = uv[ uc ];
  4615. x1 = vB.x - vA.x;
  4616. x2 = vC.x - vA.x;
  4617. y1 = vB.y - vA.y;
  4618. y2 = vC.y - vA.y;
  4619. z1 = vB.z - vA.z;
  4620. z2 = vC.z - vA.z;
  4621. s1 = uvB.x - uvA.x;
  4622. s2 = uvC.x - uvA.x;
  4623. t1 = uvB.y - uvA.y;
  4624. t2 = uvC.y - uvA.y;
  4625. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4626. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  4627. ( t2 * y1 - t1 * y2 ) * r,
  4628. ( t2 * z1 - t1 * z2 ) * r );
  4629. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  4630. ( s1 * y2 - s2 * y1 ) * r,
  4631. ( s1 * z2 - s2 * z1 ) * r );
  4632. tan1[ a ].add( sdir );
  4633. tan1[ b ].add( sdir );
  4634. tan1[ c ].add( sdir );
  4635. tan2[ a ].add( tdir );
  4636. tan2[ b ].add( tdir );
  4637. tan2[ c ].add( tdir );
  4638. }
  4639. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4640. face = this.faces[ f ];
  4641. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  4642. if ( face instanceof THREE.Face3 ) {
  4643. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  4644. } else if ( face instanceof THREE.Face4 ) {
  4645. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  4646. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  4647. }
  4648. }
  4649. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  4650. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4651. face = this.faces[ f ];
  4652. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  4653. n.copy( face.vertexNormals[ i ] );
  4654. vertexIndex = face[ faceIndex[ i ] ];
  4655. t = tan1[ vertexIndex ];
  4656. // Gram-Schmidt orthogonalize
  4657. tmp.copy( t );
  4658. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4659. // Calculate handedness
  4660. tmp2.crossVectors( face.vertexNormals[ i ], t );
  4661. test = tmp2.dot( tan2[ vertexIndex ] );
  4662. w = (test < 0.0) ? -1.0 : 1.0;
  4663. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  4664. }
  4665. }
  4666. this.hasTangents = true;
  4667. },
  4668. computeLineDistances: function ( ) {
  4669. var d = 0;
  4670. var vertices = this.vertices;
  4671. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4672. if ( i > 0 ) {
  4673. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  4674. }
  4675. this.lineDistances[ i ] = d;
  4676. }
  4677. },
  4678. computeBoundingBox: function () {
  4679. if ( this.boundingBox === null ) {
  4680. this.boundingBox = new THREE.Box3();
  4681. }
  4682. this.boundingBox.setFromPoints( this.vertices );
  4683. },
  4684. computeBoundingSphere: function () {
  4685. if ( this.boundingSphere === null ) {
  4686. this.boundingSphere = new THREE.Sphere();
  4687. }
  4688. this.boundingSphere.setFromCenterAndPoints( this.boundingSphere.center, this.vertices );
  4689. },
  4690. /*
  4691. * Checks for duplicate vertices with hashmap.
  4692. * Duplicated vertices are removed
  4693. * and faces' vertices are updated.
  4694. */
  4695. mergeVertices: function () {
  4696. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  4697. var unique = [], changes = [];
  4698. var v, key;
  4699. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  4700. var precision = Math.pow( 10, precisionPoints );
  4701. var i,il, face;
  4702. var indices, k, j, jl, u;
  4703. // reset cache of vertices as it now will be changing.
  4704. this.__tmpVertices = undefined;
  4705. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  4706. v = this.vertices[ i ];
  4707. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  4708. if ( verticesMap[ key ] === undefined ) {
  4709. verticesMap[ key ] = i;
  4710. unique.push( this.vertices[ i ] );
  4711. changes[ i ] = unique.length - 1;
  4712. } else {
  4713. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  4714. changes[ i ] = changes[ verticesMap[ key ] ];
  4715. }
  4716. };
  4717. // if faces are completely degenerate after merging vertices, we
  4718. // have to remove them from the geometry.
  4719. var faceIndicesToRemove = [];
  4720. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  4721. face = this.faces[ i ];
  4722. if ( face instanceof THREE.Face3 ) {
  4723. face.a = changes[ face.a ];
  4724. face.b = changes[ face.b ];
  4725. face.c = changes[ face.c ];
  4726. indices = [ face.a, face.b, face.c ];
  4727. var dupIndex = -1;
  4728. // if any duplicate vertices are found in a Face3
  4729. // we have to remove the face as nothing can be saved
  4730. for ( var n = 0; n < 3; n ++ ) {
  4731. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  4732. dupIndex = n;
  4733. faceIndicesToRemove.push( i );
  4734. break;
  4735. }
  4736. }
  4737. } else if ( face instanceof THREE.Face4 ) {
  4738. face.a = changes[ face.a ];
  4739. face.b = changes[ face.b ];
  4740. face.c = changes[ face.c ];
  4741. face.d = changes[ face.d ];
  4742. // check dups in (a, b, c, d) and convert to -> face3
  4743. indices = [ face.a, face.b, face.c, face.d ];
  4744. var dupIndex = -1;
  4745. for ( var n = 0; n < 4; n ++ ) {
  4746. if ( indices[ n ] == indices[ ( n + 1 ) % 4 ] ) {
  4747. // if more than one duplicated vertex is found
  4748. // we can't generate any valid Face3's, thus
  4749. // we need to remove this face complete.
  4750. if ( dupIndex >= 0 ) {
  4751. faceIndicesToRemove.push( i );
  4752. }
  4753. dupIndex = n;
  4754. }
  4755. }
  4756. if ( dupIndex >= 0 ) {
  4757. indices.splice( dupIndex, 1 );
  4758. var newFace = new THREE.Face3( indices[0], indices[1], indices[2], face.normal, face.color, face.materialIndex );
  4759. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4760. u = this.faceVertexUvs[ j ][ i ];
  4761. if ( u ) {
  4762. u.splice( dupIndex, 1 );
  4763. }
  4764. }
  4765. if( face.vertexNormals && face.vertexNormals.length > 0) {
  4766. newFace.vertexNormals = face.vertexNormals;
  4767. newFace.vertexNormals.splice( dupIndex, 1 );
  4768. }
  4769. if( face.vertexColors && face.vertexColors.length > 0 ) {
  4770. newFace.vertexColors = face.vertexColors;
  4771. newFace.vertexColors.splice( dupIndex, 1 );
  4772. }
  4773. this.faces[ i ] = newFace;
  4774. }
  4775. }
  4776. }
  4777. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  4778. this.faces.splice( i, 1 );
  4779. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4780. this.faceVertexUvs[ j ].splice( i, 1 );
  4781. }
  4782. }
  4783. // Use unique set of vertices
  4784. var diff = this.vertices.length - unique.length;
  4785. this.vertices = unique;
  4786. return diff;
  4787. },
  4788. clone: function () {
  4789. var geometry = new THREE.Geometry();
  4790. var vertices = this.vertices;
  4791. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4792. geometry.vertices.push( vertices[ i ].clone() );
  4793. }
  4794. var faces = this.faces;
  4795. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  4796. geometry.faces.push( faces[ i ].clone() );
  4797. }
  4798. var uvs = this.faceVertexUvs[ 0 ];
  4799. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  4800. var uv = uvs[ i ], uvCopy = [];
  4801. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  4802. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  4803. }
  4804. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  4805. }
  4806. return geometry;
  4807. },
  4808. dispose: function () {
  4809. this.dispatchEvent( { type: 'dispose' } );
  4810. }
  4811. };
  4812. THREE.GeometryIdCount = 0;
  4813. /**
  4814. * @author alteredq / http://alteredqualia.com/
  4815. */
  4816. THREE.BufferGeometry = function () {
  4817. THREE.EventDispatcher.call( this );
  4818. this.id = THREE.GeometryIdCount ++;
  4819. // attributes
  4820. this.attributes = {};
  4821. // attributes typed arrays are kept only if dynamic flag is set
  4822. this.dynamic = false;
  4823. // offsets for chunks when using indexed elements
  4824. this.offsets = [];
  4825. // boundings
  4826. this.boundingBox = null;
  4827. this.boundingSphere = null;
  4828. this.hasTangents = false;
  4829. // for compatibility
  4830. this.morphTargets = [];
  4831. };
  4832. THREE.BufferGeometry.prototype = {
  4833. constructor : THREE.BufferGeometry,
  4834. applyMatrix: function ( matrix ) {
  4835. var positionArray;
  4836. var normalArray;
  4837. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  4838. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  4839. if ( positionArray !== undefined ) {
  4840. matrix.multiplyVector3Array( positionArray );
  4841. this.verticesNeedUpdate = true;
  4842. }
  4843. if ( normalArray !== undefined ) {
  4844. var normalMatrix = new THREE.Matrix3();
  4845. normalMatrix.getInverse( matrix ).transpose();
  4846. normalMatrix.multiplyVector3Array( normalArray );
  4847. this.normalizeNormals();
  4848. this.normalsNeedUpdate = true;
  4849. }
  4850. },
  4851. computeBoundingBox: function () {
  4852. if ( this.boundingBox === null ) {
  4853. this.boundingBox = new THREE.Box3();
  4854. }
  4855. var positions = this.attributes[ "position" ].array;
  4856. if ( positions ) {
  4857. var bb = this.boundingBox;
  4858. var x, y, z;
  4859. if( positions.length >= 3 ) {
  4860. bb.min.x = bb.max.x = positions[ 0 ];
  4861. bb.min.y = bb.max.y = positions[ 1 ];
  4862. bb.min.z = bb.max.z = positions[ 2 ];
  4863. }
  4864. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  4865. x = positions[ i ];
  4866. y = positions[ i + 1 ];
  4867. z = positions[ i + 2 ];
  4868. // bounding box
  4869. if ( x < bb.min.x ) {
  4870. bb.min.x = x;
  4871. } else if ( x > bb.max.x ) {
  4872. bb.max.x = x;
  4873. }
  4874. if ( y < bb.min.y ) {
  4875. bb.min.y = y;
  4876. } else if ( y > bb.max.y ) {
  4877. bb.max.y = y;
  4878. }
  4879. if ( z < bb.min.z ) {
  4880. bb.min.z = z;
  4881. } else if ( z > bb.max.z ) {
  4882. bb.max.z = z;
  4883. }
  4884. }
  4885. }
  4886. if ( positions === undefined || positions.length === 0 ) {
  4887. this.boundingBox.min.set( 0, 0, 0 );
  4888. this.boundingBox.max.set( 0, 0, 0 );
  4889. }
  4890. },
  4891. computeBoundingSphere: function () {
  4892. if ( this.boundingSphere === null ) {
  4893. this.boundingSphere = new THREE.Sphere();
  4894. }
  4895. var positions = this.attributes[ "position" ].array;
  4896. if ( positions ) {
  4897. var radiusSq, maxRadiusSq = 0;
  4898. var x, y, z;
  4899. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  4900. x = positions[ i ];
  4901. y = positions[ i + 1 ];
  4902. z = positions[ i + 2 ];
  4903. radiusSq = x * x + y * y + z * z;
  4904. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  4905. }
  4906. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  4907. }
  4908. },
  4909. computeVertexNormals: function () {
  4910. if ( this.attributes[ "position" ] ) {
  4911. var i, il;
  4912. var j, jl;
  4913. var nVertexElements = this.attributes[ "position" ].array.length;
  4914. if ( this.attributes[ "normal" ] === undefined ) {
  4915. this.attributes[ "normal" ] = {
  4916. itemSize: 3,
  4917. array: new Float32Array( nVertexElements ),
  4918. numItems: nVertexElements
  4919. };
  4920. } else {
  4921. // reset existing normals to zero
  4922. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  4923. this.attributes[ "normal" ].array[ i ] = 0;
  4924. }
  4925. }
  4926. var positions = this.attributes[ "position" ].array;
  4927. var normals = this.attributes[ "normal" ].array;
  4928. var vA, vB, vC, x, y, z,
  4929. pA = new THREE.Vector3(),
  4930. pB = new THREE.Vector3(),
  4931. pC = new THREE.Vector3(),
  4932. cb = new THREE.Vector3(),
  4933. ab = new THREE.Vector3();
  4934. // indexed elements
  4935. if ( this.attributes[ "index" ] ) {
  4936. var indices = this.attributes[ "index" ].array;
  4937. var offsets = this.offsets;
  4938. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4939. var start = offsets[ j ].start;
  4940. var count = offsets[ j ].count;
  4941. var index = offsets[ j ].index;
  4942. for ( i = start, il = start + count; i < il; i += 3 ) {
  4943. vA = index + indices[ i ];
  4944. vB = index + indices[ i + 1 ];
  4945. vC = index + indices[ i + 2 ];
  4946. x = positions[ vA * 3 ];
  4947. y = positions[ vA * 3 + 1 ];
  4948. z = positions[ vA * 3 + 2 ];
  4949. pA.set( x, y, z );
  4950. x = positions[ vB * 3 ];
  4951. y = positions[ vB * 3 + 1 ];
  4952. z = positions[ vB * 3 + 2 ];
  4953. pB.set( x, y, z );
  4954. x = positions[ vC * 3 ];
  4955. y = positions[ vC * 3 + 1 ];
  4956. z = positions[ vC * 3 + 2 ];
  4957. pC.set( x, y, z );
  4958. cb.subVectors( pC, pB );
  4959. ab.subVectors( pA, pB );
  4960. cb.cross( ab );
  4961. normals[ vA * 3 ] += cb.x;
  4962. normals[ vA * 3 + 1 ] += cb.y;
  4963. normals[ vA * 3 + 2 ] += cb.z;
  4964. normals[ vB * 3 ] += cb.x;
  4965. normals[ vB * 3 + 1 ] += cb.y;
  4966. normals[ vB * 3 + 2 ] += cb.z;
  4967. normals[ vC * 3 ] += cb.x;
  4968. normals[ vC * 3 + 1 ] += cb.y;
  4969. normals[ vC * 3 + 2 ] += cb.z;
  4970. }
  4971. }
  4972. // non-indexed elements (unconnected triangle soup)
  4973. } else {
  4974. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  4975. x = positions[ i ];
  4976. y = positions[ i + 1 ];
  4977. z = positions[ i + 2 ];
  4978. pA.set( x, y, z );
  4979. x = positions[ i + 3 ];
  4980. y = positions[ i + 4 ];
  4981. z = positions[ i + 5 ];
  4982. pB.set( x, y, z );
  4983. x = positions[ i + 6 ];
  4984. y = positions[ i + 7 ];
  4985. z = positions[ i + 8 ];
  4986. pC.set( x, y, z );
  4987. cb.subVectors( pC, pB );
  4988. ab.subVectors( pA, pB );
  4989. cb.cross( ab );
  4990. normals[ i ] = cb.x;
  4991. normals[ i + 1 ] = cb.y;
  4992. normals[ i + 2 ] = cb.z;
  4993. normals[ i + 3 ] = cb.x;
  4994. normals[ i + 4 ] = cb.y;
  4995. normals[ i + 5 ] = cb.z;
  4996. normals[ i + 6 ] = cb.x;
  4997. normals[ i + 7 ] = cb.y;
  4998. normals[ i + 8 ] = cb.z;
  4999. }
  5000. }
  5001. this.normalizeNormals();
  5002. this.normalsNeedUpdate = true;
  5003. }
  5004. },
  5005. normalizeNormals: function () {
  5006. var normals = this.attributes[ "normal" ].array;
  5007. var x, y, z, n;
  5008. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5009. x = normals[ i ];
  5010. y = normals[ i + 1 ];
  5011. z = normals[ i + 2 ];
  5012. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5013. normals[ i ] *= n;
  5014. normals[ i + 1 ] *= n;
  5015. normals[ i + 2 ] *= n;
  5016. }
  5017. },
  5018. computeTangents: function () {
  5019. // based on http://www.terathon.com/code/tangent.html
  5020. // (per vertex tangents)
  5021. if ( this.attributes[ "index" ] === undefined ||
  5022. this.attributes[ "position" ] === undefined ||
  5023. this.attributes[ "normal" ] === undefined ||
  5024. this.attributes[ "uv" ] === undefined ) {
  5025. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5026. return;
  5027. }
  5028. var indices = this.attributes[ "index" ].array;
  5029. var positions = this.attributes[ "position" ].array;
  5030. var normals = this.attributes[ "normal" ].array;
  5031. var uvs = this.attributes[ "uv" ].array;
  5032. var nVertices = positions.length / 3;
  5033. if ( this.attributes[ "tangent" ] === undefined ) {
  5034. var nTangentElements = 4 * nVertices;
  5035. this.attributes[ "tangent" ] = {
  5036. itemSize: 4,
  5037. array: new Float32Array( nTangentElements ),
  5038. numItems: nTangentElements
  5039. };
  5040. }
  5041. var tangents = this.attributes[ "tangent" ].array;
  5042. var tan1 = [], tan2 = [];
  5043. for ( var k = 0; k < nVertices; k ++ ) {
  5044. tan1[ k ] = new THREE.Vector3();
  5045. tan2[ k ] = new THREE.Vector3();
  5046. }
  5047. var xA, yA, zA,
  5048. xB, yB, zB,
  5049. xC, yC, zC,
  5050. uA, vA,
  5051. uB, vB,
  5052. uC, vC,
  5053. x1, x2, y1, y2, z1, z2,
  5054. s1, s2, t1, t2, r;
  5055. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5056. function handleTriangle( a, b, c ) {
  5057. xA = positions[ a * 3 ];
  5058. yA = positions[ a * 3 + 1 ];
  5059. zA = positions[ a * 3 + 2 ];
  5060. xB = positions[ b * 3 ];
  5061. yB = positions[ b * 3 + 1 ];
  5062. zB = positions[ b * 3 + 2 ];
  5063. xC = positions[ c * 3 ];
  5064. yC = positions[ c * 3 + 1 ];
  5065. zC = positions[ c * 3 + 2 ];
  5066. uA = uvs[ a * 2 ];
  5067. vA = uvs[ a * 2 + 1 ];
  5068. uB = uvs[ b * 2 ];
  5069. vB = uvs[ b * 2 + 1 ];
  5070. uC = uvs[ c * 2 ];
  5071. vC = uvs[ c * 2 + 1 ];
  5072. x1 = xB - xA;
  5073. x2 = xC - xA;
  5074. y1 = yB - yA;
  5075. y2 = yC - yA;
  5076. z1 = zB - zA;
  5077. z2 = zC - zA;
  5078. s1 = uB - uA;
  5079. s2 = uC - uA;
  5080. t1 = vB - vA;
  5081. t2 = vC - vA;
  5082. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5083. sdir.set(
  5084. ( t2 * x1 - t1 * x2 ) * r,
  5085. ( t2 * y1 - t1 * y2 ) * r,
  5086. ( t2 * z1 - t1 * z2 ) * r
  5087. );
  5088. tdir.set(
  5089. ( s1 * x2 - s2 * x1 ) * r,
  5090. ( s1 * y2 - s2 * y1 ) * r,
  5091. ( s1 * z2 - s2 * z1 ) * r
  5092. );
  5093. tan1[ a ].add( sdir );
  5094. tan1[ b ].add( sdir );
  5095. tan1[ c ].add( sdir );
  5096. tan2[ a ].add( tdir );
  5097. tan2[ b ].add( tdir );
  5098. tan2[ c ].add( tdir );
  5099. }
  5100. var i, il;
  5101. var j, jl;
  5102. var iA, iB, iC;
  5103. var offsets = this.offsets;
  5104. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5105. var start = offsets[ j ].start;
  5106. var count = offsets[ j ].count;
  5107. var index = offsets[ j ].index;
  5108. for ( i = start, il = start + count; i < il; i += 3 ) {
  5109. iA = index + indices[ i ];
  5110. iB = index + indices[ i + 1 ];
  5111. iC = index + indices[ i + 2 ];
  5112. handleTriangle( iA, iB, iC );
  5113. }
  5114. }
  5115. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5116. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5117. var w, t, test;
  5118. function handleVertex( v ) {
  5119. n.x = normals[ v * 3 ];
  5120. n.y = normals[ v * 3 + 1 ];
  5121. n.z = normals[ v * 3 + 2 ];
  5122. n2.copy( n );
  5123. t = tan1[ v ];
  5124. // Gram-Schmidt orthogonalize
  5125. tmp.copy( t );
  5126. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5127. // Calculate handedness
  5128. tmp2.crossVectors( n2, t );
  5129. test = tmp2.dot( tan2[ v ] );
  5130. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5131. tangents[ v * 4 ] = tmp.x;
  5132. tangents[ v * 4 + 1 ] = tmp.y;
  5133. tangents[ v * 4 + 2 ] = tmp.z;
  5134. tangents[ v * 4 + 3 ] = w;
  5135. }
  5136. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5137. var start = offsets[ j ].start;
  5138. var count = offsets[ j ].count;
  5139. var index = offsets[ j ].index;
  5140. for ( i = start, il = start + count; i < il; i += 3 ) {
  5141. iA = index + indices[ i ];
  5142. iB = index + indices[ i + 1 ];
  5143. iC = index + indices[ i + 2 ];
  5144. handleVertex( iA );
  5145. handleVertex( iB );
  5146. handleVertex( iC );
  5147. }
  5148. }
  5149. this.hasTangents = true;
  5150. this.tangentsNeedUpdate = true;
  5151. },
  5152. dispose: function () {
  5153. this.dispatchEvent( { type: 'dispose' } );
  5154. }
  5155. };
  5156. /**
  5157. * @author mrdoob / http://mrdoob.com/
  5158. * @author mikael emtinger / http://gomo.se/
  5159. * @author WestLangley / http://github.com/WestLangley
  5160. */
  5161. THREE.Camera = function () {
  5162. THREE.Object3D.call( this );
  5163. this.matrixWorldInverse = new THREE.Matrix4();
  5164. this.projectionMatrix = new THREE.Matrix4();
  5165. this.projectionMatrixInverse = new THREE.Matrix4();
  5166. };
  5167. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5168. THREE.Camera.prototype.lookAt = function () {
  5169. // This routine does not support cameras with rotated and/or translated parent(s)
  5170. var m1 = new THREE.Matrix4();
  5171. return function ( vector ) {
  5172. m1.lookAt( this.position, vector, this.up );
  5173. if ( this.useQuaternion === true ) {
  5174. this.quaternion.setFromRotationMatrix( m1 );
  5175. } else {
  5176. this.rotation.setEulerFromRotationMatrix( m1, this.eulerOrder );
  5177. }
  5178. };
  5179. }();
  5180. /**
  5181. * @author alteredq / http://alteredqualia.com/
  5182. */
  5183. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5184. THREE.Camera.call( this );
  5185. this.left = left;
  5186. this.right = right;
  5187. this.top = top;
  5188. this.bottom = bottom;
  5189. this.near = ( near !== undefined ) ? near : 0.1;
  5190. this.far = ( far !== undefined ) ? far : 2000;
  5191. this.updateProjectionMatrix();
  5192. };
  5193. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5194. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5195. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5196. };
  5197. /**
  5198. * @author mrdoob / http://mrdoob.com/
  5199. * @author greggman / http://games.greggman.com/
  5200. * @author zz85 / http://www.lab4games.net/zz85/blog
  5201. */
  5202. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5203. THREE.Camera.call( this );
  5204. this.fov = fov !== undefined ? fov : 50;
  5205. this.aspect = aspect !== undefined ? aspect : 1;
  5206. this.near = near !== undefined ? near : 0.1;
  5207. this.far = far !== undefined ? far : 2000;
  5208. this.updateProjectionMatrix();
  5209. };
  5210. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5211. /**
  5212. * Uses Focal Length (in mm) to estimate and set FOV
  5213. * 35mm (fullframe) camera is used if frame size is not specified;
  5214. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5215. */
  5216. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5217. if ( frameHeight === undefined ) frameHeight = 24;
  5218. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5219. this.updateProjectionMatrix();
  5220. }
  5221. /**
  5222. * Sets an offset in a larger frustum. This is useful for multi-window or
  5223. * multi-monitor/multi-machine setups.
  5224. *
  5225. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5226. * the monitors are in grid like this
  5227. *
  5228. * +---+---+---+
  5229. * | A | B | C |
  5230. * +---+---+---+
  5231. * | D | E | F |
  5232. * +---+---+---+
  5233. *
  5234. * then for each monitor you would call it like this
  5235. *
  5236. * var w = 1920;
  5237. * var h = 1080;
  5238. * var fullWidth = w * 3;
  5239. * var fullHeight = h * 2;
  5240. *
  5241. * --A--
  5242. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5243. * --B--
  5244. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5245. * --C--
  5246. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5247. * --D--
  5248. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5249. * --E--
  5250. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5251. * --F--
  5252. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5253. *
  5254. * Note there is no reason monitors have to be the same size or in a grid.
  5255. */
  5256. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5257. this.fullWidth = fullWidth;
  5258. this.fullHeight = fullHeight;
  5259. this.x = x;
  5260. this.y = y;
  5261. this.width = width;
  5262. this.height = height;
  5263. this.updateProjectionMatrix();
  5264. };
  5265. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5266. if ( this.fullWidth ) {
  5267. var aspect = this.fullWidth / this.fullHeight;
  5268. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5269. var bottom = -top;
  5270. var left = aspect * bottom;
  5271. var right = aspect * top;
  5272. var width = Math.abs( right - left );
  5273. var height = Math.abs( top - bottom );
  5274. this.projectionMatrix.makeFrustum(
  5275. left + this.x * width / this.fullWidth,
  5276. left + ( this.x + this.width ) * width / this.fullWidth,
  5277. top - ( this.y + this.height ) * height / this.fullHeight,
  5278. top - this.y * height / this.fullHeight,
  5279. this.near,
  5280. this.far
  5281. );
  5282. } else {
  5283. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5284. }
  5285. };
  5286. /**
  5287. * @author mrdoob / http://mrdoob.com/
  5288. * @author alteredq / http://alteredqualia.com/
  5289. */
  5290. THREE.Light = function ( hex ) {
  5291. THREE.Object3D.call( this );
  5292. this.color = new THREE.Color( hex );
  5293. };
  5294. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5295. /**
  5296. * @author mrdoob / http://mrdoob.com/
  5297. */
  5298. THREE.AmbientLight = function ( hex ) {
  5299. THREE.Light.call( this, hex );
  5300. };
  5301. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5302. /**
  5303. * @author MPanknin / http://www.redplant.de/
  5304. * @author alteredq / http://alteredqualia.com/
  5305. */
  5306. THREE.AreaLight = function ( hex, intensity ) {
  5307. THREE.Light.call( this, hex );
  5308. this.normal = new THREE.Vector3( 0, -1, 0 );
  5309. this.right = new THREE.Vector3( 1, 0, 0 );
  5310. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5311. this.width = 1.0;
  5312. this.height = 1.0;
  5313. this.constantAttenuation = 1.5;
  5314. this.linearAttenuation = 0.5;
  5315. this.quadraticAttenuation = 0.1;
  5316. };
  5317. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5318. /**
  5319. * @author mrdoob / http://mrdoob.com/
  5320. * @author alteredq / http://alteredqualia.com/
  5321. */
  5322. THREE.DirectionalLight = function ( hex, intensity ) {
  5323. THREE.Light.call( this, hex );
  5324. this.position = new THREE.Vector3( 0, 1, 0 );
  5325. this.target = new THREE.Object3D();
  5326. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5327. this.castShadow = false;
  5328. this.onlyShadow = false;
  5329. //
  5330. this.shadowCameraNear = 50;
  5331. this.shadowCameraFar = 5000;
  5332. this.shadowCameraLeft = -500;
  5333. this.shadowCameraRight = 500;
  5334. this.shadowCameraTop = 500;
  5335. this.shadowCameraBottom = -500;
  5336. this.shadowCameraVisible = false;
  5337. this.shadowBias = 0;
  5338. this.shadowDarkness = 0.5;
  5339. this.shadowMapWidth = 512;
  5340. this.shadowMapHeight = 512;
  5341. //
  5342. this.shadowCascade = false;
  5343. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5344. this.shadowCascadeCount = 2;
  5345. this.shadowCascadeBias = [ 0, 0, 0 ];
  5346. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5347. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5348. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5349. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5350. this.shadowCascadeArray = [];
  5351. //
  5352. this.shadowMap = null;
  5353. this.shadowMapSize = null;
  5354. this.shadowCamera = null;
  5355. this.shadowMatrix = null;
  5356. };
  5357. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5358. /**
  5359. * @author alteredq / http://alteredqualia.com/
  5360. */
  5361. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5362. THREE.Light.call( this, skyColorHex );
  5363. this.groundColor = new THREE.Color( groundColorHex );
  5364. this.position = new THREE.Vector3( 0, 100, 0 );
  5365. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5366. };
  5367. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5368. /**
  5369. * @author mrdoob / http://mrdoob.com/
  5370. */
  5371. THREE.PointLight = function ( hex, intensity, distance ) {
  5372. THREE.Light.call( this, hex );
  5373. this.position = new THREE.Vector3( 0, 0, 0 );
  5374. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5375. this.distance = ( distance !== undefined ) ? distance : 0;
  5376. };
  5377. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5378. /**
  5379. * @author alteredq / http://alteredqualia.com/
  5380. */
  5381. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5382. THREE.Light.call( this, hex );
  5383. this.position = new THREE.Vector3( 0, 1, 0 );
  5384. this.target = new THREE.Object3D();
  5385. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5386. this.distance = ( distance !== undefined ) ? distance : 0;
  5387. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  5388. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5389. this.castShadow = false;
  5390. this.onlyShadow = false;
  5391. //
  5392. this.shadowCameraNear = 50;
  5393. this.shadowCameraFar = 5000;
  5394. this.shadowCameraFov = 50;
  5395. this.shadowCameraVisible = false;
  5396. this.shadowBias = 0;
  5397. this.shadowDarkness = 0.5;
  5398. this.shadowMapWidth = 512;
  5399. this.shadowMapHeight = 512;
  5400. //
  5401. this.shadowMap = null;
  5402. this.shadowMapSize = null;
  5403. this.shadowCamera = null;
  5404. this.shadowMatrix = null;
  5405. };
  5406. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  5407. /**
  5408. * @author alteredq / http://alteredqualia.com/
  5409. */
  5410. THREE.Loader = function ( showStatus ) {
  5411. this.showStatus = showStatus;
  5412. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  5413. this.onLoadStart = function () {};
  5414. this.onLoadProgress = function () {};
  5415. this.onLoadComplete = function () {};
  5416. };
  5417. THREE.Loader.prototype = {
  5418. constructor: THREE.Loader,
  5419. crossOrigin: 'anonymous',
  5420. addStatusElement: function () {
  5421. var e = document.createElement( "div" );
  5422. e.style.position = "absolute";
  5423. e.style.right = "0px";
  5424. e.style.top = "0px";
  5425. e.style.fontSize = "0.8em";
  5426. e.style.textAlign = "left";
  5427. e.style.background = "rgba(0,0,0,0.25)";
  5428. e.style.color = "#fff";
  5429. e.style.width = "120px";
  5430. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  5431. e.style.zIndex = 1000;
  5432. e.innerHTML = "Loading ...";
  5433. return e;
  5434. },
  5435. updateProgress: function ( progress ) {
  5436. var message = "Loaded ";
  5437. if ( progress.total ) {
  5438. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  5439. } else {
  5440. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  5441. }
  5442. this.statusDomElement.innerHTML = message;
  5443. },
  5444. extractUrlBase: function ( url ) {
  5445. var parts = url.split( '/' );
  5446. parts.pop();
  5447. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  5448. },
  5449. initMaterials: function ( materials, texturePath ) {
  5450. var array = [];
  5451. for ( var i = 0; i < materials.length; ++ i ) {
  5452. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  5453. }
  5454. return array;
  5455. },
  5456. needsTangents: function ( materials ) {
  5457. for( var i = 0, il = materials.length; i < il; i ++ ) {
  5458. var m = materials[ i ];
  5459. if ( m instanceof THREE.ShaderMaterial ) return true;
  5460. }
  5461. return false;
  5462. },
  5463. createMaterial: function ( m, texturePath ) {
  5464. var _this = this;
  5465. function is_pow2( n ) {
  5466. var l = Math.log( n ) / Math.LN2;
  5467. return Math.floor( l ) == l;
  5468. }
  5469. function nearest_pow2( n ) {
  5470. var l = Math.log( n ) / Math.LN2;
  5471. return Math.pow( 2, Math.round( l ) );
  5472. }
  5473. function load_image( where, url ) {
  5474. var image = new Image();
  5475. image.onload = function () {
  5476. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  5477. var width = nearest_pow2( this.width );
  5478. var height = nearest_pow2( this.height );
  5479. where.image.width = width;
  5480. where.image.height = height;
  5481. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  5482. } else {
  5483. where.image = this;
  5484. }
  5485. where.needsUpdate = true;
  5486. };
  5487. image.crossOrigin = _this.crossOrigin;
  5488. image.src = url;
  5489. }
  5490. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  5491. var isCompressed = /\.dds$/i.test( sourceFile );
  5492. var fullPath = texturePath + "/" + sourceFile;
  5493. if ( isCompressed ) {
  5494. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  5495. where[ name ] = texture;
  5496. } else {
  5497. var texture = document.createElement( 'canvas' );
  5498. where[ name ] = new THREE.Texture( texture );
  5499. }
  5500. where[ name ].sourceFile = sourceFile;
  5501. if( repeat ) {
  5502. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5503. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5504. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5505. }
  5506. if ( offset ) {
  5507. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5508. }
  5509. if ( wrap ) {
  5510. var wrapMap = {
  5511. "repeat": THREE.RepeatWrapping,
  5512. "mirror": THREE.MirroredRepeatWrapping
  5513. }
  5514. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5515. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5516. }
  5517. if ( anisotropy ) {
  5518. where[ name ].anisotropy = anisotropy;
  5519. }
  5520. if ( ! isCompressed ) {
  5521. load_image( where[ name ], fullPath );
  5522. }
  5523. }
  5524. function rgb2hex( rgb ) {
  5525. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5526. }
  5527. // defaults
  5528. var mtype = "MeshLambertMaterial";
  5529. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5530. // parameters from model file
  5531. if ( m.shading ) {
  5532. var shading = m.shading.toLowerCase();
  5533. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5534. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5535. }
  5536. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5537. mpars.blending = THREE[ m.blending ];
  5538. }
  5539. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5540. mpars.transparent = m.transparent;
  5541. }
  5542. if ( m.depthTest !== undefined ) {
  5543. mpars.depthTest = m.depthTest;
  5544. }
  5545. if ( m.depthWrite !== undefined ) {
  5546. mpars.depthWrite = m.depthWrite;
  5547. }
  5548. if ( m.visible !== undefined ) {
  5549. mpars.visible = m.visible;
  5550. }
  5551. if ( m.flipSided !== undefined ) {
  5552. mpars.side = THREE.BackSide;
  5553. }
  5554. if ( m.doubleSided !== undefined ) {
  5555. mpars.side = THREE.DoubleSide;
  5556. }
  5557. if ( m.wireframe !== undefined ) {
  5558. mpars.wireframe = m.wireframe;
  5559. }
  5560. if ( m.vertexColors !== undefined ) {
  5561. if ( m.vertexColors === "face" ) {
  5562. mpars.vertexColors = THREE.FaceColors;
  5563. } else if ( m.vertexColors ) {
  5564. mpars.vertexColors = THREE.VertexColors;
  5565. }
  5566. }
  5567. // colors
  5568. if ( m.colorDiffuse ) {
  5569. mpars.color = rgb2hex( m.colorDiffuse );
  5570. } else if ( m.DbgColor ) {
  5571. mpars.color = m.DbgColor;
  5572. }
  5573. if ( m.colorSpecular ) {
  5574. mpars.specular = rgb2hex( m.colorSpecular );
  5575. }
  5576. if ( m.colorAmbient ) {
  5577. mpars.ambient = rgb2hex( m.colorAmbient );
  5578. }
  5579. // modifiers
  5580. if ( m.transparency ) {
  5581. mpars.opacity = m.transparency;
  5582. }
  5583. if ( m.specularCoef ) {
  5584. mpars.shininess = m.specularCoef;
  5585. }
  5586. // textures
  5587. if ( m.mapDiffuse && texturePath ) {
  5588. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  5589. }
  5590. if ( m.mapLight && texturePath ) {
  5591. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  5592. }
  5593. if ( m.mapBump && texturePath ) {
  5594. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  5595. }
  5596. if ( m.mapNormal && texturePath ) {
  5597. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  5598. }
  5599. if ( m.mapSpecular && texturePath ) {
  5600. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  5601. }
  5602. //
  5603. if ( m.mapBumpScale ) {
  5604. mpars.bumpScale = m.mapBumpScale;
  5605. }
  5606. // special case for normal mapped material
  5607. if ( m.mapNormal ) {
  5608. var shader = THREE.ShaderLib[ "normalmap" ];
  5609. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5610. uniforms[ "tNormal" ].value = mpars.normalMap;
  5611. if ( m.mapNormalFactor ) {
  5612. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5613. }
  5614. if ( mpars.map ) {
  5615. uniforms[ "tDiffuse" ].value = mpars.map;
  5616. uniforms[ "enableDiffuse" ].value = true;
  5617. }
  5618. if ( mpars.specularMap ) {
  5619. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5620. uniforms[ "enableSpecular" ].value = true;
  5621. }
  5622. if ( mpars.lightMap ) {
  5623. uniforms[ "tAO" ].value = mpars.lightMap;
  5624. uniforms[ "enableAO" ].value = true;
  5625. }
  5626. // for the moment don't handle displacement texture
  5627. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5628. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5629. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5630. uniforms[ "uShininess" ].value = mpars.shininess;
  5631. if ( mpars.opacity !== undefined ) {
  5632. uniforms[ "uOpacity" ].value = mpars.opacity;
  5633. }
  5634. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5635. var material = new THREE.ShaderMaterial( parameters );
  5636. if ( mpars.transparent ) {
  5637. material.transparent = true;
  5638. }
  5639. } else {
  5640. var material = new THREE[ mtype ]( mpars );
  5641. }
  5642. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5643. return material;
  5644. }
  5645. };
  5646. /**
  5647. * @author mrdoob / http://mrdoob.com/
  5648. */
  5649. THREE.ImageLoader = function () {
  5650. THREE.EventDispatcher.call( this );
  5651. this.crossOrigin = null;
  5652. };
  5653. THREE.ImageLoader.prototype = {
  5654. constructor: THREE.ImageLoader,
  5655. load: function ( url, image ) {
  5656. var scope = this;
  5657. if ( image === undefined ) image = new Image();
  5658. image.addEventListener( 'load', function () {
  5659. scope.dispatchEvent( { type: 'load', content: image } );
  5660. }, false );
  5661. image.addEventListener( 'error', function () {
  5662. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5663. }, false );
  5664. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5665. image.src = url;
  5666. }
  5667. }
  5668. /**
  5669. * @author mrdoob / http://mrdoob.com/
  5670. * @author alteredq / http://alteredqualia.com/
  5671. */
  5672. THREE.JSONLoader = function ( showStatus ) {
  5673. THREE.Loader.call( this, showStatus );
  5674. this.withCredentials = false;
  5675. };
  5676. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  5677. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  5678. var scope = this;
  5679. // todo: unify load API to for easier SceneLoader use
  5680. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  5681. this.onLoadStart();
  5682. this.loadAjaxJSON( this, url, callback, texturePath );
  5683. };
  5684. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  5685. var xhr = new XMLHttpRequest();
  5686. var length = 0;
  5687. xhr.onreadystatechange = function () {
  5688. if ( xhr.readyState === xhr.DONE ) {
  5689. if ( xhr.status === 200 || xhr.status === 0 ) {
  5690. if ( xhr.responseText ) {
  5691. var json = JSON.parse( xhr.responseText );
  5692. context.createModel( json, callback, texturePath );
  5693. } else {
  5694. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  5695. }
  5696. // in context of more complex asset initialization
  5697. // do not block on single failed file
  5698. // maybe should go even one more level up
  5699. context.onLoadComplete();
  5700. } else {
  5701. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5702. }
  5703. } else if ( xhr.readyState === xhr.LOADING ) {
  5704. if ( callbackProgress ) {
  5705. if ( length === 0 ) {
  5706. length = xhr.getResponseHeader( "Content-Length" );
  5707. }
  5708. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5709. }
  5710. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  5711. length = xhr.getResponseHeader( "Content-Length" );
  5712. }
  5713. };
  5714. xhr.open( "GET", url, true );
  5715. xhr.withCredentials = this.withCredentials;
  5716. xhr.send( null );
  5717. };
  5718. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  5719. var scope = this,
  5720. geometry = new THREE.Geometry(),
  5721. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  5722. parseModel( scale );
  5723. parseSkin();
  5724. parseMorphing( scale );
  5725. geometry.computeCentroids();
  5726. geometry.computeFaceNormals();
  5727. function parseModel( scale ) {
  5728. function isBitSet( value, position ) {
  5729. return value & ( 1 << position );
  5730. }
  5731. var i, j, fi,
  5732. offset, zLength, nVertices,
  5733. colorIndex, normalIndex, uvIndex, materialIndex,
  5734. type,
  5735. isQuad,
  5736. hasMaterial,
  5737. hasFaceUv, hasFaceVertexUv,
  5738. hasFaceNormal, hasFaceVertexNormal,
  5739. hasFaceColor, hasFaceVertexColor,
  5740. vertex, face, color, normal,
  5741. uvLayer, uvs, u, v,
  5742. faces = json.faces,
  5743. vertices = json.vertices,
  5744. normals = json.normals,
  5745. colors = json.colors,
  5746. nUvLayers = 0;
  5747. // disregard empty arrays
  5748. for ( i = 0; i < json.uvs.length; i++ ) {
  5749. if ( json.uvs[ i ].length ) nUvLayers ++;
  5750. }
  5751. for ( i = 0; i < nUvLayers; i++ ) {
  5752. geometry.faceUvs[ i ] = [];
  5753. geometry.faceVertexUvs[ i ] = [];
  5754. }
  5755. offset = 0;
  5756. zLength = vertices.length;
  5757. while ( offset < zLength ) {
  5758. vertex = new THREE.Vector3();
  5759. vertex.x = vertices[ offset ++ ] * scale;
  5760. vertex.y = vertices[ offset ++ ] * scale;
  5761. vertex.z = vertices[ offset ++ ] * scale;
  5762. geometry.vertices.push( vertex );
  5763. }
  5764. offset = 0;
  5765. zLength = faces.length;
  5766. while ( offset < zLength ) {
  5767. type = faces[ offset ++ ];
  5768. isQuad = isBitSet( type, 0 );
  5769. hasMaterial = isBitSet( type, 1 );
  5770. hasFaceUv = isBitSet( type, 2 );
  5771. hasFaceVertexUv = isBitSet( type, 3 );
  5772. hasFaceNormal = isBitSet( type, 4 );
  5773. hasFaceVertexNormal = isBitSet( type, 5 );
  5774. hasFaceColor = isBitSet( type, 6 );
  5775. hasFaceVertexColor = isBitSet( type, 7 );
  5776. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5777. if ( isQuad ) {
  5778. face = new THREE.Face4();
  5779. face.a = faces[ offset ++ ];
  5780. face.b = faces[ offset ++ ];
  5781. face.c = faces[ offset ++ ];
  5782. face.d = faces[ offset ++ ];
  5783. nVertices = 4;
  5784. } else {
  5785. face = new THREE.Face3();
  5786. face.a = faces[ offset ++ ];
  5787. face.b = faces[ offset ++ ];
  5788. face.c = faces[ offset ++ ];
  5789. nVertices = 3;
  5790. }
  5791. if ( hasMaterial ) {
  5792. materialIndex = faces[ offset ++ ];
  5793. face.materialIndex = materialIndex;
  5794. }
  5795. // to get face <=> uv index correspondence
  5796. fi = geometry.faces.length;
  5797. if ( hasFaceUv ) {
  5798. for ( i = 0; i < nUvLayers; i++ ) {
  5799. uvLayer = json.uvs[ i ];
  5800. uvIndex = faces[ offset ++ ];
  5801. u = uvLayer[ uvIndex * 2 ];
  5802. v = uvLayer[ uvIndex * 2 + 1 ];
  5803. geometry.faceUvs[ i ][ fi ] = new THREE.Vector2( u, v );
  5804. }
  5805. }
  5806. if ( hasFaceVertexUv ) {
  5807. for ( i = 0; i < nUvLayers; i++ ) {
  5808. uvLayer = json.uvs[ i ];
  5809. uvs = [];
  5810. for ( j = 0; j < nVertices; j ++ ) {
  5811. uvIndex = faces[ offset ++ ];
  5812. u = uvLayer[ uvIndex * 2 ];
  5813. v = uvLayer[ uvIndex * 2 + 1 ];
  5814. uvs[ j ] = new THREE.Vector2( u, v );
  5815. }
  5816. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5817. }
  5818. }
  5819. if ( hasFaceNormal ) {
  5820. normalIndex = faces[ offset ++ ] * 3;
  5821. normal = new THREE.Vector3();
  5822. normal.x = normals[ normalIndex ++ ];
  5823. normal.y = normals[ normalIndex ++ ];
  5824. normal.z = normals[ normalIndex ];
  5825. face.normal = normal;
  5826. }
  5827. if ( hasFaceVertexNormal ) {
  5828. for ( i = 0; i < nVertices; i++ ) {
  5829. normalIndex = faces[ offset ++ ] * 3;
  5830. normal = new THREE.Vector3();
  5831. normal.x = normals[ normalIndex ++ ];
  5832. normal.y = normals[ normalIndex ++ ];
  5833. normal.z = normals[ normalIndex ];
  5834. face.vertexNormals.push( normal );
  5835. }
  5836. }
  5837. if ( hasFaceColor ) {
  5838. colorIndex = faces[ offset ++ ];
  5839. color = new THREE.Color( colors[ colorIndex ] );
  5840. face.color = color;
  5841. }
  5842. if ( hasFaceVertexColor ) {
  5843. for ( i = 0; i < nVertices; i++ ) {
  5844. colorIndex = faces[ offset ++ ];
  5845. color = new THREE.Color( colors[ colorIndex ] );
  5846. face.vertexColors.push( color );
  5847. }
  5848. }
  5849. geometry.faces.push( face );
  5850. }
  5851. };
  5852. function parseSkin() {
  5853. var i, l, x, y, z, w, a, b, c, d;
  5854. if ( json.skinWeights ) {
  5855. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  5856. x = json.skinWeights[ i ];
  5857. y = json.skinWeights[ i + 1 ];
  5858. z = 0;
  5859. w = 0;
  5860. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5861. }
  5862. }
  5863. if ( json.skinIndices ) {
  5864. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  5865. a = json.skinIndices[ i ];
  5866. b = json.skinIndices[ i + 1 ];
  5867. c = 0;
  5868. d = 0;
  5869. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5870. }
  5871. }
  5872. geometry.bones = json.bones;
  5873. geometry.animation = json.animation;
  5874. };
  5875. function parseMorphing( scale ) {
  5876. if ( json.morphTargets !== undefined ) {
  5877. var i, l, v, vl, dstVertices, srcVertices;
  5878. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  5879. geometry.morphTargets[ i ] = {};
  5880. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  5881. geometry.morphTargets[ i ].vertices = [];
  5882. dstVertices = geometry.morphTargets[ i ].vertices;
  5883. srcVertices = json.morphTargets [ i ].vertices;
  5884. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5885. var vertex = new THREE.Vector3();
  5886. vertex.x = srcVertices[ v ] * scale;
  5887. vertex.y = srcVertices[ v + 1 ] * scale;
  5888. vertex.z = srcVertices[ v + 2 ] * scale;
  5889. dstVertices.push( vertex );
  5890. }
  5891. }
  5892. }
  5893. if ( json.morphColors !== undefined ) {
  5894. var i, l, c, cl, dstColors, srcColors, color;
  5895. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  5896. geometry.morphColors[ i ] = {};
  5897. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  5898. geometry.morphColors[ i ].colors = [];
  5899. dstColors = geometry.morphColors[ i ].colors;
  5900. srcColors = json.morphColors [ i ].colors;
  5901. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5902. color = new THREE.Color( 0xffaa00 );
  5903. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5904. dstColors.push( color );
  5905. }
  5906. }
  5907. }
  5908. };
  5909. var materials = this.initMaterials( json.materials, texturePath );
  5910. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  5911. callback( geometry, materials );
  5912. };
  5913. /**
  5914. * @author mrdoob / http://mrdoob.com/
  5915. */
  5916. THREE.LoadingMonitor = function () {
  5917. THREE.EventDispatcher.call( this );
  5918. var scope = this;
  5919. var loaded = 0;
  5920. var total = 0;
  5921. var onLoad = function ( event ) {
  5922. loaded ++;
  5923. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  5924. if ( loaded === total ) {
  5925. scope.dispatchEvent( { type: 'load' } );
  5926. }
  5927. };
  5928. this.add = function ( loader ) {
  5929. total ++;
  5930. loader.addEventListener( 'load', onLoad, false );
  5931. };
  5932. };
  5933. /**
  5934. * @author alteredq / http://alteredqualia.com/
  5935. */
  5936. THREE.SceneLoader = function () {
  5937. this.onLoadStart = function () {};
  5938. this.onLoadProgress = function() {};
  5939. this.onLoadComplete = function () {};
  5940. this.callbackSync = function () {};
  5941. this.callbackProgress = function () {};
  5942. this.geometryHandlerMap = {};
  5943. this.hierarchyHandlerMap = {};
  5944. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  5945. };
  5946. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5947. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  5948. var scope = this;
  5949. var xhr = new XMLHttpRequest();
  5950. xhr.onreadystatechange = function () {
  5951. if ( xhr.readyState === 4 ) {
  5952. if ( xhr.status === 200 || xhr.status === 0 ) {
  5953. var json = JSON.parse( xhr.responseText );
  5954. scope.parse( json, callbackFinished, url );
  5955. } else {
  5956. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5957. }
  5958. }
  5959. };
  5960. xhr.open( "GET", url, true );
  5961. xhr.send( null );
  5962. };
  5963. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  5964. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5965. };
  5966. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  5967. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5968. };
  5969. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  5970. var scope = this;
  5971. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  5972. var geometry, material, camera, fog,
  5973. texture, images, color,
  5974. light, hex, intensity,
  5975. counter_models, counter_textures,
  5976. total_models, total_textures,
  5977. result;
  5978. var target_array = [];
  5979. var data = json;
  5980. // async geometry loaders
  5981. for ( var typeID in this.geometryHandlerMap ) {
  5982. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  5983. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5984. }
  5985. // async hierachy loaders
  5986. for ( var typeID in this.hierarchyHandlerMap ) {
  5987. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  5988. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5989. }
  5990. counter_models = 0;
  5991. counter_textures = 0;
  5992. result = {
  5993. scene: new THREE.Scene(),
  5994. geometries: {},
  5995. face_materials: {},
  5996. materials: {},
  5997. textures: {},
  5998. objects: {},
  5999. cameras: {},
  6000. lights: {},
  6001. fogs: {},
  6002. empties: {},
  6003. groups: {}
  6004. };
  6005. if ( data.transform ) {
  6006. var position = data.transform.position,
  6007. rotation = data.transform.rotation,
  6008. scale = data.transform.scale;
  6009. if ( position )
  6010. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  6011. if ( rotation )
  6012. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  6013. if ( scale )
  6014. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  6015. if ( position || rotation || scale ) {
  6016. result.scene.updateMatrix();
  6017. result.scene.updateMatrixWorld();
  6018. }
  6019. }
  6020. function get_url( source_url, url_type ) {
  6021. if ( url_type == "relativeToHTML" ) {
  6022. return source_url;
  6023. } else {
  6024. return urlBase + "/" + source_url;
  6025. }
  6026. };
  6027. // toplevel loader function, delegates to handle_children
  6028. function handle_objects() {
  6029. handle_children( result.scene, data.objects );
  6030. }
  6031. // handle all the children from the loaded json and attach them to given parent
  6032. function handle_children( parent, children ) {
  6033. var mat, dst, pos, rot, scl, quat;
  6034. for ( var objID in children ) {
  6035. // check by id if child has already been handled,
  6036. // if not, create new object
  6037. if ( result.objects[ objID ] === undefined ) {
  6038. var objJSON = children[ objID ];
  6039. var object = null;
  6040. // meshes
  6041. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlerMap ) ) {
  6042. if ( objJSON.loading === undefined ) {
  6043. var reservedTypes = { "type": 1, "url": 1, "material": 1,
  6044. "position": 1, "rotation": 1, "scale" : 1,
  6045. "visible": 1, "children": 1, "userData": 1,
  6046. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1 };
  6047. var loaderParameters = {};
  6048. for ( var parType in objJSON ) {
  6049. if ( ! ( parType in reservedTypes ) ) {
  6050. loaderParameters[ parType ] = objJSON[ parType ];
  6051. }
  6052. }
  6053. material = result.materials[ objJSON.material ];
  6054. objJSON.loading = true;
  6055. var loader = scope.hierarchyHandlerMap[ objJSON.type ][ "loaderObject" ];
  6056. // ColladaLoader
  6057. if ( loader.options ) {
  6058. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  6059. // UTF8Loader
  6060. // OBJLoader
  6061. } else {
  6062. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  6063. }
  6064. }
  6065. } else if ( objJSON.geometry !== undefined ) {
  6066. geometry = result.geometries[ objJSON.geometry ];
  6067. // geometry already loaded
  6068. if ( geometry ) {
  6069. var needsTangents = false;
  6070. material = result.materials[ objJSON.material ];
  6071. needsTangents = material instanceof THREE.ShaderMaterial;
  6072. pos = objJSON.position;
  6073. rot = objJSON.rotation;
  6074. scl = objJSON.scale;
  6075. mat = objJSON.matrix;
  6076. quat = objJSON.quaternion;
  6077. // use materials from the model file
  6078. // if there is no material specified in the object
  6079. if ( ! objJSON.material ) {
  6080. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6081. }
  6082. // use materials from the model file
  6083. // if there is just empty face material
  6084. // (must create new material as each model has its own face material)
  6085. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  6086. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6087. }
  6088. if ( material instanceof THREE.MeshFaceMaterial ) {
  6089. for ( var i = 0; i < material.materials.length; i ++ ) {
  6090. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  6091. }
  6092. }
  6093. if ( needsTangents ) {
  6094. geometry.computeTangents();
  6095. }
  6096. if ( objJSON.skin ) {
  6097. object = new THREE.SkinnedMesh( geometry, material );
  6098. } else if ( objJSON.morph ) {
  6099. object = new THREE.MorphAnimMesh( geometry, material );
  6100. if ( objJSON.duration !== undefined ) {
  6101. object.duration = objJSON.duration;
  6102. }
  6103. if ( objJSON.time !== undefined ) {
  6104. object.time = objJSON.time;
  6105. }
  6106. if ( objJSON.mirroredLoop !== undefined ) {
  6107. object.mirroredLoop = objJSON.mirroredLoop;
  6108. }
  6109. if ( material.morphNormals ) {
  6110. geometry.computeMorphNormals();
  6111. }
  6112. } else {
  6113. object = new THREE.Mesh( geometry, material );
  6114. }
  6115. object.name = objID;
  6116. if ( mat ) {
  6117. object.matrixAutoUpdate = false;
  6118. object.matrix.set(
  6119. mat[0], mat[1], mat[2], mat[3],
  6120. mat[4], mat[5], mat[6], mat[7],
  6121. mat[8], mat[9], mat[10], mat[11],
  6122. mat[12], mat[13], mat[14], mat[15]
  6123. );
  6124. } else {
  6125. object.position.set( pos[0], pos[1], pos[2] );
  6126. if ( quat ) {
  6127. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6128. object.useQuaternion = true;
  6129. } else {
  6130. object.rotation.set( rot[0], rot[1], rot[2] );
  6131. }
  6132. object.scale.set( scl[0], scl[1], scl[2] );
  6133. }
  6134. object.visible = objJSON.visible;
  6135. object.castShadow = objJSON.castShadow;
  6136. object.receiveShadow = objJSON.receiveShadow;
  6137. parent.add( object );
  6138. result.objects[ objID ] = object;
  6139. }
  6140. // lights
  6141. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  6142. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  6143. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  6144. if ( objJSON.type === "DirectionalLight" ) {
  6145. pos = objJSON.direction;
  6146. light = new THREE.DirectionalLight( hex, intensity );
  6147. light.position.set( pos[0], pos[1], pos[2] );
  6148. if ( objJSON.target ) {
  6149. target_array.push( { "object": light, "targetName" : objJSON.target } );
  6150. // kill existing default target
  6151. // otherwise it gets added to scene when parent gets added
  6152. light.target = null;
  6153. }
  6154. } else if ( objJSON.type === "PointLight" ) {
  6155. pos = objJSON.position;
  6156. dst = objJSON.distance;
  6157. light = new THREE.PointLight( hex, intensity, dst );
  6158. light.position.set( pos[0], pos[1], pos[2] );
  6159. } else if ( objJSON.type === "AmbientLight" ) {
  6160. light = new THREE.AmbientLight( hex );
  6161. }
  6162. parent.add( light );
  6163. light.name = objID;
  6164. result.lights[ objID ] = light;
  6165. result.objects[ objID ] = light;
  6166. // cameras
  6167. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  6168. if ( objJSON.type === "PerspectiveCamera" ) {
  6169. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  6170. } else if ( objJSON.type === "OrthographicCamera" ) {
  6171. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  6172. }
  6173. pos = objJSON.position;
  6174. camera.position.set( pos[0], pos[1], pos[2] );
  6175. parent.add( camera );
  6176. camera.name = objID;
  6177. result.cameras[ objID ] = camera;
  6178. result.objects[ objID ] = camera;
  6179. // pure Object3D
  6180. } else {
  6181. pos = objJSON.position;
  6182. rot = objJSON.rotation;
  6183. scl = objJSON.scale;
  6184. quat = objJSON.quaternion;
  6185. object = new THREE.Object3D();
  6186. object.name = objID;
  6187. object.position.set( pos[0], pos[1], pos[2] );
  6188. if ( quat ) {
  6189. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6190. object.useQuaternion = true;
  6191. } else {
  6192. object.rotation.set( rot[0], rot[1], rot[2] );
  6193. }
  6194. object.scale.set( scl[0], scl[1], scl[2] );
  6195. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  6196. parent.add( object );
  6197. result.objects[ objID ] = object;
  6198. result.empties[ objID ] = object;
  6199. }
  6200. if ( object ) {
  6201. if ( objJSON.userData !== undefined ) {
  6202. for ( var key in objJSON.userData ) {
  6203. var value = objJSON.userData[ key ];
  6204. object.userData[ key ] = value;
  6205. }
  6206. }
  6207. if ( objJSON.groups !== undefined ) {
  6208. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  6209. var groupID = objJSON.groups[ i ];
  6210. if ( result.groups[ groupID ] === undefined ) {
  6211. result.groups[ groupID ] = [];
  6212. }
  6213. result.groups[ groupID ].push( objID );
  6214. }
  6215. }
  6216. if ( objJSON.children !== undefined ) {
  6217. handle_children( object, objJSON.children );
  6218. }
  6219. }
  6220. }
  6221. }
  6222. };
  6223. function handle_mesh( geo, mat, id ) {
  6224. result.geometries[ id ] = geo;
  6225. result.face_materials[ id ] = mat;
  6226. handle_objects();
  6227. };
  6228. function handle_hierarchy( node, id, parent, material, obj ) {
  6229. var p = obj.position;
  6230. var r = obj.rotation;
  6231. var q = obj.quaternion;
  6232. var s = obj.scale;
  6233. node.position.set( p[0], p[1], p[2] );
  6234. if ( q ) {
  6235. node.quaternion.set( q[0], q[1], q[2], q[3] );
  6236. node.useQuaternion = true;
  6237. } else {
  6238. node.rotation.set( r[0], r[1], r[2] );
  6239. }
  6240. node.scale.set( s[0], s[1], s[2] );
  6241. // override children materials
  6242. // if object material was specified in JSON explicitly
  6243. if ( material ) {
  6244. node.traverse( function ( child ) {
  6245. child.material = material;
  6246. } );
  6247. }
  6248. // override children visibility
  6249. // with root node visibility as specified in JSON
  6250. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  6251. node.traverse( function ( child ) {
  6252. child.visible = visible;
  6253. } );
  6254. parent.add( node );
  6255. node.name = id;
  6256. result.objects[ id ] = node;
  6257. handle_objects();
  6258. };
  6259. function create_callback_geometry( id ) {
  6260. return function( geo, mat ) {
  6261. handle_mesh( geo, mat, id );
  6262. counter_models -= 1;
  6263. scope.onLoadComplete();
  6264. async_callback_gate();
  6265. }
  6266. };
  6267. function create_callback_hierachy( id, parent, material, obj ) {
  6268. return function( event ) {
  6269. var result;
  6270. // loaders which use EventDispatcher
  6271. if ( event.content ) {
  6272. result = event.content;
  6273. // ColladaLoader
  6274. } else if ( event.dae ) {
  6275. result = event.scene;
  6276. // UTF8Loader
  6277. } else {
  6278. result = event;
  6279. }
  6280. handle_hierarchy( result, id, parent, material, obj );
  6281. counter_models -= 1;
  6282. scope.onLoadComplete();
  6283. async_callback_gate();
  6284. }
  6285. };
  6286. function create_callback_embed( id ) {
  6287. return function( geo, mat ) {
  6288. result.geometries[ id ] = geo;
  6289. result.face_materials[ id ] = mat;
  6290. }
  6291. };
  6292. function async_callback_gate() {
  6293. var progress = {
  6294. totalModels : total_models,
  6295. totalTextures : total_textures,
  6296. loadedModels : total_models - counter_models,
  6297. loadedTextures : total_textures - counter_textures
  6298. };
  6299. scope.callbackProgress( progress, result );
  6300. scope.onLoadProgress();
  6301. if ( counter_models === 0 && counter_textures === 0 ) {
  6302. finalize();
  6303. callbackFinished( result );
  6304. }
  6305. };
  6306. function finalize() {
  6307. // take care of targets which could be asynchronously loaded objects
  6308. for ( var i = 0; i < target_array.length; i ++ ) {
  6309. var ta = target_array[ i ];
  6310. var target = result.objects[ ta.targetName ];
  6311. if ( target ) {
  6312. ta.object.target = target;
  6313. } else {
  6314. // if there was error and target of specified name doesn't exist in the scene file
  6315. // create instead dummy target
  6316. // (target must be added to scene explicitly as parent is already added)
  6317. ta.object.target = new THREE.Object3D();
  6318. result.scene.add( ta.object.target );
  6319. }
  6320. ta.object.target.userData.targetInverse = ta.object;
  6321. }
  6322. };
  6323. var callbackTexture = function ( count ) {
  6324. counter_textures -= count;
  6325. async_callback_gate();
  6326. scope.onLoadComplete();
  6327. };
  6328. // must use this instead of just directly calling callbackTexture
  6329. // because of closure in the calling context loop
  6330. var generateTextureCallback = function ( count ) {
  6331. return function() {
  6332. callbackTexture( count );
  6333. };
  6334. };
  6335. // first go synchronous elements
  6336. // fogs
  6337. var fogID, fogJSON;
  6338. for ( fogID in data.fogs ) {
  6339. fogJSON = data.fogs[ fogID ];
  6340. if ( fogJSON.type === "linear" ) {
  6341. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  6342. } else if ( fogJSON.type === "exp2" ) {
  6343. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  6344. }
  6345. color = fogJSON.color;
  6346. fog.color.setRGB( color[0], color[1], color[2] );
  6347. result.fogs[ fogID ] = fog;
  6348. }
  6349. // now come potentially asynchronous elements
  6350. // geometries
  6351. // count how many geometries will be loaded asynchronously
  6352. var geoID, geoJSON;
  6353. for ( geoID in data.geometries ) {
  6354. geoJSON = data.geometries[ geoID ];
  6355. if ( geoJSON.type in this.geometryHandlerMap ) {
  6356. counter_models += 1;
  6357. scope.onLoadStart();
  6358. }
  6359. }
  6360. // count how many hierarchies will be loaded asynchronously
  6361. var objID, objJSON;
  6362. for ( objID in data.objects ) {
  6363. objJSON = data.objects[ objID ];
  6364. if ( objJSON.type && ( objJSON.type in this.hierarchyHandlerMap ) ) {
  6365. counter_models += 1;
  6366. scope.onLoadStart();
  6367. }
  6368. }
  6369. total_models = counter_models;
  6370. for ( geoID in data.geometries ) {
  6371. geoJSON = data.geometries[ geoID ];
  6372. if ( geoJSON.type === "cube" ) {
  6373. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  6374. result.geometries[ geoID ] = geometry;
  6375. } else if ( geoJSON.type === "plane" ) {
  6376. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  6377. result.geometries[ geoID ] = geometry;
  6378. } else if ( geoJSON.type === "sphere" ) {
  6379. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  6380. result.geometries[ geoID ] = geometry;
  6381. } else if ( geoJSON.type === "cylinder" ) {
  6382. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  6383. result.geometries[ geoID ] = geometry;
  6384. } else if ( geoJSON.type === "torus" ) {
  6385. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  6386. result.geometries[ geoID ] = geometry;
  6387. } else if ( geoJSON.type === "icosahedron" ) {
  6388. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  6389. result.geometries[ geoID ] = geometry;
  6390. } else if ( geoJSON.type in this.geometryHandlerMap ) {
  6391. var loaderParameters = {};
  6392. for ( var parType in geoJSON ) {
  6393. if ( parType !== "type" && parType !== "url" ) {
  6394. loaderParameters[ parType ] = geoJSON[ parType ];
  6395. }
  6396. }
  6397. var loader = this.geometryHandlerMap[ geoJSON.type ][ "loaderObject" ];
  6398. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  6399. } else if ( geoJSON.type === "embedded" ) {
  6400. var modelJson = data.embeds[ geoJSON.id ],
  6401. texture_path = "";
  6402. // pass metadata along to jsonLoader so it knows the format version
  6403. modelJson.metadata = data.metadata;
  6404. if ( modelJson ) {
  6405. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  6406. jsonLoader.createModel( modelJson, create_callback_embed( geoID ), texture_path );
  6407. }
  6408. }
  6409. }
  6410. // textures
  6411. // count how many textures will be loaded asynchronously
  6412. var textureID, textureJSON;
  6413. for ( textureID in data.textures ) {
  6414. textureJSON = data.textures[ textureID ];
  6415. if ( textureJSON.url instanceof Array ) {
  6416. counter_textures += textureJSON.url.length;
  6417. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  6418. scope.onLoadStart();
  6419. }
  6420. } else {
  6421. counter_textures += 1;
  6422. scope.onLoadStart();
  6423. }
  6424. }
  6425. total_textures = counter_textures;
  6426. for ( textureID in data.textures ) {
  6427. textureJSON = data.textures[ textureID ];
  6428. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  6429. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  6430. }
  6431. if ( textureJSON.url instanceof Array ) {
  6432. var count = textureJSON.url.length;
  6433. var url_array = [];
  6434. for( var i = 0; i < count; i ++ ) {
  6435. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  6436. }
  6437. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  6438. if ( isCompressed ) {
  6439. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6440. } else {
  6441. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6442. }
  6443. } else {
  6444. var isCompressed = /\.dds$/i.test( textureJSON.url );
  6445. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  6446. var textureCallback = generateTextureCallback( 1 );
  6447. if ( isCompressed ) {
  6448. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  6449. } else {
  6450. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  6451. }
  6452. if ( THREE[ textureJSON.minFilter ] !== undefined )
  6453. texture.minFilter = THREE[ textureJSON.minFilter ];
  6454. if ( THREE[ textureJSON.magFilter ] !== undefined )
  6455. texture.magFilter = THREE[ textureJSON.magFilter ];
  6456. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  6457. if ( textureJSON.repeat ) {
  6458. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  6459. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6460. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6461. }
  6462. if ( textureJSON.offset ) {
  6463. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  6464. }
  6465. // handle wrap after repeat so that default repeat can be overriden
  6466. if ( textureJSON.wrap ) {
  6467. var wrapMap = {
  6468. "repeat" : THREE.RepeatWrapping,
  6469. "mirror" : THREE.MirroredRepeatWrapping
  6470. }
  6471. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  6472. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  6473. }
  6474. }
  6475. result.textures[ textureID ] = texture;
  6476. }
  6477. // materials
  6478. var matID, matJSON;
  6479. var parID;
  6480. for ( matID in data.materials ) {
  6481. matJSON = data.materials[ matID ];
  6482. for ( parID in matJSON.parameters ) {
  6483. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  6484. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  6485. } else if ( parID === "shading" ) {
  6486. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  6487. } else if ( parID === "side" ) {
  6488. if ( matJSON.parameters[ parID ] == "double" ) {
  6489. matJSON.parameters[ parID ] = THREE.DoubleSide;
  6490. } else if ( matJSON.parameters[ parID ] == "back" ) {
  6491. matJSON.parameters[ parID ] = THREE.BackSide;
  6492. } else {
  6493. matJSON.parameters[ parID ] = THREE.FrontSide;
  6494. }
  6495. } else if ( parID === "blending" ) {
  6496. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  6497. } else if ( parID === "combine" ) {
  6498. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  6499. } else if ( parID === "vertexColors" ) {
  6500. if ( matJSON.parameters[ parID ] == "face" ) {
  6501. matJSON.parameters[ parID ] = THREE.FaceColors;
  6502. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  6503. } else if ( matJSON.parameters[ parID ] ) {
  6504. matJSON.parameters[ parID ] = THREE.VertexColors;
  6505. }
  6506. } else if ( parID === "wrapRGB" ) {
  6507. var v3 = matJSON.parameters[ parID ];
  6508. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  6509. }
  6510. }
  6511. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  6512. matJSON.parameters.transparent = true;
  6513. }
  6514. if ( matJSON.parameters.normalMap ) {
  6515. var shader = THREE.ShaderLib[ "normalmap" ];
  6516. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6517. var diffuse = matJSON.parameters.color;
  6518. var specular = matJSON.parameters.specular;
  6519. var ambient = matJSON.parameters.ambient;
  6520. var shininess = matJSON.parameters.shininess;
  6521. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  6522. if ( matJSON.parameters.normalScale ) {
  6523. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  6524. }
  6525. if ( matJSON.parameters.map ) {
  6526. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  6527. uniforms[ "enableDiffuse" ].value = true;
  6528. }
  6529. if ( matJSON.parameters.envMap ) {
  6530. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  6531. uniforms[ "enableReflection" ].value = true;
  6532. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  6533. }
  6534. if ( matJSON.parameters.lightMap ) {
  6535. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  6536. uniforms[ "enableAO" ].value = true;
  6537. }
  6538. if ( matJSON.parameters.specularMap ) {
  6539. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  6540. uniforms[ "enableSpecular" ].value = true;
  6541. }
  6542. if ( matJSON.parameters.displacementMap ) {
  6543. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  6544. uniforms[ "enableDisplacement" ].value = true;
  6545. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  6546. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  6547. }
  6548. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  6549. uniforms[ "uSpecularColor" ].value.setHex( specular );
  6550. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  6551. uniforms[ "uShininess" ].value = shininess;
  6552. if ( matJSON.parameters.opacity ) {
  6553. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  6554. }
  6555. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6556. material = new THREE.ShaderMaterial( parameters );
  6557. } else {
  6558. material = new THREE[ matJSON.type ]( matJSON.parameters );
  6559. }
  6560. result.materials[ matID ] = material;
  6561. }
  6562. // second pass through all materials to initialize MeshFaceMaterials
  6563. // that could be referring to other materials out of order
  6564. for ( matID in data.materials ) {
  6565. matJSON = data.materials[ matID ];
  6566. if ( matJSON.parameters.materials ) {
  6567. var materialArray = [];
  6568. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  6569. var label = matJSON.parameters.materials[ i ];
  6570. materialArray.push( result.materials[ label ] );
  6571. }
  6572. result.materials[ matID ].materials = materialArray;
  6573. }
  6574. }
  6575. // objects ( synchronous init of procedural primitives )
  6576. handle_objects();
  6577. // defaults
  6578. if ( result.cameras && data.defaults.camera ) {
  6579. result.currentCamera = result.cameras[ data.defaults.camera ];
  6580. }
  6581. if ( result.fogs && data.defaults.fog ) {
  6582. result.scene.fog = result.fogs[ data.defaults.fog ];
  6583. }
  6584. // synchronous callback
  6585. scope.callbackSync( result );
  6586. // just in case there are no async elements
  6587. async_callback_gate();
  6588. };
  6589. /**
  6590. * @author mrdoob / http://mrdoob.com/
  6591. */
  6592. THREE.TextureLoader = function () {
  6593. THREE.EventDispatcher.call( this );
  6594. this.crossOrigin = null;
  6595. };
  6596. THREE.TextureLoader.prototype = {
  6597. constructor: THREE.TextureLoader,
  6598. load: function ( url ) {
  6599. var scope = this;
  6600. var image = new Image();
  6601. image.addEventListener( 'load', function () {
  6602. var texture = new THREE.Texture( image );
  6603. texture.needsUpdate = true;
  6604. scope.dispatchEvent( { type: 'load', content: texture } );
  6605. }, false );
  6606. image.addEventListener( 'error', function () {
  6607. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6608. }, false );
  6609. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  6610. image.src = url;
  6611. }
  6612. }
  6613. /**
  6614. * @author mrdoob / http://mrdoob.com/
  6615. * @author alteredq / http://alteredqualia.com/
  6616. */
  6617. THREE.Material = function () {
  6618. THREE.EventDispatcher.call( this );
  6619. this.id = THREE.MaterialIdCount ++;
  6620. this.name = '';
  6621. this.side = THREE.FrontSide;
  6622. this.opacity = 1;
  6623. this.transparent = false;
  6624. this.blending = THREE.NormalBlending;
  6625. this.blendSrc = THREE.SrcAlphaFactor;
  6626. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  6627. this.blendEquation = THREE.AddEquation;
  6628. this.depthTest = true;
  6629. this.depthWrite = true;
  6630. this.polygonOffset = false;
  6631. this.polygonOffsetFactor = 0;
  6632. this.polygonOffsetUnits = 0;
  6633. this.alphaTest = 0;
  6634. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  6635. this.visible = true;
  6636. this.needsUpdate = true;
  6637. };
  6638. THREE.Material.prototype.setValues = function ( values ) {
  6639. if ( values === undefined ) return;
  6640. for ( var key in values ) {
  6641. var newValue = values[ key ];
  6642. if ( newValue === undefined ) {
  6643. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  6644. continue;
  6645. }
  6646. if ( key in this ) {
  6647. var currentValue = this[ key ];
  6648. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  6649. currentValue.copy( newValue );
  6650. } else if ( currentValue instanceof THREE.Color ) {
  6651. currentValue.set( newValue );
  6652. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  6653. currentValue.copy( newValue );
  6654. } else {
  6655. this[ key ] = newValue;
  6656. }
  6657. }
  6658. }
  6659. };
  6660. THREE.Material.prototype.clone = function ( material ) {
  6661. if ( material === undefined ) material = new THREE.Material();
  6662. material.name = this.name;
  6663. material.side = this.side;
  6664. material.opacity = this.opacity;
  6665. material.transparent = this.transparent;
  6666. material.blending = this.blending;
  6667. material.blendSrc = this.blendSrc;
  6668. material.blendDst = this.blendDst;
  6669. material.blendEquation = this.blendEquation;
  6670. material.depthTest = this.depthTest;
  6671. material.depthWrite = this.depthWrite;
  6672. material.polygonOffset = this.polygonOffset;
  6673. material.polygonOffsetFactor = this.polygonOffsetFactor;
  6674. material.polygonOffsetUnits = this.polygonOffsetUnits;
  6675. material.alphaTest = this.alphaTest;
  6676. material.overdraw = this.overdraw;
  6677. material.visible = this.visible;
  6678. return material;
  6679. };
  6680. THREE.Material.prototype.dispose = function () {
  6681. this.dispatchEvent( { type: 'dispose' } );
  6682. };
  6683. THREE.MaterialIdCount = 0;
  6684. /**
  6685. * @author mrdoob / http://mrdoob.com/
  6686. * @author alteredq / http://alteredqualia.com/
  6687. *
  6688. * parameters = {
  6689. * color: <hex>,
  6690. * opacity: <float>,
  6691. *
  6692. * blending: THREE.NormalBlending,
  6693. * depthTest: <bool>,
  6694. * depthWrite: <bool>,
  6695. *
  6696. * linewidth: <float>,
  6697. * linecap: "round",
  6698. * linejoin: "round",
  6699. *
  6700. * vertexColors: <bool>
  6701. *
  6702. * fog: <bool>
  6703. * }
  6704. */
  6705. THREE.LineBasicMaterial = function ( parameters ) {
  6706. THREE.Material.call( this );
  6707. this.color = new THREE.Color( 0xffffff );
  6708. this.linewidth = 1;
  6709. this.linecap = 'round';
  6710. this.linejoin = 'round';
  6711. this.vertexColors = false;
  6712. this.fog = true;
  6713. this.setValues( parameters );
  6714. };
  6715. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6716. THREE.LineBasicMaterial.prototype.clone = function () {
  6717. var material = new THREE.LineBasicMaterial();
  6718. THREE.Material.prototype.clone.call( this, material );
  6719. material.color.copy( this.color );
  6720. material.linewidth = this.linewidth;
  6721. material.linecap = this.linecap;
  6722. material.linejoin = this.linejoin;
  6723. material.vertexColors = this.vertexColors;
  6724. material.fog = this.fog;
  6725. return material;
  6726. };
  6727. /**
  6728. * @author alteredq / http://alteredqualia.com/
  6729. *
  6730. * parameters = {
  6731. * color: <hex>,
  6732. * opacity: <float>,
  6733. *
  6734. * blending: THREE.NormalBlending,
  6735. * depthTest: <bool>,
  6736. * depthWrite: <bool>,
  6737. *
  6738. * linewidth: <float>,
  6739. *
  6740. * scale: <float>,
  6741. * dashSize: <float>,
  6742. * gapSize: <float>,
  6743. *
  6744. * vertexColors: <bool>
  6745. *
  6746. * fog: <bool>
  6747. * }
  6748. */
  6749. THREE.LineDashedMaterial = function ( parameters ) {
  6750. THREE.Material.call( this );
  6751. this.color = new THREE.Color( 0xffffff );
  6752. this.linewidth = 1;
  6753. this.scale = 1;
  6754. this.dashSize = 3;
  6755. this.gapSize = 1;
  6756. this.vertexColors = false;
  6757. this.fog = true;
  6758. this.setValues( parameters );
  6759. };
  6760. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  6761. THREE.LineDashedMaterial.prototype.clone = function () {
  6762. var material = new THREE.LineDashedMaterial();
  6763. THREE.Material.prototype.clone.call( this, material );
  6764. material.color.copy( this.color );
  6765. material.linewidth = this.linewidth;
  6766. material.scale = this.scale;
  6767. material.dashSize = this.dashSize;
  6768. material.gapSize = this.gapSize;
  6769. material.vertexColors = this.vertexColors;
  6770. material.fog = this.fog;
  6771. return material;
  6772. };
  6773. /**
  6774. * @author mrdoob / http://mrdoob.com/
  6775. * @author alteredq / http://alteredqualia.com/
  6776. *
  6777. * parameters = {
  6778. * color: <hex>,
  6779. * opacity: <float>,
  6780. * map: new THREE.Texture( <Image> ),
  6781. *
  6782. * lightMap: new THREE.Texture( <Image> ),
  6783. *
  6784. * specularMap: new THREE.Texture( <Image> ),
  6785. *
  6786. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6787. * combine: THREE.Multiply,
  6788. * reflectivity: <float>,
  6789. * refractionRatio: <float>,
  6790. *
  6791. * shading: THREE.SmoothShading,
  6792. * blending: THREE.NormalBlending,
  6793. * depthTest: <bool>,
  6794. * depthWrite: <bool>,
  6795. *
  6796. * wireframe: <boolean>,
  6797. * wireframeLinewidth: <float>,
  6798. *
  6799. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6800. *
  6801. * skinning: <bool>,
  6802. * morphTargets: <bool>,
  6803. *
  6804. * fog: <bool>
  6805. * }
  6806. */
  6807. THREE.MeshBasicMaterial = function ( parameters ) {
  6808. THREE.Material.call( this );
  6809. this.color = new THREE.Color( 0xffffff ); // emissive
  6810. this.map = null;
  6811. this.lightMap = null;
  6812. this.specularMap = null;
  6813. this.envMap = null;
  6814. this.combine = THREE.MultiplyOperation;
  6815. this.reflectivity = 1;
  6816. this.refractionRatio = 0.98;
  6817. this.fog = true;
  6818. this.shading = THREE.SmoothShading;
  6819. this.wireframe = false;
  6820. this.wireframeLinewidth = 1;
  6821. this.wireframeLinecap = 'round';
  6822. this.wireframeLinejoin = 'round';
  6823. this.vertexColors = THREE.NoColors;
  6824. this.skinning = false;
  6825. this.morphTargets = false;
  6826. this.setValues( parameters );
  6827. };
  6828. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6829. THREE.MeshBasicMaterial.prototype.clone = function () {
  6830. var material = new THREE.MeshBasicMaterial();
  6831. THREE.Material.prototype.clone.call( this, material );
  6832. material.color.copy( this.color );
  6833. material.map = this.map;
  6834. material.lightMap = this.lightMap;
  6835. material.specularMap = this.specularMap;
  6836. material.envMap = this.envMap;
  6837. material.combine = this.combine;
  6838. material.reflectivity = this.reflectivity;
  6839. material.refractionRatio = this.refractionRatio;
  6840. material.fog = this.fog;
  6841. material.shading = this.shading;
  6842. material.wireframe = this.wireframe;
  6843. material.wireframeLinewidth = this.wireframeLinewidth;
  6844. material.wireframeLinecap = this.wireframeLinecap;
  6845. material.wireframeLinejoin = this.wireframeLinejoin;
  6846. material.vertexColors = this.vertexColors;
  6847. material.skinning = this.skinning;
  6848. material.morphTargets = this.morphTargets;
  6849. return material;
  6850. };
  6851. /**
  6852. * @author mrdoob / http://mrdoob.com/
  6853. * @author alteredq / http://alteredqualia.com/
  6854. *
  6855. * parameters = {
  6856. * color: <hex>,
  6857. * ambient: <hex>,
  6858. * emissive: <hex>,
  6859. * opacity: <float>,
  6860. *
  6861. * map: new THREE.Texture( <Image> ),
  6862. *
  6863. * lightMap: new THREE.Texture( <Image> ),
  6864. *
  6865. * specularMap: new THREE.Texture( <Image> ),
  6866. *
  6867. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6868. * combine: THREE.Multiply,
  6869. * reflectivity: <float>,
  6870. * refractionRatio: <float>,
  6871. *
  6872. * shading: THREE.SmoothShading,
  6873. * blending: THREE.NormalBlending,
  6874. * depthTest: <bool>,
  6875. * depthWrite: <bool>,
  6876. *
  6877. * wireframe: <boolean>,
  6878. * wireframeLinewidth: <float>,
  6879. *
  6880. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6881. *
  6882. * skinning: <bool>,
  6883. * morphTargets: <bool>,
  6884. * morphNormals: <bool>,
  6885. *
  6886. * fog: <bool>
  6887. * }
  6888. */
  6889. THREE.MeshLambertMaterial = function ( parameters ) {
  6890. THREE.Material.call( this );
  6891. this.color = new THREE.Color( 0xffffff ); // diffuse
  6892. this.ambient = new THREE.Color( 0xffffff );
  6893. this.emissive = new THREE.Color( 0x000000 );
  6894. this.wrapAround = false;
  6895. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6896. this.map = null;
  6897. this.lightMap = null;
  6898. this.specularMap = null;
  6899. this.envMap = null;
  6900. this.combine = THREE.MultiplyOperation;
  6901. this.reflectivity = 1;
  6902. this.refractionRatio = 0.98;
  6903. this.fog = true;
  6904. this.shading = THREE.SmoothShading;
  6905. this.wireframe = false;
  6906. this.wireframeLinewidth = 1;
  6907. this.wireframeLinecap = 'round';
  6908. this.wireframeLinejoin = 'round';
  6909. this.vertexColors = THREE.NoColors;
  6910. this.skinning = false;
  6911. this.morphTargets = false;
  6912. this.morphNormals = false;
  6913. this.setValues( parameters );
  6914. };
  6915. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  6916. THREE.MeshLambertMaterial.prototype.clone = function () {
  6917. var material = new THREE.MeshLambertMaterial();
  6918. THREE.Material.prototype.clone.call( this, material );
  6919. material.color.copy( this.color );
  6920. material.ambient.copy( this.ambient );
  6921. material.emissive.copy( this.emissive );
  6922. material.wrapAround = this.wrapAround;
  6923. material.wrapRGB.copy( this.wrapRGB );
  6924. material.map = this.map;
  6925. material.lightMap = this.lightMap;
  6926. material.specularMap = this.specularMap;
  6927. material.envMap = this.envMap;
  6928. material.combine = this.combine;
  6929. material.reflectivity = this.reflectivity;
  6930. material.refractionRatio = this.refractionRatio;
  6931. material.fog = this.fog;
  6932. material.shading = this.shading;
  6933. material.wireframe = this.wireframe;
  6934. material.wireframeLinewidth = this.wireframeLinewidth;
  6935. material.wireframeLinecap = this.wireframeLinecap;
  6936. material.wireframeLinejoin = this.wireframeLinejoin;
  6937. material.vertexColors = this.vertexColors;
  6938. material.skinning = this.skinning;
  6939. material.morphTargets = this.morphTargets;
  6940. material.morphNormals = this.morphNormals;
  6941. return material;
  6942. };
  6943. /**
  6944. * @author mrdoob / http://mrdoob.com/
  6945. * @author alteredq / http://alteredqualia.com/
  6946. *
  6947. * parameters = {
  6948. * color: <hex>,
  6949. * ambient: <hex>,
  6950. * emissive: <hex>,
  6951. * specular: <hex>,
  6952. * shininess: <float>,
  6953. * opacity: <float>,
  6954. *
  6955. * map: new THREE.Texture( <Image> ),
  6956. *
  6957. * lightMap: new THREE.Texture( <Image> ),
  6958. *
  6959. * bumpMap: new THREE.Texture( <Image> ),
  6960. * bumpScale: <float>,
  6961. *
  6962. * normalMap: new THREE.Texture( <Image> ),
  6963. * normalScale: <Vector2>,
  6964. *
  6965. * specularMap: new THREE.Texture( <Image> ),
  6966. *
  6967. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6968. * combine: THREE.Multiply,
  6969. * reflectivity: <float>,
  6970. * refractionRatio: <float>,
  6971. *
  6972. * shading: THREE.SmoothShading,
  6973. * blending: THREE.NormalBlending,
  6974. * depthTest: <bool>,
  6975. * depthWrite: <bool>,
  6976. *
  6977. * wireframe: <boolean>,
  6978. * wireframeLinewidth: <float>,
  6979. *
  6980. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6981. *
  6982. * skinning: <bool>,
  6983. * morphTargets: <bool>,
  6984. * morphNormals: <bool>,
  6985. *
  6986. * fog: <bool>
  6987. * }
  6988. */
  6989. THREE.MeshPhongMaterial = function ( parameters ) {
  6990. THREE.Material.call( this );
  6991. this.color = new THREE.Color( 0xffffff ); // diffuse
  6992. this.ambient = new THREE.Color( 0xffffff );
  6993. this.emissive = new THREE.Color( 0x000000 );
  6994. this.specular = new THREE.Color( 0x111111 );
  6995. this.shininess = 30;
  6996. this.metal = false;
  6997. this.perPixel = true;
  6998. this.wrapAround = false;
  6999. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7000. this.map = null;
  7001. this.lightMap = null;
  7002. this.bumpMap = null;
  7003. this.bumpScale = 1;
  7004. this.normalMap = null;
  7005. this.normalScale = new THREE.Vector2( 1, 1 );
  7006. this.specularMap = null;
  7007. this.envMap = null;
  7008. this.combine = THREE.MultiplyOperation;
  7009. this.reflectivity = 1;
  7010. this.refractionRatio = 0.98;
  7011. this.fog = true;
  7012. this.shading = THREE.SmoothShading;
  7013. this.wireframe = false;
  7014. this.wireframeLinewidth = 1;
  7015. this.wireframeLinecap = 'round';
  7016. this.wireframeLinejoin = 'round';
  7017. this.vertexColors = THREE.NoColors;
  7018. this.skinning = false;
  7019. this.morphTargets = false;
  7020. this.morphNormals = false;
  7021. this.setValues( parameters );
  7022. };
  7023. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  7024. THREE.MeshPhongMaterial.prototype.clone = function () {
  7025. var material = new THREE.MeshPhongMaterial();
  7026. THREE.Material.prototype.clone.call( this, material );
  7027. material.color.copy( this.color );
  7028. material.ambient.copy( this.ambient );
  7029. material.emissive.copy( this.emissive );
  7030. material.specular.copy( this.specular );
  7031. material.shininess = this.shininess;
  7032. material.metal = this.metal;
  7033. material.perPixel = this.perPixel;
  7034. material.wrapAround = this.wrapAround;
  7035. material.wrapRGB.copy( this.wrapRGB );
  7036. material.map = this.map;
  7037. material.lightMap = this.lightMap;
  7038. material.bumpMap = this.bumpMap;
  7039. material.bumpScale = this.bumpScale;
  7040. material.normalMap = this.normalMap;
  7041. material.normalScale.copy( this.normalScale );
  7042. material.specularMap = this.specularMap;
  7043. material.envMap = this.envMap;
  7044. material.combine = this.combine;
  7045. material.reflectivity = this.reflectivity;
  7046. material.refractionRatio = this.refractionRatio;
  7047. material.fog = this.fog;
  7048. material.shading = this.shading;
  7049. material.wireframe = this.wireframe;
  7050. material.wireframeLinewidth = this.wireframeLinewidth;
  7051. material.wireframeLinecap = this.wireframeLinecap;
  7052. material.wireframeLinejoin = this.wireframeLinejoin;
  7053. material.vertexColors = this.vertexColors;
  7054. material.skinning = this.skinning;
  7055. material.morphTargets = this.morphTargets;
  7056. material.morphNormals = this.morphNormals;
  7057. return material;
  7058. };
  7059. /**
  7060. * @author mrdoob / http://mrdoob.com/
  7061. * @author alteredq / http://alteredqualia.com/
  7062. *
  7063. * parameters = {
  7064. * opacity: <float>,
  7065. *
  7066. * blending: THREE.NormalBlending,
  7067. * depthTest: <bool>,
  7068. * depthWrite: <bool>,
  7069. *
  7070. * wireframe: <boolean>,
  7071. * wireframeLinewidth: <float>
  7072. * }
  7073. */
  7074. THREE.MeshDepthMaterial = function ( parameters ) {
  7075. THREE.Material.call( this );
  7076. this.wireframe = false;
  7077. this.wireframeLinewidth = 1;
  7078. this.setValues( parameters );
  7079. };
  7080. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  7081. THREE.MeshDepthMaterial.prototype.clone = function () {
  7082. var material = new THREE.LineBasicMaterial();
  7083. THREE.Material.prototype.clone.call( this, material );
  7084. material.wireframe = this.wireframe;
  7085. material.wireframeLinewidth = this.wireframeLinewidth;
  7086. return material;
  7087. };
  7088. /**
  7089. * @author mrdoob / http://mrdoob.com/
  7090. *
  7091. * parameters = {
  7092. * opacity: <float>,
  7093. *
  7094. * shading: THREE.FlatShading,
  7095. * blending: THREE.NormalBlending,
  7096. * depthTest: <bool>,
  7097. * depthWrite: <bool>,
  7098. *
  7099. * wireframe: <boolean>,
  7100. * wireframeLinewidth: <float>
  7101. * }
  7102. */
  7103. THREE.MeshNormalMaterial = function ( parameters ) {
  7104. THREE.Material.call( this, parameters );
  7105. this.shading = THREE.FlatShading;
  7106. this.wireframe = false;
  7107. this.wireframeLinewidth = 1;
  7108. this.setValues( parameters );
  7109. };
  7110. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  7111. THREE.MeshNormalMaterial.prototype.clone = function () {
  7112. var material = new THREE.MeshNormalMaterial();
  7113. THREE.Material.prototype.clone.call( this, material );
  7114. material.shading = this.shading;
  7115. material.wireframe = this.wireframe;
  7116. material.wireframeLinewidth = this.wireframeLinewidth;
  7117. return material;
  7118. };
  7119. /**
  7120. * @author mrdoob / http://mrdoob.com/
  7121. */
  7122. THREE.MeshFaceMaterial = function ( materials ) {
  7123. this.materials = materials instanceof Array ? materials : [];
  7124. };
  7125. THREE.MeshFaceMaterial.prototype.clone = function () {
  7126. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  7127. };
  7128. /**
  7129. * @author mrdoob / http://mrdoob.com/
  7130. * @author alteredq / http://alteredqualia.com/
  7131. *
  7132. * parameters = {
  7133. * color: <hex>,
  7134. * opacity: <float>,
  7135. * map: new THREE.Texture( <Image> ),
  7136. *
  7137. * size: <float>,
  7138. *
  7139. * blending: THREE.NormalBlending,
  7140. * depthTest: <bool>,
  7141. * depthWrite: <bool>,
  7142. *
  7143. * vertexColors: <bool>,
  7144. *
  7145. * fog: <bool>
  7146. * }
  7147. */
  7148. THREE.ParticleBasicMaterial = function ( parameters ) {
  7149. THREE.Material.call( this );
  7150. this.color = new THREE.Color( 0xffffff );
  7151. this.map = null;
  7152. this.size = 1;
  7153. this.sizeAttenuation = true;
  7154. this.vertexColors = false;
  7155. this.fog = true;
  7156. this.setValues( parameters );
  7157. };
  7158. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7159. THREE.ParticleBasicMaterial.prototype.clone = function () {
  7160. var material = new THREE.ParticleBasicMaterial();
  7161. THREE.Material.prototype.clone.call( this, material );
  7162. material.color.copy( this.color );
  7163. material.map = this.map;
  7164. material.size = this.size;
  7165. material.sizeAttenuation = this.sizeAttenuation;
  7166. material.vertexColors = this.vertexColors;
  7167. material.fog = this.fog;
  7168. return material;
  7169. };
  7170. /**
  7171. * @author mrdoob / http://mrdoob.com/
  7172. *
  7173. * parameters = {
  7174. * color: <hex>,
  7175. * program: <function>,
  7176. * opacity: <float>,
  7177. * blending: THREE.NormalBlending
  7178. * }
  7179. */
  7180. THREE.ParticleCanvasMaterial = function ( parameters ) {
  7181. THREE.Material.call( this );
  7182. this.color = new THREE.Color( 0xffffff );
  7183. this.program = function ( context, color ) {};
  7184. this.setValues( parameters );
  7185. };
  7186. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  7187. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  7188. var material = new THREE.ParticleCanvasMaterial();
  7189. THREE.Material.prototype.clone.call( this, material );
  7190. material.color.copy( this.color );
  7191. material.program = this.program;
  7192. return material;
  7193. };
  7194. /**
  7195. * @author alteredq / http://alteredqualia.com/
  7196. *
  7197. * parameters = {
  7198. * fragmentShader: <string>,
  7199. * vertexShader: <string>,
  7200. *
  7201. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  7202. *
  7203. * defines: { "label" : "value" },
  7204. *
  7205. * shading: THREE.SmoothShading,
  7206. * blending: THREE.NormalBlending,
  7207. * depthTest: <bool>,
  7208. * depthWrite: <bool>,
  7209. *
  7210. * wireframe: <boolean>,
  7211. * wireframeLinewidth: <float>,
  7212. *
  7213. * lights: <bool>,
  7214. *
  7215. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7216. *
  7217. * skinning: <bool>,
  7218. * morphTargets: <bool>,
  7219. * morphNormals: <bool>,
  7220. *
  7221. * fog: <bool>
  7222. * }
  7223. */
  7224. THREE.ShaderMaterial = function ( parameters ) {
  7225. THREE.Material.call( this );
  7226. this.fragmentShader = "void main() {}";
  7227. this.vertexShader = "void main() {}";
  7228. this.uniforms = {};
  7229. this.defines = {};
  7230. this.attributes = null;
  7231. this.shading = THREE.SmoothShading;
  7232. this.wireframe = false;
  7233. this.wireframeLinewidth = 1;
  7234. this.fog = false; // set to use scene fog
  7235. this.lights = false; // set to use scene lights
  7236. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  7237. this.skinning = false; // set to use skinning attribute streams
  7238. this.morphTargets = false; // set to use morph targets
  7239. this.morphNormals = false; // set to use morph normals
  7240. this.setValues( parameters );
  7241. };
  7242. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  7243. THREE.ShaderMaterial.prototype.clone = function () {
  7244. var material = new THREE.ShaderMaterial();
  7245. THREE.Material.prototype.clone.call( this, material );
  7246. material.fragmentShader = this.fragmentShader;
  7247. material.vertexShader = this.vertexShader;
  7248. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  7249. material.attributes = this.attributes;
  7250. material.defines = this.defines;
  7251. material.shading = this.shading;
  7252. material.wireframe = this.wireframe;
  7253. material.wireframeLinewidth = this.wireframeLinewidth;
  7254. material.fog = this.fog;
  7255. material.lights = this.lights;
  7256. material.vertexColors = this.vertexColors;
  7257. material.skinning = this.skinning;
  7258. material.morphTargets = this.morphTargets;
  7259. material.morphNormals = this.morphNormals;
  7260. return material;
  7261. };
  7262. /**
  7263. * @author alteredq / http://alteredqualia.com/
  7264. *
  7265. * parameters = {
  7266. * color: <hex>,
  7267. * opacity: <float>,
  7268. * map: new THREE.Texture( <Image> ),
  7269. *
  7270. * blending: THREE.NormalBlending,
  7271. * depthTest: <bool>,
  7272. * depthWrite: <bool>,
  7273. *
  7274. * useScreenCoordinates: <bool>,
  7275. * sizeAttenuation: <bool>,
  7276. * scaleByViewport: <bool>,
  7277. * alignment: THREE.SpriteAlignment.center,
  7278. *
  7279. * uvOffset: new THREE.Vector2(),
  7280. * uvScale: new THREE.Vector2(),
  7281. *
  7282. * fog: <bool>
  7283. * }
  7284. */
  7285. THREE.SpriteMaterial = function ( parameters ) {
  7286. THREE.Material.call( this );
  7287. // defaults
  7288. this.color = new THREE.Color( 0xffffff );
  7289. this.map = new THREE.Texture();
  7290. this.useScreenCoordinates = true;
  7291. this.depthTest = !this.useScreenCoordinates;
  7292. this.sizeAttenuation = !this.useScreenCoordinates;
  7293. this.scaleByViewport = !this.sizeAttenuation;
  7294. this.alignment = THREE.SpriteAlignment.center.clone();
  7295. this.fog = false;
  7296. this.uvOffset = new THREE.Vector2( 0, 0 );
  7297. this.uvScale = new THREE.Vector2( 1, 1 );
  7298. // set parameters
  7299. this.setValues( parameters );
  7300. // override coupled defaults if not specified explicitly by parameters
  7301. parameters = parameters || {};
  7302. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  7303. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  7304. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  7305. };
  7306. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  7307. THREE.SpriteMaterial.prototype.clone = function () {
  7308. var material = new THREE.SpriteMaterial();
  7309. THREE.Material.prototype.clone.call( this, material );
  7310. material.color.copy( this.color );
  7311. material.map = this.map;
  7312. material.useScreenCoordinates = this.useScreenCoordinates;
  7313. material.sizeAttenuation = this.sizeAttenuation;
  7314. material.scaleByViewport = this.scaleByViewport;
  7315. material.alignment.copy( this.alignment );
  7316. material.uvOffset.copy( this.uvOffset );
  7317. material.uvScale.copy( this.uvScale );
  7318. material.fog = this.fog;
  7319. return material;
  7320. };
  7321. // Alignment enums
  7322. THREE.SpriteAlignment = {};
  7323. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  7324. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  7325. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  7326. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  7327. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  7328. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  7329. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  7330. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  7331. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  7332. /**
  7333. * @author mrdoob / http://mrdoob.com/
  7334. * @author alteredq / http://alteredqualia.com/
  7335. * @author szimek / https://github.com/szimek/
  7336. */
  7337. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  7338. THREE.EventDispatcher.call( this );
  7339. this.id = THREE.TextureIdCount ++;
  7340. this.name = '';
  7341. this.image = image;
  7342. this.mipmaps = [];
  7343. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  7344. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  7345. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  7346. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  7347. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  7348. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  7349. this.format = format !== undefined ? format : THREE.RGBAFormat;
  7350. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  7351. this.offset = new THREE.Vector2( 0, 0 );
  7352. this.repeat = new THREE.Vector2( 1, 1 );
  7353. this.generateMipmaps = true;
  7354. this.premultiplyAlpha = false;
  7355. this.flipY = true;
  7356. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7357. this.needsUpdate = false;
  7358. this.onUpdate = null;
  7359. };
  7360. THREE.Texture.prototype = {
  7361. constructor: THREE.Texture,
  7362. clone: function ( texture ) {
  7363. if ( texture === undefined ) texture = new THREE.Texture();
  7364. texture.image = this.image;
  7365. texture.mipmaps = this.mipmaps.slice(0);
  7366. texture.mapping = this.mapping;
  7367. texture.wrapS = this.wrapS;
  7368. texture.wrapT = this.wrapT;
  7369. texture.magFilter = this.magFilter;
  7370. texture.minFilter = this.minFilter;
  7371. texture.anisotropy = this.anisotropy;
  7372. texture.format = this.format;
  7373. texture.type = this.type;
  7374. texture.offset.copy( this.offset );
  7375. texture.repeat.copy( this.repeat );
  7376. texture.generateMipmaps = this.generateMipmaps;
  7377. texture.premultiplyAlpha = this.premultiplyAlpha;
  7378. texture.flipY = this.flipY;
  7379. texture.unpackAlignment = this.unpackAlignment;
  7380. return texture;
  7381. },
  7382. dispose: function () {
  7383. this.dispatchEvent( { type: 'dispose' } );
  7384. }
  7385. };
  7386. THREE.TextureIdCount = 0;
  7387. /**
  7388. * @author alteredq / http://alteredqualia.com/
  7389. */
  7390. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7391. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7392. this.image = { width: width, height: height };
  7393. this.mipmaps = mipmaps;
  7394. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  7395. };
  7396. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  7397. THREE.CompressedTexture.prototype.clone = function () {
  7398. var texture = new THREE.CompressedTexture();
  7399. THREE.Texture.prototype.clone.call( this, texture );
  7400. return texture;
  7401. };
  7402. /**
  7403. * @author alteredq / http://alteredqualia.com/
  7404. */
  7405. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7406. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7407. this.image = { data: data, width: width, height: height };
  7408. };
  7409. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  7410. THREE.DataTexture.prototype.clone = function () {
  7411. var texture = new THREE.DataTexture();
  7412. THREE.Texture.prototype.clone.call( this, texture );
  7413. return texture;
  7414. };
  7415. /**
  7416. * @author mrdoob / http://mrdoob.com/
  7417. */
  7418. THREE.Particle = function ( material ) {
  7419. THREE.Object3D.call( this );
  7420. this.material = material;
  7421. };
  7422. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  7423. THREE.Particle.prototype.clone = function ( object ) {
  7424. if ( object === undefined ) object = new THREE.Particle( this.material );
  7425. THREE.Object3D.prototype.clone.call( this, object );
  7426. return object;
  7427. };
  7428. /**
  7429. * @author alteredq / http://alteredqualia.com/
  7430. */
  7431. THREE.ParticleSystem = function ( geometry, material ) {
  7432. THREE.Object3D.call( this );
  7433. this.geometry = geometry;
  7434. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  7435. this.sortParticles = false;
  7436. if ( this.geometry ) {
  7437. // calc bound radius
  7438. if( this.geometry.boundingSphere === null ) {
  7439. this.geometry.computeBoundingSphere();
  7440. }
  7441. }
  7442. this.frustumCulled = false;
  7443. };
  7444. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  7445. THREE.ParticleSystem.prototype.clone = function ( object ) {
  7446. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  7447. object.sortParticles = this.sortParticles;
  7448. THREE.Object3D.prototype.clone.call( this, object );
  7449. return object;
  7450. };
  7451. /**
  7452. * @author mrdoob / http://mrdoob.com/
  7453. */
  7454. THREE.Line = function ( geometry, material, type ) {
  7455. THREE.Object3D.call( this );
  7456. this.geometry = geometry;
  7457. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  7458. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  7459. if ( this.geometry ) {
  7460. if ( ! this.geometry.boundingSphere ) {
  7461. this.geometry.computeBoundingSphere();
  7462. }
  7463. }
  7464. };
  7465. THREE.LineStrip = 0;
  7466. THREE.LinePieces = 1;
  7467. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  7468. THREE.Line.prototype.clone = function ( object ) {
  7469. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  7470. THREE.Object3D.prototype.clone.call( this, object );
  7471. return object;
  7472. };
  7473. /**
  7474. * @author mrdoob / http://mrdoob.com/
  7475. * @author alteredq / http://alteredqualia.com/
  7476. * @author mikael emtinger / http://gomo.se/
  7477. * @author jonobr1 / http://jonobr1.com/
  7478. */
  7479. THREE.Mesh = function ( geometry, material ) {
  7480. THREE.Object3D.call( this );
  7481. this.geometry = geometry;
  7482. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  7483. if ( this.geometry !== undefined ) {
  7484. if ( this.geometry.boundingSphere === null ) {
  7485. this.geometry.computeBoundingSphere();
  7486. }
  7487. this.updateMorphTargets();
  7488. }
  7489. };
  7490. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  7491. THREE.Mesh.prototype.updateMorphTargets = function () {
  7492. if ( this.geometry.morphTargets.length > 0 ) {
  7493. this.morphTargetBase = -1;
  7494. this.morphTargetForcedOrder = [];
  7495. this.morphTargetInfluences = [];
  7496. this.morphTargetDictionary = {};
  7497. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  7498. this.morphTargetInfluences.push( 0 );
  7499. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  7500. }
  7501. }
  7502. };
  7503. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  7504. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  7505. return this.morphTargetDictionary[ name ];
  7506. }
  7507. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  7508. return 0;
  7509. };
  7510. THREE.Mesh.prototype.clone = function ( object ) {
  7511. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  7512. THREE.Object3D.prototype.clone.call( this, object );
  7513. return object;
  7514. };
  7515. /**
  7516. * @author mikael emtinger / http://gomo.se/
  7517. * @author alteredq / http://alteredqualia.com/
  7518. */
  7519. THREE.Bone = function( belongsToSkin ) {
  7520. THREE.Object3D.call( this );
  7521. this.skin = belongsToSkin;
  7522. this.skinMatrix = new THREE.Matrix4();
  7523. };
  7524. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  7525. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  7526. // update local
  7527. if ( this.matrixAutoUpdate ) {
  7528. forceUpdate |= this.updateMatrix();
  7529. }
  7530. // update skin matrix
  7531. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  7532. if( parentSkinMatrix ) {
  7533. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  7534. } else {
  7535. this.skinMatrix.copy( this.matrix );
  7536. }
  7537. this.matrixWorldNeedsUpdate = false;
  7538. forceUpdate = true;
  7539. }
  7540. // update children
  7541. var child, i, l = this.children.length;
  7542. for ( i = 0; i < l; i ++ ) {
  7543. this.children[ i ].update( this.skinMatrix, forceUpdate );
  7544. }
  7545. };
  7546. /**
  7547. * @author mikael emtinger / http://gomo.se/
  7548. * @author alteredq / http://alteredqualia.com/
  7549. */
  7550. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  7551. THREE.Mesh.call( this, geometry, material );
  7552. //
  7553. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  7554. // init bones
  7555. this.identityMatrix = new THREE.Matrix4();
  7556. this.bones = [];
  7557. this.boneMatrices = [];
  7558. var b, bone, gbone, p, q, s;
  7559. if ( this.geometry && this.geometry.bones !== undefined ) {
  7560. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  7561. gbone = this.geometry.bones[ b ];
  7562. p = gbone.pos;
  7563. q = gbone.rotq;
  7564. s = gbone.scl;
  7565. bone = this.addBone();
  7566. bone.name = gbone.name;
  7567. bone.position.set( p[0], p[1], p[2] );
  7568. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  7569. bone.useQuaternion = true;
  7570. if ( s !== undefined ) {
  7571. bone.scale.set( s[0], s[1], s[2] );
  7572. } else {
  7573. bone.scale.set( 1, 1, 1 );
  7574. }
  7575. }
  7576. for ( b = 0; b < this.bones.length; b ++ ) {
  7577. gbone = this.geometry.bones[ b ];
  7578. bone = this.bones[ b ];
  7579. if ( gbone.parent === -1 ) {
  7580. this.add( bone );
  7581. } else {
  7582. this.bones[ gbone.parent ].add( bone );
  7583. }
  7584. }
  7585. //
  7586. var nBones = this.bones.length;
  7587. if ( this.useVertexTexture ) {
  7588. // layout (1 matrix = 4 pixels)
  7589. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  7590. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  7591. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  7592. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  7593. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  7594. var size;
  7595. if ( nBones > 256 )
  7596. size = 64;
  7597. else if ( nBones > 64 )
  7598. size = 32;
  7599. else if ( nBones > 16 )
  7600. size = 16;
  7601. else
  7602. size = 8;
  7603. this.boneTextureWidth = size;
  7604. this.boneTextureHeight = size;
  7605. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  7606. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  7607. this.boneTexture.minFilter = THREE.NearestFilter;
  7608. this.boneTexture.magFilter = THREE.NearestFilter;
  7609. this.boneTexture.generateMipmaps = false;
  7610. this.boneTexture.flipY = false;
  7611. } else {
  7612. this.boneMatrices = new Float32Array( 16 * nBones );
  7613. }
  7614. this.pose();
  7615. }
  7616. };
  7617. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  7618. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  7619. if ( bone === undefined ) {
  7620. bone = new THREE.Bone( this );
  7621. }
  7622. this.bones.push( bone );
  7623. return bone;
  7624. };
  7625. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  7626. this.matrixAutoUpdate && this.updateMatrix();
  7627. // update matrixWorld
  7628. if ( this.matrixWorldNeedsUpdate || force ) {
  7629. if ( this.parent ) {
  7630. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  7631. } else {
  7632. this.matrixWorld.copy( this.matrix );
  7633. }
  7634. this.matrixWorldNeedsUpdate = false;
  7635. force = true;
  7636. }
  7637. // update children
  7638. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  7639. var child = this.children[ i ];
  7640. if ( child instanceof THREE.Bone ) {
  7641. child.update( this.identityMatrix, false );
  7642. } else {
  7643. child.updateMatrixWorld( true );
  7644. }
  7645. }
  7646. // make a snapshot of the bones' rest position
  7647. if ( this.boneInverses == undefined ) {
  7648. this.boneInverses = [];
  7649. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7650. var inverse = new THREE.Matrix4();
  7651. inverse.getInverse( this.bones[ b ].skinMatrix );
  7652. this.boneInverses.push( inverse );
  7653. }
  7654. }
  7655. // flatten bone matrices to array
  7656. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7657. // compute the offset between the current and the original transform;
  7658. //TODO: we could get rid of this multiplication step if the skinMatrix
  7659. // was already representing the offset; however, this requires some
  7660. // major changes to the animation system
  7661. THREE.SkinnedMesh.offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  7662. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  7663. }
  7664. if ( this.useVertexTexture ) {
  7665. this.boneTexture.needsUpdate = true;
  7666. }
  7667. };
  7668. THREE.SkinnedMesh.prototype.pose = function () {
  7669. this.updateMatrixWorld( true );
  7670. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  7671. // normalize weights
  7672. var sw = this.geometry.skinWeights[ i ];
  7673. var scale = 1.0 / sw.lengthManhattan();
  7674. if ( scale !== Infinity ) {
  7675. sw.multiplyScalar( scale );
  7676. } else {
  7677. sw.set( 1 ); // this will be normalized by the shader anyway
  7678. }
  7679. }
  7680. };
  7681. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  7682. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  7683. THREE.Mesh.prototype.clone.call( this, object );
  7684. return object;
  7685. };
  7686. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  7687. /**
  7688. * @author alteredq / http://alteredqualia.com/
  7689. */
  7690. THREE.MorphAnimMesh = function ( geometry, material ) {
  7691. THREE.Mesh.call( this, geometry, material );
  7692. // API
  7693. this.duration = 1000; // milliseconds
  7694. this.mirroredLoop = false;
  7695. this.time = 0;
  7696. // internals
  7697. this.lastKeyframe = 0;
  7698. this.currentKeyframe = 0;
  7699. this.direction = 1;
  7700. this.directionBackwards = false;
  7701. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  7702. };
  7703. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  7704. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  7705. this.startKeyframe = start;
  7706. this.endKeyframe = end;
  7707. this.length = this.endKeyframe - this.startKeyframe + 1;
  7708. };
  7709. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  7710. this.direction = 1;
  7711. this.directionBackwards = false;
  7712. };
  7713. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  7714. this.direction = -1;
  7715. this.directionBackwards = true;
  7716. };
  7717. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  7718. var geometry = this.geometry;
  7719. if ( ! geometry.animations ) geometry.animations = {};
  7720. var firstAnimation, animations = geometry.animations;
  7721. var pattern = /([a-z]+)(\d+)/;
  7722. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  7723. var morph = geometry.morphTargets[ i ];
  7724. var parts = morph.name.match( pattern );
  7725. if ( parts && parts.length > 1 ) {
  7726. var label = parts[ 1 ];
  7727. var num = parts[ 2 ];
  7728. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  7729. var animation = animations[ label ];
  7730. if ( i < animation.start ) animation.start = i;
  7731. if ( i > animation.end ) animation.end = i;
  7732. if ( ! firstAnimation ) firstAnimation = label;
  7733. }
  7734. }
  7735. geometry.firstAnimation = firstAnimation;
  7736. };
  7737. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  7738. if ( ! this.geometry.animations ) this.geometry.animations = {};
  7739. this.geometry.animations[ label ] = { start: start, end: end };
  7740. };
  7741. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  7742. var animation = this.geometry.animations[ label ];
  7743. if ( animation ) {
  7744. this.setFrameRange( animation.start, animation.end );
  7745. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  7746. this.time = 0;
  7747. } else {
  7748. console.warn( "animation[" + label + "] undefined" );
  7749. }
  7750. };
  7751. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  7752. var frameTime = this.duration / this.length;
  7753. this.time += this.direction * delta;
  7754. if ( this.mirroredLoop ) {
  7755. if ( this.time > this.duration || this.time < 0 ) {
  7756. this.direction *= -1;
  7757. if ( this.time > this.duration ) {
  7758. this.time = this.duration;
  7759. this.directionBackwards = true;
  7760. }
  7761. if ( this.time < 0 ) {
  7762. this.time = 0;
  7763. this.directionBackwards = false;
  7764. }
  7765. }
  7766. } else {
  7767. this.time = this.time % this.duration;
  7768. if ( this.time < 0 ) this.time += this.duration;
  7769. }
  7770. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  7771. if ( keyframe !== this.currentKeyframe ) {
  7772. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  7773. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  7774. this.morphTargetInfluences[ keyframe ] = 0;
  7775. this.lastKeyframe = this.currentKeyframe;
  7776. this.currentKeyframe = keyframe;
  7777. }
  7778. var mix = ( this.time % frameTime ) / frameTime;
  7779. if ( this.directionBackwards ) {
  7780. mix = 1 - mix;
  7781. }
  7782. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  7783. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  7784. };
  7785. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  7786. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  7787. object.duration = this.duration;
  7788. object.mirroredLoop = this.mirroredLoop;
  7789. object.time = this.time;
  7790. object.lastKeyframe = this.lastKeyframe;
  7791. object.currentKeyframe = this.currentKeyframe;
  7792. object.direction = this.direction;
  7793. object.directionBackwards = this.directionBackwards;
  7794. THREE.Mesh.prototype.clone.call( this, object );
  7795. return object;
  7796. };
  7797. /**
  7798. * @author alteredq / http://alteredqualia.com/
  7799. */
  7800. THREE.Ribbon = function ( geometry, material ) {
  7801. THREE.Object3D.call( this );
  7802. this.geometry = geometry;
  7803. this.material = material;
  7804. };
  7805. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  7806. THREE.Ribbon.prototype.clone = function ( object ) {
  7807. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  7808. THREE.Object3D.prototype.clone.call( this, object );
  7809. return object;
  7810. };
  7811. /**
  7812. * @author mikael emtinger / http://gomo.se/
  7813. * @author alteredq / http://alteredqualia.com/
  7814. * @author mrdoob / http://mrdoob.com/
  7815. */
  7816. THREE.LOD = function () {
  7817. THREE.Object3D.call( this );
  7818. this.LODs = [];
  7819. };
  7820. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  7821. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  7822. if ( visibleAtDistance === undefined ) {
  7823. visibleAtDistance = 0;
  7824. }
  7825. visibleAtDistance = Math.abs( visibleAtDistance );
  7826. for ( var l = 0; l < this.LODs.length; l ++ ) {
  7827. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  7828. break;
  7829. }
  7830. }
  7831. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  7832. this.add( object3D );
  7833. };
  7834. THREE.LOD.prototype.update = function ( camera ) {
  7835. if ( this.LODs.length > 1 ) {
  7836. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  7837. var inverse = camera.matrixWorldInverse;
  7838. var distance = -( inverse.elements[2] * this.matrixWorld.elements[12] + inverse.elements[6] * this.matrixWorld.elements[13] + inverse.elements[10] * this.matrixWorld.elements[14] + inverse.elements[14] );
  7839. this.LODs[ 0 ].object3D.visible = true;
  7840. for ( var l = 1; l < this.LODs.length; l ++ ) {
  7841. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  7842. this.LODs[ l - 1 ].object3D.visible = false;
  7843. this.LODs[ l ].object3D.visible = true;
  7844. } else {
  7845. break;
  7846. }
  7847. }
  7848. for( ; l < this.LODs.length; l ++ ) {
  7849. this.LODs[ l ].object3D.visible = false;
  7850. }
  7851. }
  7852. };
  7853. THREE.LOD.prototype.clone = function () {
  7854. // TODO
  7855. };
  7856. /**
  7857. * @author mikael emtinger / http://gomo.se/
  7858. * @author alteredq / http://alteredqualia.com/
  7859. */
  7860. THREE.Sprite = function ( material ) {
  7861. THREE.Object3D.call( this );
  7862. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  7863. this.rotation3d = this.rotation;
  7864. this.rotation = 0;
  7865. };
  7866. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  7867. /*
  7868. * Custom update matrix
  7869. */
  7870. THREE.Sprite.prototype.updateMatrix = function () {
  7871. this.matrix.setPosition( this.position );
  7872. this.rotation3d.set( 0, 0, this.rotation );
  7873. this.matrix.setRotationFromEuler( this.rotation3d );
  7874. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  7875. this.matrix.scale( this.scale );
  7876. }
  7877. this.matrixWorldNeedsUpdate = true;
  7878. };
  7879. THREE.Sprite.prototype.clone = function ( object ) {
  7880. if ( object === undefined ) object = new THREE.Sprite( this.material );
  7881. THREE.Object3D.prototype.clone.call( this, object );
  7882. return object;
  7883. };
  7884. /**
  7885. * @author mrdoob / http://mrdoob.com/
  7886. */
  7887. THREE.Scene = function () {
  7888. THREE.Object3D.call( this );
  7889. this.fog = null;
  7890. this.overrideMaterial = null;
  7891. this.matrixAutoUpdate = false;
  7892. this.__objects = [];
  7893. this.__lights = [];
  7894. this.__objectsAdded = [];
  7895. this.__objectsRemoved = [];
  7896. };
  7897. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  7898. THREE.Scene.prototype.__addObject = function ( object ) {
  7899. if ( object instanceof THREE.Light ) {
  7900. if ( this.__lights.indexOf( object ) === - 1 ) {
  7901. this.__lights.push( object );
  7902. }
  7903. if ( object.target && object.target.parent === undefined ) {
  7904. this.add( object.target );
  7905. }
  7906. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  7907. if ( this.__objects.indexOf( object ) === - 1 ) {
  7908. this.__objects.push( object );
  7909. this.__objectsAdded.push( object );
  7910. // check if previously removed
  7911. var i = this.__objectsRemoved.indexOf( object );
  7912. if ( i !== -1 ) {
  7913. this.__objectsRemoved.splice( i, 1 );
  7914. }
  7915. }
  7916. }
  7917. for ( var c = 0; c < object.children.length; c ++ ) {
  7918. this.__addObject( object.children[ c ] );
  7919. }
  7920. };
  7921. THREE.Scene.prototype.__removeObject = function ( object ) {
  7922. if ( object instanceof THREE.Light ) {
  7923. var i = this.__lights.indexOf( object );
  7924. if ( i !== -1 ) {
  7925. this.__lights.splice( i, 1 );
  7926. }
  7927. } else if ( !( object instanceof THREE.Camera ) ) {
  7928. var i = this.__objects.indexOf( object );
  7929. if( i !== -1 ) {
  7930. this.__objects.splice( i, 1 );
  7931. this.__objectsRemoved.push( object );
  7932. // check if previously added
  7933. var ai = this.__objectsAdded.indexOf( object );
  7934. if ( ai !== -1 ) {
  7935. this.__objectsAdded.splice( ai, 1 );
  7936. }
  7937. }
  7938. }
  7939. for ( var c = 0; c < object.children.length; c ++ ) {
  7940. this.__removeObject( object.children[ c ] );
  7941. }
  7942. };
  7943. /**
  7944. * @author mrdoob / http://mrdoob.com/
  7945. * @author alteredq / http://alteredqualia.com/
  7946. */
  7947. THREE.Fog = function ( hex, near, far ) {
  7948. this.name = '';
  7949. this.color = new THREE.Color( hex );
  7950. this.near = ( near !== undefined ) ? near : 1;
  7951. this.far = ( far !== undefined ) ? far : 1000;
  7952. };
  7953. THREE.Fog.prototype.clone = function () {
  7954. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  7955. };
  7956. /**
  7957. * @author mrdoob / http://mrdoob.com/
  7958. * @author alteredq / http://alteredqualia.com/
  7959. */
  7960. THREE.FogExp2 = function ( hex, density ) {
  7961. this.name = '';
  7962. this.color = new THREE.Color( hex );
  7963. this.density = ( density !== undefined ) ? density : 0.00025;
  7964. };
  7965. THREE.FogExp2.prototype.clone = function () {
  7966. return new THREE.FogExp2( this.color.getHex(), this.density );
  7967. };
  7968. /**
  7969. * @author mrdoob / http://mrdoob.com/
  7970. */
  7971. THREE.CanvasRenderer = function ( parameters ) {
  7972. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  7973. var smoothstep = THREE.Math.smoothstep;
  7974. parameters = parameters || {};
  7975. var _this = this,
  7976. _renderData, _elements, _lights,
  7977. _projector = new THREE.Projector(),
  7978. _canvas = parameters.canvas !== undefined
  7979. ? parameters.canvas
  7980. : document.createElement( 'canvas' ),
  7981. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  7982. _context = _canvas.getContext( '2d' ),
  7983. _clearColor = new THREE.Color( 0x000000 ),
  7984. _clearOpacity = 0,
  7985. _contextGlobalAlpha = 1,
  7986. _contextGlobalCompositeOperation = 0,
  7987. _contextStrokeStyle = null,
  7988. _contextFillStyle = null,
  7989. _contextLineWidth = null,
  7990. _contextLineCap = null,
  7991. _contextLineJoin = null,
  7992. _contextDashSize = null,
  7993. _contextGapSize = 0,
  7994. _v1, _v2, _v3, _v4,
  7995. _v5 = new THREE.RenderableVertex(),
  7996. _v6 = new THREE.RenderableVertex(),
  7997. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  7998. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  7999. _color = new THREE.Color(),
  8000. _color1 = new THREE.Color(),
  8001. _color2 = new THREE.Color(),
  8002. _color3 = new THREE.Color(),
  8003. _color4 = new THREE.Color(),
  8004. _diffuseColor = new THREE.Color(),
  8005. _emissiveColor = new THREE.Color(),
  8006. _lightColor = new THREE.Color(),
  8007. _patterns = {}, _imagedatas = {},
  8008. _near, _far,
  8009. _image, _uvs,
  8010. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  8011. _clipBox = new THREE.Box2(),
  8012. _clearBox = new THREE.Box2(),
  8013. _elemBox = new THREE.Box2(),
  8014. _ambientLight = new THREE.Color(),
  8015. _directionalLights = new THREE.Color(),
  8016. _pointLights = new THREE.Color(),
  8017. _vector3 = new THREE.Vector3(), // Needed for PointLight
  8018. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  8019. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  8020. _pixelMap = document.createElement( 'canvas' );
  8021. _pixelMap.width = _pixelMap.height = 2;
  8022. _pixelMapContext = _pixelMap.getContext( '2d' );
  8023. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  8024. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  8025. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  8026. _pixelMapData = _pixelMapImage.data;
  8027. _gradientMap = document.createElement( 'canvas' );
  8028. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  8029. _gradientMapContext = _gradientMap.getContext( '2d' );
  8030. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  8031. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  8032. _gradientMapQuality --; // Fix UVs
  8033. // dash+gap fallbacks for Firefox and everything else
  8034. if ( _context.setLineDash === undefined ) {
  8035. if ( _context.mozDash !== undefined ) {
  8036. _context.setLineDash = function ( values ) {
  8037. _context.mozDash = values[ 0 ] !== null ? values : null;
  8038. }
  8039. } else {
  8040. _context.setLineDash = function () {}
  8041. }
  8042. }
  8043. this.domElement = _canvas;
  8044. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  8045. ? parameters.devicePixelRatio
  8046. : window.devicePixelRatio !== undefined
  8047. ? window.devicePixelRatio
  8048. : 1;
  8049. this.autoClear = true;
  8050. this.sortObjects = true;
  8051. this.sortElements = true;
  8052. this.info = {
  8053. render: {
  8054. vertices: 0,
  8055. faces: 0
  8056. }
  8057. }
  8058. // WebGLRenderer compatibility
  8059. this.supportsVertexTextures = function () {};
  8060. this.setFaceCulling = function () {};
  8061. this.setSize = function ( width, height ) {
  8062. _canvasWidth = width * this.devicePixelRatio;
  8063. _canvasHeight = height * this.devicePixelRatio;
  8064. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  8065. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  8066. _canvas.width = _canvasWidth;
  8067. _canvas.height = _canvasHeight;
  8068. _canvas.style.width = width + 'px';
  8069. _canvas.style.height = height + 'px';
  8070. _clipBox.set(
  8071. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8072. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8073. );
  8074. _clearBox.set(
  8075. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8076. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8077. );
  8078. _contextGlobalAlpha = 1;
  8079. _contextGlobalCompositeOperation = 0;
  8080. _contextStrokeStyle = null;
  8081. _contextFillStyle = null;
  8082. _contextLineWidth = null;
  8083. _contextLineCap = null;
  8084. _contextLineJoin = null;
  8085. };
  8086. this.setClearColor = function ( color, opacity ) {
  8087. _clearColor.copy( color );
  8088. _clearOpacity = opacity !== undefined ? opacity : 1;
  8089. _clearBox.set(
  8090. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8091. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8092. );
  8093. };
  8094. this.setClearColorHex = function ( hex, opacity ) {
  8095. _clearColor.setHex( hex );
  8096. _clearOpacity = opacity !== undefined ? opacity : 1;
  8097. _clearBox.set(
  8098. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8099. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8100. );
  8101. };
  8102. this.getMaxAnisotropy = function () {
  8103. return 0;
  8104. };
  8105. this.clear = function () {
  8106. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8107. if ( _clearBox.empty() === false ) {
  8108. _clearBox.intersect( _clipBox );
  8109. _clearBox.expandByScalar( 2 );
  8110. if ( _clearOpacity < 1 ) {
  8111. _context.clearRect(
  8112. _clearBox.min.x | 0,
  8113. _clearBox.min.y | 0,
  8114. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8115. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8116. );
  8117. }
  8118. if ( _clearOpacity > 0 ) {
  8119. setBlending( THREE.NormalBlending );
  8120. setOpacity( 1 );
  8121. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  8122. _context.fillRect(
  8123. _clearBox.min.x | 0,
  8124. _clearBox.min.y | 0,
  8125. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8126. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8127. );
  8128. }
  8129. _clearBox.makeEmpty();
  8130. }
  8131. };
  8132. this.render = function ( scene, camera ) {
  8133. if ( camera instanceof THREE.Camera === false ) {
  8134. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  8135. return;
  8136. }
  8137. if ( this.autoClear === true ) {
  8138. this.clear();
  8139. }
  8140. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8141. _this.info.render.vertices = 0;
  8142. _this.info.render.faces = 0;
  8143. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  8144. _elements = _renderData.elements;
  8145. _lights = _renderData.lights;
  8146. /* DEBUG
  8147. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  8148. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  8149. */
  8150. calculateLights();
  8151. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  8152. var element = _elements[ e ];
  8153. var material = element.material;
  8154. if ( material === undefined || material.visible === false ) continue;
  8155. _elemBox.makeEmpty();
  8156. if ( element instanceof THREE.RenderableParticle ) {
  8157. _v1 = element;
  8158. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  8159. renderParticle( _v1, element, material );
  8160. } else if ( element instanceof THREE.RenderableLine ) {
  8161. _v1 = element.v1; _v2 = element.v2;
  8162. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8163. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8164. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen ] );
  8165. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8166. renderLine( _v1, _v2, element, material );
  8167. }
  8168. } else if ( element instanceof THREE.RenderableFace3 ) {
  8169. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  8170. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8171. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8172. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8173. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8174. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8175. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8176. if ( material.overdraw === true ) {
  8177. expand( _v1.positionScreen, _v2.positionScreen );
  8178. expand( _v2.positionScreen, _v3.positionScreen );
  8179. expand( _v3.positionScreen, _v1.positionScreen );
  8180. }
  8181. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen ] );
  8182. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  8183. } else if ( element instanceof THREE.RenderableFace4 ) {
  8184. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  8185. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8186. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8187. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8188. if ( _v4.positionScreen.z < -1 || _v4.positionScreen.z > 1 ) continue;
  8189. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8190. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8191. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8192. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  8193. _v5.positionScreen.copy( _v2.positionScreen );
  8194. _v6.positionScreen.copy( _v4.positionScreen );
  8195. if ( material.overdraw === true ) {
  8196. expand( _v1.positionScreen, _v2.positionScreen );
  8197. expand( _v2.positionScreen, _v4.positionScreen );
  8198. expand( _v4.positionScreen, _v1.positionScreen );
  8199. expand( _v3.positionScreen, _v5.positionScreen );
  8200. expand( _v3.positionScreen, _v6.positionScreen );
  8201. }
  8202. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen, _v4.positionScreen ] );
  8203. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  8204. }
  8205. /* DEBUG
  8206. setLineWidth( 1 );
  8207. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  8208. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  8209. */
  8210. _clearBox.union( _elemBox );
  8211. }
  8212. /* DEBUG
  8213. setLineWidth( 1 );
  8214. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  8215. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  8216. */
  8217. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  8218. //
  8219. function calculateLights() {
  8220. _ambientLight.setRGB( 0, 0, 0 );
  8221. _directionalLights.setRGB( 0, 0, 0 );
  8222. _pointLights.setRGB( 0, 0, 0 );
  8223. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8224. var light = _lights[ l ];
  8225. var lightColor = light.color;
  8226. if ( light instanceof THREE.AmbientLight ) {
  8227. _ambientLight.add( lightColor );
  8228. } else if ( light instanceof THREE.DirectionalLight ) {
  8229. // for particles
  8230. _directionalLights.add( lightColor );
  8231. } else if ( light instanceof THREE.PointLight ) {
  8232. // for particles
  8233. _pointLights.add( lightColor );
  8234. }
  8235. }
  8236. }
  8237. function calculateLight( position, normal, color ) {
  8238. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8239. var light = _lights[ l ];
  8240. _lightColor.copy( light.color );
  8241. if ( light instanceof THREE.DirectionalLight ) {
  8242. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld ).normalize();
  8243. var amount = normal.dot( lightPosition );
  8244. if ( amount <= 0 ) continue;
  8245. amount *= light.intensity;
  8246. color.add( _lightColor.multiplyScalar( amount ) );
  8247. } else if ( light instanceof THREE.PointLight ) {
  8248. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld );
  8249. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  8250. if ( amount <= 0 ) continue;
  8251. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  8252. if ( amount == 0 ) continue;
  8253. amount *= light.intensity;
  8254. color.add( _lightColor.multiplyScalar( amount ) );
  8255. }
  8256. }
  8257. }
  8258. function renderParticle( v1, element, material ) {
  8259. setOpacity( material.opacity );
  8260. setBlending( material.blending );
  8261. var width, height, scaleX, scaleY,
  8262. bitmap, bitmapWidth, bitmapHeight;
  8263. if ( material instanceof THREE.ParticleBasicMaterial ) {
  8264. if ( material.map === null ) {
  8265. scaleX = element.object.scale.x;
  8266. scaleY = element.object.scale.y;
  8267. // TODO: Be able to disable this
  8268. scaleX *= element.scale.x * _canvasWidthHalf;
  8269. scaleY *= element.scale.y * _canvasHeightHalf;
  8270. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  8271. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  8272. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8273. return;
  8274. }
  8275. setFillStyle( material.color.getStyle() );
  8276. _context.save();
  8277. _context.translate( v1.x, v1.y );
  8278. _context.rotate( - element.rotation );
  8279. _context.scale( scaleX, scaleY );
  8280. _context.fillRect( -1, -1, 2, 2 );
  8281. _context.restore();
  8282. } else {
  8283. bitmap = material.map.image;
  8284. bitmapWidth = bitmap.width >> 1;
  8285. bitmapHeight = bitmap.height >> 1;
  8286. scaleX = element.scale.x * _canvasWidthHalf;
  8287. scaleY = element.scale.y * _canvasHeightHalf;
  8288. width = scaleX * bitmapWidth;
  8289. height = scaleY * bitmapHeight;
  8290. // TODO: Rotations break this...
  8291. _elemBox.min.set( v1.x - width, v1.y - height );
  8292. _elemBox.max.set( v1.x + width, v1.y + height );
  8293. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8294. return;
  8295. }
  8296. _context.save();
  8297. _context.translate( v1.x, v1.y );
  8298. _context.rotate( - element.rotation );
  8299. _context.scale( scaleX, - scaleY );
  8300. _context.translate( - bitmapWidth, - bitmapHeight );
  8301. _context.drawImage( bitmap, 0, 0 );
  8302. _context.restore();
  8303. }
  8304. /* DEBUG
  8305. setStrokeStyle( 'rgb(255,255,0)' );
  8306. _context.beginPath();
  8307. _context.moveTo( v1.x - 10, v1.y );
  8308. _context.lineTo( v1.x + 10, v1.y );
  8309. _context.moveTo( v1.x, v1.y - 10 );
  8310. _context.lineTo( v1.x, v1.y + 10 );
  8311. _context.stroke();
  8312. */
  8313. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  8314. width = element.scale.x * _canvasWidthHalf;
  8315. height = element.scale.y * _canvasHeightHalf;
  8316. _elemBox.min.set( v1.x - width, v1.y - height );
  8317. _elemBox.max.set( v1.x + width, v1.y + height );
  8318. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8319. return;
  8320. }
  8321. setStrokeStyle( material.color.getStyle() );
  8322. setFillStyle( material.color.getStyle() );
  8323. _context.save();
  8324. _context.translate( v1.x, v1.y );
  8325. _context.rotate( - element.rotation );
  8326. _context.scale( width, height );
  8327. material.program( _context );
  8328. _context.restore();
  8329. }
  8330. }
  8331. function renderLine( v1, v2, element, material ) {
  8332. setOpacity( material.opacity );
  8333. setBlending( material.blending );
  8334. _context.beginPath();
  8335. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  8336. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  8337. if ( material instanceof THREE.LineBasicMaterial ) {
  8338. setLineWidth( material.linewidth );
  8339. setLineCap( material.linecap );
  8340. setLineJoin( material.linejoin );
  8341. setStrokeStyle( material.color.getStyle() );
  8342. _context.stroke();
  8343. _elemBox.expandByScalar( material.linewidth * 2 );
  8344. } else if ( material instanceof THREE.LineDashedMaterial ) {
  8345. setLineWidth( material.linewidth );
  8346. setLineCap( material.linecap );
  8347. setLineJoin( material.linejoin );
  8348. setStrokeStyle( material.color.getStyle() );
  8349. setDashAndGap( material.dashSize, material.gapSize );
  8350. _context.stroke();
  8351. _elemBox.expandByScalar( material.linewidth * 2 );
  8352. setDashAndGap( null, null );
  8353. }
  8354. }
  8355. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  8356. _this.info.render.vertices += 3;
  8357. _this.info.render.faces ++;
  8358. setOpacity( material.opacity );
  8359. setBlending( material.blending );
  8360. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8361. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8362. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8363. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  8364. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  8365. _diffuseColor.copy( material.color );
  8366. _emissiveColor.copy( material.emissive );
  8367. if ( material.vertexColors === THREE.FaceColors ) {
  8368. _diffuseColor.multiply( element.color );
  8369. }
  8370. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  8371. _color1.copy( _ambientLight );
  8372. _color2.copy( _ambientLight );
  8373. _color3.copy( _ambientLight );
  8374. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8375. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8376. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  8377. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8378. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8379. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8380. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8381. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8382. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8383. } else {
  8384. _color.copy( _ambientLight );
  8385. calculateLight( element.centroidModel, element.normalModel, _color );
  8386. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8387. material.wireframe === true
  8388. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8389. : fillPath( _color );
  8390. }
  8391. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8392. if ( material.map !== null ) {
  8393. if ( material.map.mapping instanceof THREE.UVMapping ) {
  8394. _uvs = element.uvs[ 0 ];
  8395. 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 );
  8396. }
  8397. } else if ( material.envMap !== null ) {
  8398. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  8399. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  8400. _uv1x = 0.5 * _vector3.x + 0.5;
  8401. _uv1y = 0.5 * _vector3.y + 0.5;
  8402. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  8403. _uv2x = 0.5 * _vector3.x + 0.5;
  8404. _uv2y = 0.5 * _vector3.y + 0.5;
  8405. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  8406. _uv3x = 0.5 * _vector3.x + 0.5;
  8407. _uv3y = 0.5 * _vector3.y + 0.5;
  8408. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  8409. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  8410. }*/
  8411. } else {
  8412. _color.copy( material.color );
  8413. if ( material.vertexColors === THREE.FaceColors ) {
  8414. _color.multiply( element.color );
  8415. }
  8416. material.wireframe === true
  8417. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8418. : fillPath( _color );
  8419. }
  8420. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8421. _near = camera.near;
  8422. _far = camera.far;
  8423. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  8424. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  8425. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  8426. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8427. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8428. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8429. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8430. var normal;
  8431. if ( material.shading == THREE.FlatShading ) {
  8432. normal = element.normalModelView;
  8433. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8434. material.wireframe === true
  8435. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8436. : fillPath( _color );
  8437. } else if ( material.shading == THREE.SmoothShading ) {
  8438. normal = element.vertexNormalsModelView[ uv1 ];
  8439. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8440. normal = element.vertexNormalsModelView[ uv2 ];
  8441. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8442. normal = element.vertexNormalsModelView[ uv3 ];
  8443. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8444. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8445. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8446. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8447. }
  8448. }
  8449. }
  8450. function renderFace4( v1, v2, v3, v4, v5, v6, element, material ) {
  8451. _this.info.render.vertices += 4;
  8452. _this.info.render.faces ++;
  8453. setOpacity( material.opacity );
  8454. setBlending( material.blending );
  8455. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  8456. // Let renderFace3() handle this
  8457. renderFace3( v1, v2, v4, 0, 1, 3, element, material );
  8458. renderFace3( v5, v3, v6, 1, 2, 3, element, material );
  8459. return;
  8460. }
  8461. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8462. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8463. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8464. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  8465. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  8466. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  8467. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8468. _diffuseColor.copy( material.color );
  8469. _emissiveColor.copy( material.emissive );
  8470. if ( material.vertexColors === THREE.FaceColors ) {
  8471. _diffuseColor.multiply( element.color );
  8472. }
  8473. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  8474. _color1.copy( _ambientLight );
  8475. _color2.copy( _ambientLight );
  8476. _color3.copy( _ambientLight );
  8477. _color4.copy( _ambientLight );
  8478. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8479. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8480. calculateLight( element.v4.positionWorld, element.vertexNormalsModel[ 3 ], _color3 );
  8481. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color4 );
  8482. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8483. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8484. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8485. _color4.multiply( _diffuseColor ).add( _emissiveColor );
  8486. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8487. // TODO: UVs are incorrect, v4->v3?
  8488. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8489. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8490. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8491. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8492. } else {
  8493. _color.copy( _ambientLight );
  8494. calculateLight( element.centroidModel, element.normalModel, _color );
  8495. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8496. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8497. material.wireframe === true
  8498. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8499. : fillPath( _color );
  8500. }
  8501. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  8502. _color.copy( material.color );
  8503. if ( material.vertexColors === THREE.FaceColors ) {
  8504. _color.multiply( element.color );
  8505. }
  8506. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8507. material.wireframe === true
  8508. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8509. : fillPath( _color );
  8510. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8511. var normal;
  8512. if ( material.shading == THREE.FlatShading ) {
  8513. normal = element.normalModelView;
  8514. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8515. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8516. material.wireframe === true
  8517. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8518. : fillPath( _color );
  8519. } else if ( material.shading == THREE.SmoothShading ) {
  8520. normal = element.vertexNormalsModelView[ 0 ];
  8521. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8522. normal = element.vertexNormalsModelView[ 1 ];
  8523. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8524. normal = element.vertexNormalsModelView[ 3 ];
  8525. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8526. normal = element.vertexNormalsModelView[ 2 ];
  8527. _color4.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8528. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8529. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8530. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8531. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8532. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8533. }
  8534. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8535. _near = camera.near;
  8536. _far = camera.far;
  8537. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  8538. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  8539. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z * v4.positionScreen.w, _near, _far );
  8540. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  8541. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8542. // TODO: UVs are incorrect, v4->v3?
  8543. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8544. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8545. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8546. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8547. }
  8548. }
  8549. //
  8550. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  8551. _context.beginPath();
  8552. _context.moveTo( x0, y0 );
  8553. _context.lineTo( x1, y1 );
  8554. _context.lineTo( x2, y2 );
  8555. _context.closePath();
  8556. }
  8557. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  8558. _context.beginPath();
  8559. _context.moveTo( x0, y0 );
  8560. _context.lineTo( x1, y1 );
  8561. _context.lineTo( x2, y2 );
  8562. _context.lineTo( x3, y3 );
  8563. _context.closePath();
  8564. }
  8565. function strokePath( color, linewidth, linecap, linejoin ) {
  8566. setLineWidth( linewidth );
  8567. setLineCap( linecap );
  8568. setLineJoin( linejoin );
  8569. setStrokeStyle( color.getStyle() );
  8570. _context.stroke();
  8571. _elemBox.expandByScalar( linewidth * 2 );
  8572. }
  8573. function fillPath( color ) {
  8574. setFillStyle( color.getStyle() );
  8575. _context.fill();
  8576. }
  8577. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  8578. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  8579. if ( texture.needsUpdate === true ) {
  8580. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  8581. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  8582. _patterns[ texture.id ] = _context.createPattern(
  8583. texture.image, repeatX === true && repeatY === true
  8584. ? 'repeat'
  8585. : repeatX === true && repeatY === false
  8586. ? 'repeat-x'
  8587. : repeatX === false && repeatY === true
  8588. ? 'repeat-y'
  8589. : 'no-repeat'
  8590. );
  8591. texture.needsUpdate = false;
  8592. }
  8593. _patterns[ texture.id ] === undefined
  8594. ? setFillStyle( 'rgba(0,0,0,1)' )
  8595. : setFillStyle( _patterns[ texture.id ] );
  8596. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8597. var a, b, c, d, e, f, det, idet,
  8598. offsetX = texture.offset.x / texture.repeat.x,
  8599. offsetY = texture.offset.y / texture.repeat.y,
  8600. width = texture.image.width * texture.repeat.x,
  8601. height = texture.image.height * texture.repeat.y;
  8602. u0 = ( u0 + offsetX ) * width;
  8603. v0 = ( 1.0 - v0 + offsetY ) * height;
  8604. u1 = ( u1 + offsetX ) * width;
  8605. v1 = ( 1.0 - v1 + offsetY ) * height;
  8606. u2 = ( u2 + offsetX ) * width;
  8607. v2 = ( 1.0 - v2 + offsetY ) * height;
  8608. x1 -= x0; y1 -= y0;
  8609. x2 -= x0; y2 -= y0;
  8610. u1 -= u0; v1 -= v0;
  8611. u2 -= u0; v2 -= v0;
  8612. det = u1 * v2 - u2 * v1;
  8613. if ( det === 0 ) {
  8614. if ( _imagedatas[ texture.id ] === undefined ) {
  8615. var canvas = document.createElement( 'canvas' )
  8616. canvas.width = texture.image.width;
  8617. canvas.height = texture.image.height;
  8618. var context = canvas.getContext( '2d' );
  8619. context.drawImage( texture.image, 0, 0 );
  8620. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  8621. }
  8622. var data = _imagedatas[ texture.id ];
  8623. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  8624. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  8625. fillPath( _color );
  8626. return;
  8627. }
  8628. idet = 1 / det;
  8629. a = ( v2 * x1 - v1 * x2 ) * idet;
  8630. b = ( v2 * y1 - v1 * y2 ) * idet;
  8631. c = ( u1 * x2 - u2 * x1 ) * idet;
  8632. d = ( u1 * y2 - u2 * y1 ) * idet;
  8633. e = x0 - a * u0 - c * v0;
  8634. f = y0 - b * u0 - d * v0;
  8635. _context.save();
  8636. _context.transform( a, b, c, d, e, f );
  8637. _context.fill();
  8638. _context.restore();
  8639. }
  8640. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  8641. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8642. var a, b, c, d, e, f, det, idet,
  8643. width = image.width - 1,
  8644. height = image.height - 1;
  8645. u0 *= width; v0 *= height;
  8646. u1 *= width; v1 *= height;
  8647. u2 *= width; v2 *= height;
  8648. x1 -= x0; y1 -= y0;
  8649. x2 -= x0; y2 -= y0;
  8650. u1 -= u0; v1 -= v0;
  8651. u2 -= u0; v2 -= v0;
  8652. det = u1 * v2 - u2 * v1;
  8653. idet = 1 / det;
  8654. a = ( v2 * x1 - v1 * x2 ) * idet;
  8655. b = ( v2 * y1 - v1 * y2 ) * idet;
  8656. c = ( u1 * x2 - u2 * x1 ) * idet;
  8657. d = ( u1 * y2 - u2 * y1 ) * idet;
  8658. e = x0 - a * u0 - c * v0;
  8659. f = y0 - b * u0 - d * v0;
  8660. _context.save();
  8661. _context.transform( a, b, c, d, e, f );
  8662. _context.clip();
  8663. _context.drawImage( image, 0, 0 );
  8664. _context.restore();
  8665. }
  8666. function getGradientTexture( color1, color2, color3, color4 ) {
  8667. // http://mrdoob.com/blog/post/710
  8668. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  8669. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  8670. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  8671. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  8672. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  8673. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  8674. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  8675. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  8676. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  8677. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  8678. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  8679. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  8680. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  8681. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  8682. return _gradientMap;
  8683. }
  8684. // Hide anti-alias gaps
  8685. function expand( v1, v2 ) {
  8686. var x = v2.x - v1.x, y = v2.y - v1.y,
  8687. det = x * x + y * y, idet;
  8688. if ( det === 0 ) return;
  8689. idet = 1 / Math.sqrt( det );
  8690. x *= idet; y *= idet;
  8691. v2.x += x; v2.y += y;
  8692. v1.x -= x; v1.y -= y;
  8693. }
  8694. };
  8695. // Context cached methods.
  8696. function setOpacity( value ) {
  8697. if ( _contextGlobalAlpha !== value ) {
  8698. _context.globalAlpha = value;
  8699. _contextGlobalAlpha = value;
  8700. }
  8701. }
  8702. function setBlending( value ) {
  8703. if ( _contextGlobalCompositeOperation !== value ) {
  8704. if ( value === THREE.NormalBlending ) {
  8705. _context.globalCompositeOperation = 'source-over';
  8706. } else if ( value === THREE.AdditiveBlending ) {
  8707. _context.globalCompositeOperation = 'lighter';
  8708. } else if ( value === THREE.SubtractiveBlending ) {
  8709. _context.globalCompositeOperation = 'darker';
  8710. }
  8711. _contextGlobalCompositeOperation = value;
  8712. }
  8713. }
  8714. function setLineWidth( value ) {
  8715. if ( _contextLineWidth !== value ) {
  8716. _context.lineWidth = value;
  8717. _contextLineWidth = value;
  8718. }
  8719. }
  8720. function setLineCap( value ) {
  8721. // "butt", "round", "square"
  8722. if ( _contextLineCap !== value ) {
  8723. _context.lineCap = value;
  8724. _contextLineCap = value;
  8725. }
  8726. }
  8727. function setLineJoin( value ) {
  8728. // "round", "bevel", "miter"
  8729. if ( _contextLineJoin !== value ) {
  8730. _context.lineJoin = value;
  8731. _contextLineJoin = value;
  8732. }
  8733. }
  8734. function setStrokeStyle( value ) {
  8735. if ( _contextStrokeStyle !== value ) {
  8736. _context.strokeStyle = value;
  8737. _contextStrokeStyle = value;
  8738. }
  8739. }
  8740. function setFillStyle( value ) {
  8741. if ( _contextFillStyle !== value ) {
  8742. _context.fillStyle = value;
  8743. _contextFillStyle = value;
  8744. }
  8745. }
  8746. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  8747. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  8748. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  8749. _contextDashSize = dashSizeValue;
  8750. _contextGapSize = gapSizeValue;
  8751. }
  8752. }
  8753. };
  8754. /**
  8755. * @author alteredq / http://alteredqualia.com/
  8756. * @author mrdoob / http://mrdoob.com/
  8757. * @author mikael emtinger / http://gomo.se/
  8758. */
  8759. THREE.ShaderChunk = {
  8760. // FOG
  8761. fog_pars_fragment: [
  8762. "#ifdef USE_FOG",
  8763. "uniform vec3 fogColor;",
  8764. "#ifdef FOG_EXP2",
  8765. "uniform float fogDensity;",
  8766. "#else",
  8767. "uniform float fogNear;",
  8768. "uniform float fogFar;",
  8769. "#endif",
  8770. "#endif"
  8771. ].join("\n"),
  8772. fog_fragment: [
  8773. "#ifdef USE_FOG",
  8774. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  8775. "#ifdef FOG_EXP2",
  8776. "const float LOG2 = 1.442695;",
  8777. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  8778. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  8779. "#else",
  8780. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  8781. "#endif",
  8782. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  8783. "#endif"
  8784. ].join("\n"),
  8785. // ENVIRONMENT MAP
  8786. envmap_pars_fragment: [
  8787. "#ifdef USE_ENVMAP",
  8788. "uniform float reflectivity;",
  8789. "uniform samplerCube envMap;",
  8790. "uniform float flipEnvMap;",
  8791. "uniform int combine;",
  8792. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8793. "uniform bool useRefract;",
  8794. "uniform float refractionRatio;",
  8795. "#else",
  8796. "varying vec3 vReflect;",
  8797. "#endif",
  8798. "#endif"
  8799. ].join("\n"),
  8800. envmap_fragment: [
  8801. "#ifdef USE_ENVMAP",
  8802. "vec3 reflectVec;",
  8803. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8804. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  8805. "if ( useRefract ) {",
  8806. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  8807. "} else { ",
  8808. "reflectVec = reflect( cameraToVertex, normal );",
  8809. "}",
  8810. "#else",
  8811. "reflectVec = vReflect;",
  8812. "#endif",
  8813. "#ifdef DOUBLE_SIDED",
  8814. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8815. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8816. "#else",
  8817. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8818. "#endif",
  8819. "#ifdef GAMMA_INPUT",
  8820. "cubeColor.xyz *= cubeColor.xyz;",
  8821. "#endif",
  8822. "if ( combine == 1 ) {",
  8823. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  8824. "} else if ( combine == 2 ) {",
  8825. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  8826. "} else {",
  8827. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  8828. "}",
  8829. "#endif"
  8830. ].join("\n"),
  8831. envmap_pars_vertex: [
  8832. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8833. "varying vec3 vReflect;",
  8834. "uniform float refractionRatio;",
  8835. "uniform bool useRefract;",
  8836. "#endif"
  8837. ].join("\n"),
  8838. worldpos_vertex : [
  8839. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  8840. "#ifdef USE_SKINNING",
  8841. "vec4 worldPosition = modelMatrix * skinned;",
  8842. "#endif",
  8843. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8844. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  8845. "#endif",
  8846. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8847. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  8848. "#endif",
  8849. "#endif"
  8850. ].join("\n"),
  8851. envmap_vertex : [
  8852. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8853. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  8854. "worldNormal = normalize( worldNormal );",
  8855. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  8856. "if ( useRefract ) {",
  8857. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  8858. "} else {",
  8859. "vReflect = reflect( cameraToVertex, worldNormal );",
  8860. "}",
  8861. "#endif"
  8862. ].join("\n"),
  8863. // COLOR MAP (particles)
  8864. map_particle_pars_fragment: [
  8865. "#ifdef USE_MAP",
  8866. "uniform sampler2D map;",
  8867. "#endif"
  8868. ].join("\n"),
  8869. map_particle_fragment: [
  8870. "#ifdef USE_MAP",
  8871. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  8872. "#endif"
  8873. ].join("\n"),
  8874. // COLOR MAP (triangles)
  8875. map_pars_vertex: [
  8876. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8877. "varying vec2 vUv;",
  8878. "uniform vec4 offsetRepeat;",
  8879. "#endif"
  8880. ].join("\n"),
  8881. map_pars_fragment: [
  8882. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8883. "varying vec2 vUv;",
  8884. "#endif",
  8885. "#ifdef USE_MAP",
  8886. "uniform sampler2D map;",
  8887. "#endif"
  8888. ].join("\n"),
  8889. map_vertex: [
  8890. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8891. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  8892. "#endif"
  8893. ].join("\n"),
  8894. map_fragment: [
  8895. "#ifdef USE_MAP",
  8896. "vec4 texelColor = texture2D( map, vUv );",
  8897. "#ifdef GAMMA_INPUT",
  8898. "texelColor.xyz *= texelColor.xyz;",
  8899. "#endif",
  8900. "gl_FragColor = gl_FragColor * texelColor;",
  8901. "#endif"
  8902. ].join("\n"),
  8903. // LIGHT MAP
  8904. lightmap_pars_fragment: [
  8905. "#ifdef USE_LIGHTMAP",
  8906. "varying vec2 vUv2;",
  8907. "uniform sampler2D lightMap;",
  8908. "#endif"
  8909. ].join("\n"),
  8910. lightmap_pars_vertex: [
  8911. "#ifdef USE_LIGHTMAP",
  8912. "varying vec2 vUv2;",
  8913. "#endif"
  8914. ].join("\n"),
  8915. lightmap_fragment: [
  8916. "#ifdef USE_LIGHTMAP",
  8917. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  8918. "#endif"
  8919. ].join("\n"),
  8920. lightmap_vertex: [
  8921. "#ifdef USE_LIGHTMAP",
  8922. "vUv2 = uv2;",
  8923. "#endif"
  8924. ].join("\n"),
  8925. // BUMP MAP
  8926. bumpmap_pars_fragment: [
  8927. "#ifdef USE_BUMPMAP",
  8928. "uniform sampler2D bumpMap;",
  8929. "uniform float bumpScale;",
  8930. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  8931. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  8932. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8933. "vec2 dHdxy_fwd() {",
  8934. "vec2 dSTdx = dFdx( vUv );",
  8935. "vec2 dSTdy = dFdy( vUv );",
  8936. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  8937. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  8938. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  8939. "return vec2( dBx, dBy );",
  8940. "}",
  8941. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  8942. "vec3 vSigmaX = dFdx( surf_pos );",
  8943. "vec3 vSigmaY = dFdy( surf_pos );",
  8944. "vec3 vN = surf_norm;", // normalized
  8945. "vec3 R1 = cross( vSigmaY, vN );",
  8946. "vec3 R2 = cross( vN, vSigmaX );",
  8947. "float fDet = dot( vSigmaX, R1 );",
  8948. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  8949. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  8950. "}",
  8951. "#endif"
  8952. ].join("\n"),
  8953. // NORMAL MAP
  8954. normalmap_pars_fragment: [
  8955. "#ifdef USE_NORMALMAP",
  8956. "uniform sampler2D normalMap;",
  8957. "uniform vec2 normalScale;",
  8958. // Per-Pixel Tangent Space Normal Mapping
  8959. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  8960. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  8961. "vec3 q0 = dFdx( eye_pos.xyz );",
  8962. "vec3 q1 = dFdy( eye_pos.xyz );",
  8963. "vec2 st0 = dFdx( vUv.st );",
  8964. "vec2 st1 = dFdy( vUv.st );",
  8965. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  8966. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  8967. "vec3 N = normalize( surf_norm );",
  8968. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  8969. "mapN.xy = normalScale * mapN.xy;",
  8970. "mat3 tsn = mat3( S, T, N );",
  8971. "return normalize( tsn * mapN );",
  8972. "}",
  8973. "#endif"
  8974. ].join("\n"),
  8975. // SPECULAR MAP
  8976. specularmap_pars_fragment: [
  8977. "#ifdef USE_SPECULARMAP",
  8978. "uniform sampler2D specularMap;",
  8979. "#endif"
  8980. ].join("\n"),
  8981. specularmap_fragment: [
  8982. "float specularStrength;",
  8983. "#ifdef USE_SPECULARMAP",
  8984. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  8985. "specularStrength = texelSpecular.r;",
  8986. "#else",
  8987. "specularStrength = 1.0;",
  8988. "#endif"
  8989. ].join("\n"),
  8990. // LIGHTS LAMBERT
  8991. lights_lambert_pars_vertex: [
  8992. "uniform vec3 ambient;",
  8993. "uniform vec3 diffuse;",
  8994. "uniform vec3 emissive;",
  8995. "uniform vec3 ambientLightColor;",
  8996. "#if MAX_DIR_LIGHTS > 0",
  8997. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8998. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8999. "#endif",
  9000. "#if MAX_HEMI_LIGHTS > 0",
  9001. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9002. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9003. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9004. "#endif",
  9005. "#if MAX_POINT_LIGHTS > 0",
  9006. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9007. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9008. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9009. "#endif",
  9010. "#if MAX_SPOT_LIGHTS > 0",
  9011. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9012. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9013. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9014. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9015. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9016. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9017. "#endif",
  9018. "#ifdef WRAP_AROUND",
  9019. "uniform vec3 wrapRGB;",
  9020. "#endif"
  9021. ].join("\n"),
  9022. lights_lambert_vertex: [
  9023. "vLightFront = vec3( 0.0 );",
  9024. "#ifdef DOUBLE_SIDED",
  9025. "vLightBack = vec3( 0.0 );",
  9026. "#endif",
  9027. "transformedNormal = normalize( transformedNormal );",
  9028. "#if MAX_DIR_LIGHTS > 0",
  9029. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9030. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9031. "vec3 dirVector = normalize( lDirection.xyz );",
  9032. "float dotProduct = dot( transformedNormal, dirVector );",
  9033. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9034. "#ifdef DOUBLE_SIDED",
  9035. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9036. "#ifdef WRAP_AROUND",
  9037. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9038. "#endif",
  9039. "#endif",
  9040. "#ifdef WRAP_AROUND",
  9041. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9042. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  9043. "#ifdef DOUBLE_SIDED",
  9044. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  9045. "#endif",
  9046. "#endif",
  9047. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  9048. "#ifdef DOUBLE_SIDED",
  9049. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  9050. "#endif",
  9051. "}",
  9052. "#endif",
  9053. "#if MAX_POINT_LIGHTS > 0",
  9054. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9055. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9056. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9057. "float lDistance = 1.0;",
  9058. "if ( pointLightDistance[ i ] > 0.0 )",
  9059. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9060. "lVector = normalize( lVector );",
  9061. "float dotProduct = dot( transformedNormal, lVector );",
  9062. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9063. "#ifdef DOUBLE_SIDED",
  9064. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9065. "#ifdef WRAP_AROUND",
  9066. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9067. "#endif",
  9068. "#endif",
  9069. "#ifdef WRAP_AROUND",
  9070. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9071. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  9072. "#ifdef DOUBLE_SIDED",
  9073. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  9074. "#endif",
  9075. "#endif",
  9076. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  9077. "#ifdef DOUBLE_SIDED",
  9078. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  9079. "#endif",
  9080. "}",
  9081. "#endif",
  9082. "#if MAX_SPOT_LIGHTS > 0",
  9083. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9084. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9085. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9086. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  9087. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9088. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9089. "float lDistance = 1.0;",
  9090. "if ( spotLightDistance[ i ] > 0.0 )",
  9091. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9092. "lVector = normalize( lVector );",
  9093. "float dotProduct = dot( transformedNormal, lVector );",
  9094. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9095. "#ifdef DOUBLE_SIDED",
  9096. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9097. "#ifdef WRAP_AROUND",
  9098. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9099. "#endif",
  9100. "#endif",
  9101. "#ifdef WRAP_AROUND",
  9102. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9103. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  9104. "#ifdef DOUBLE_SIDED",
  9105. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  9106. "#endif",
  9107. "#endif",
  9108. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  9109. "#ifdef DOUBLE_SIDED",
  9110. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  9111. "#endif",
  9112. "}",
  9113. "}",
  9114. "#endif",
  9115. "#if MAX_HEMI_LIGHTS > 0",
  9116. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9117. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9118. "vec3 lVector = normalize( lDirection.xyz );",
  9119. "float dotProduct = dot( transformedNormal, lVector );",
  9120. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9121. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  9122. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9123. "#ifdef DOUBLE_SIDED",
  9124. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  9125. "#endif",
  9126. "}",
  9127. "#endif",
  9128. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  9129. "#ifdef DOUBLE_SIDED",
  9130. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  9131. "#endif"
  9132. ].join("\n"),
  9133. // LIGHTS PHONG
  9134. lights_phong_pars_vertex: [
  9135. "#ifndef PHONG_PER_PIXEL",
  9136. "#if MAX_POINT_LIGHTS > 0",
  9137. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9138. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9139. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9140. "#endif",
  9141. "#if MAX_SPOT_LIGHTS > 0",
  9142. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9143. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9144. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9145. "#endif",
  9146. "#endif",
  9147. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9148. "varying vec3 vWorldPosition;",
  9149. "#endif"
  9150. ].join("\n"),
  9151. lights_phong_vertex: [
  9152. "#ifndef PHONG_PER_PIXEL",
  9153. "#if MAX_POINT_LIGHTS > 0",
  9154. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9155. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9156. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9157. "float lDistance = 1.0;",
  9158. "if ( pointLightDistance[ i ] > 0.0 )",
  9159. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9160. "vPointLight[ i ] = vec4( lVector, lDistance );",
  9161. "}",
  9162. "#endif",
  9163. "#if MAX_SPOT_LIGHTS > 0",
  9164. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9165. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9166. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9167. "float lDistance = 1.0;",
  9168. "if ( spotLightDistance[ i ] > 0.0 )",
  9169. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9170. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  9171. "}",
  9172. "#endif",
  9173. "#endif",
  9174. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9175. "vWorldPosition = worldPosition.xyz;",
  9176. "#endif"
  9177. ].join("\n"),
  9178. lights_phong_pars_fragment: [
  9179. "uniform vec3 ambientLightColor;",
  9180. "#if MAX_DIR_LIGHTS > 0",
  9181. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9182. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9183. "#endif",
  9184. "#if MAX_HEMI_LIGHTS > 0",
  9185. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9186. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9187. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9188. "#endif",
  9189. "#if MAX_POINT_LIGHTS > 0",
  9190. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9191. "#ifdef PHONG_PER_PIXEL",
  9192. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9193. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9194. "#else",
  9195. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9196. "#endif",
  9197. "#endif",
  9198. "#if MAX_SPOT_LIGHTS > 0",
  9199. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9200. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9201. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9202. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9203. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9204. "#ifdef PHONG_PER_PIXEL",
  9205. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9206. "#else",
  9207. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9208. "#endif",
  9209. "#endif",
  9210. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9211. "varying vec3 vWorldPosition;",
  9212. "#endif",
  9213. "#ifdef WRAP_AROUND",
  9214. "uniform vec3 wrapRGB;",
  9215. "#endif",
  9216. "varying vec3 vViewPosition;",
  9217. "varying vec3 vNormal;"
  9218. ].join("\n"),
  9219. lights_phong_fragment: [
  9220. "vec3 normal = normalize( vNormal );",
  9221. "vec3 viewPosition = normalize( vViewPosition );",
  9222. "#ifdef DOUBLE_SIDED",
  9223. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9224. "#endif",
  9225. "#ifdef USE_NORMALMAP",
  9226. "normal = perturbNormal2Arb( -viewPosition, normal );",
  9227. "#elif defined( USE_BUMPMAP )",
  9228. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  9229. "#endif",
  9230. "#if MAX_POINT_LIGHTS > 0",
  9231. "vec3 pointDiffuse = vec3( 0.0 );",
  9232. "vec3 pointSpecular = vec3( 0.0 );",
  9233. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9234. "#ifdef PHONG_PER_PIXEL",
  9235. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9236. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9237. "float lDistance = 1.0;",
  9238. "if ( pointLightDistance[ i ] > 0.0 )",
  9239. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9240. "lVector = normalize( lVector );",
  9241. "#else",
  9242. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  9243. "float lDistance = vPointLight[ i ].w;",
  9244. "#endif",
  9245. // diffuse
  9246. "float dotProduct = dot( normal, lVector );",
  9247. "#ifdef WRAP_AROUND",
  9248. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  9249. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9250. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  9251. "#else",
  9252. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  9253. "#endif",
  9254. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  9255. // specular
  9256. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  9257. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  9258. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  9259. "#ifdef PHYSICALLY_BASED_SHADING",
  9260. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9261. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9262. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  9263. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  9264. "#else",
  9265. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  9266. "#endif",
  9267. "}",
  9268. "#endif",
  9269. "#if MAX_SPOT_LIGHTS > 0",
  9270. "vec3 spotDiffuse = vec3( 0.0 );",
  9271. "vec3 spotSpecular = vec3( 0.0 );",
  9272. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9273. "#ifdef PHONG_PER_PIXEL",
  9274. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9275. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9276. "float lDistance = 1.0;",
  9277. "if ( spotLightDistance[ i ] > 0.0 )",
  9278. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9279. "lVector = normalize( lVector );",
  9280. "#else",
  9281. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  9282. "float lDistance = vSpotLight[ i ].w;",
  9283. "#endif",
  9284. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  9285. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9286. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9287. // diffuse
  9288. "float dotProduct = dot( normal, lVector );",
  9289. "#ifdef WRAP_AROUND",
  9290. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  9291. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9292. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  9293. "#else",
  9294. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  9295. "#endif",
  9296. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  9297. // specular
  9298. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  9299. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  9300. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  9301. "#ifdef PHYSICALLY_BASED_SHADING",
  9302. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9303. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9304. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  9305. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  9306. "#else",
  9307. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  9308. "#endif",
  9309. "}",
  9310. "}",
  9311. "#endif",
  9312. "#if MAX_DIR_LIGHTS > 0",
  9313. "vec3 dirDiffuse = vec3( 0.0 );",
  9314. "vec3 dirSpecular = vec3( 0.0 );" ,
  9315. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9316. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9317. "vec3 dirVector = normalize( lDirection.xyz );",
  9318. // diffuse
  9319. "float dotProduct = dot( normal, dirVector );",
  9320. "#ifdef WRAP_AROUND",
  9321. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  9322. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9323. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  9324. "#else",
  9325. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  9326. "#endif",
  9327. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  9328. // specular
  9329. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  9330. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  9331. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  9332. "#ifdef PHYSICALLY_BASED_SHADING",
  9333. /*
  9334. // fresnel term from skin shader
  9335. "const float F0 = 0.128;",
  9336. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  9337. "float exponential = pow( base, 5.0 );",
  9338. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  9339. */
  9340. /*
  9341. // fresnel term from fresnel shader
  9342. "const float mFresnelBias = 0.08;",
  9343. "const float mFresnelScale = 0.3;",
  9344. "const float mFresnelPower = 5.0;",
  9345. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  9346. */
  9347. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9348. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9349. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  9350. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  9351. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  9352. "#else",
  9353. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  9354. "#endif",
  9355. "}",
  9356. "#endif",
  9357. "#if MAX_HEMI_LIGHTS > 0",
  9358. "vec3 hemiDiffuse = vec3( 0.0 );",
  9359. "vec3 hemiSpecular = vec3( 0.0 );" ,
  9360. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9361. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9362. "vec3 lVector = normalize( lDirection.xyz );",
  9363. // diffuse
  9364. "float dotProduct = dot( normal, lVector );",
  9365. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9366. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9367. "hemiDiffuse += diffuse * hemiColor;",
  9368. // specular (sky light)
  9369. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  9370. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  9371. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  9372. // specular (ground light)
  9373. "vec3 lVectorGround = -lVector;",
  9374. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  9375. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  9376. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  9377. "#ifdef PHYSICALLY_BASED_SHADING",
  9378. "float dotProductGround = dot( normal, lVectorGround );",
  9379. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9380. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9381. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  9382. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  9383. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  9384. "#else",
  9385. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  9386. "#endif",
  9387. "}",
  9388. "#endif",
  9389. "vec3 totalDiffuse = vec3( 0.0 );",
  9390. "vec3 totalSpecular = vec3( 0.0 );",
  9391. "#if MAX_DIR_LIGHTS > 0",
  9392. "totalDiffuse += dirDiffuse;",
  9393. "totalSpecular += dirSpecular;",
  9394. "#endif",
  9395. "#if MAX_HEMI_LIGHTS > 0",
  9396. "totalDiffuse += hemiDiffuse;",
  9397. "totalSpecular += hemiSpecular;",
  9398. "#endif",
  9399. "#if MAX_POINT_LIGHTS > 0",
  9400. "totalDiffuse += pointDiffuse;",
  9401. "totalSpecular += pointSpecular;",
  9402. "#endif",
  9403. "#if MAX_SPOT_LIGHTS > 0",
  9404. "totalDiffuse += spotDiffuse;",
  9405. "totalSpecular += spotSpecular;",
  9406. "#endif",
  9407. "#ifdef METAL",
  9408. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  9409. "#else",
  9410. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  9411. "#endif"
  9412. ].join("\n"),
  9413. // VERTEX COLORS
  9414. color_pars_fragment: [
  9415. "#ifdef USE_COLOR",
  9416. "varying vec3 vColor;",
  9417. "#endif"
  9418. ].join("\n"),
  9419. color_fragment: [
  9420. "#ifdef USE_COLOR",
  9421. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  9422. "#endif"
  9423. ].join("\n"),
  9424. color_pars_vertex: [
  9425. "#ifdef USE_COLOR",
  9426. "varying vec3 vColor;",
  9427. "#endif"
  9428. ].join("\n"),
  9429. color_vertex: [
  9430. "#ifdef USE_COLOR",
  9431. "#ifdef GAMMA_INPUT",
  9432. "vColor = color * color;",
  9433. "#else",
  9434. "vColor = color;",
  9435. "#endif",
  9436. "#endif"
  9437. ].join("\n"),
  9438. // SKINNING
  9439. skinning_pars_vertex: [
  9440. "#ifdef USE_SKINNING",
  9441. "#ifdef BONE_TEXTURE",
  9442. "uniform sampler2D boneTexture;",
  9443. "mat4 getBoneMatrix( const in float i ) {",
  9444. "float j = i * 4.0;",
  9445. "float x = mod( j, N_BONE_PIXEL_X );",
  9446. "float y = floor( j / N_BONE_PIXEL_X );",
  9447. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  9448. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  9449. "y = dy * ( y + 0.5 );",
  9450. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  9451. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  9452. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  9453. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  9454. "mat4 bone = mat4( v1, v2, v3, v4 );",
  9455. "return bone;",
  9456. "}",
  9457. "#else",
  9458. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  9459. "mat4 getBoneMatrix( const in float i ) {",
  9460. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  9461. "return bone;",
  9462. "}",
  9463. "#endif",
  9464. "#endif"
  9465. ].join("\n"),
  9466. skinbase_vertex: [
  9467. "#ifdef USE_SKINNING",
  9468. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  9469. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  9470. "#endif"
  9471. ].join("\n"),
  9472. skinning_vertex: [
  9473. "#ifdef USE_SKINNING",
  9474. "#ifdef USE_MORPHTARGETS",
  9475. "vec4 skinVertex = vec4( morphed, 1.0 );",
  9476. "#else",
  9477. "vec4 skinVertex = vec4( position, 1.0 );",
  9478. "#endif",
  9479. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  9480. "skinned += boneMatY * skinVertex * skinWeight.y;",
  9481. "#endif"
  9482. ].join("\n"),
  9483. // MORPHING
  9484. morphtarget_pars_vertex: [
  9485. "#ifdef USE_MORPHTARGETS",
  9486. "#ifndef USE_MORPHNORMALS",
  9487. "uniform float morphTargetInfluences[ 8 ];",
  9488. "#else",
  9489. "uniform float morphTargetInfluences[ 4 ];",
  9490. "#endif",
  9491. "#endif"
  9492. ].join("\n"),
  9493. morphtarget_vertex: [
  9494. "#ifdef USE_MORPHTARGETS",
  9495. "vec3 morphed = vec3( 0.0 );",
  9496. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  9497. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  9498. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  9499. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  9500. "#ifndef USE_MORPHNORMALS",
  9501. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  9502. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  9503. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  9504. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  9505. "#endif",
  9506. "morphed += position;",
  9507. "#endif"
  9508. ].join("\n"),
  9509. default_vertex : [
  9510. "vec4 mvPosition;",
  9511. "#ifdef USE_SKINNING",
  9512. "mvPosition = modelViewMatrix * skinned;",
  9513. "#endif",
  9514. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  9515. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  9516. "#endif",
  9517. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  9518. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9519. "#endif",
  9520. "gl_Position = projectionMatrix * mvPosition;"
  9521. ].join("\n"),
  9522. morphnormal_vertex: [
  9523. "#ifdef USE_MORPHNORMALS",
  9524. "vec3 morphedNormal = vec3( 0.0 );",
  9525. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  9526. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  9527. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  9528. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  9529. "morphedNormal += normal;",
  9530. "#endif"
  9531. ].join("\n"),
  9532. skinnormal_vertex: [
  9533. "#ifdef USE_SKINNING",
  9534. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  9535. "skinMatrix += skinWeight.y * boneMatY;",
  9536. "#ifdef USE_MORPHNORMALS",
  9537. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  9538. "#else",
  9539. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  9540. "#endif",
  9541. "#endif"
  9542. ].join("\n"),
  9543. defaultnormal_vertex: [
  9544. "vec3 objectNormal;",
  9545. "#ifdef USE_SKINNING",
  9546. "objectNormal = skinnedNormal.xyz;",
  9547. "#endif",
  9548. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  9549. "objectNormal = morphedNormal;",
  9550. "#endif",
  9551. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  9552. "objectNormal = normal;",
  9553. "#endif",
  9554. "#ifdef FLIP_SIDED",
  9555. "objectNormal = -objectNormal;",
  9556. "#endif",
  9557. "vec3 transformedNormal = normalMatrix * objectNormal;"
  9558. ].join("\n"),
  9559. // SHADOW MAP
  9560. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  9561. // http://spidergl.org/example.php?id=6
  9562. // http://fabiensanglard.net/shadowmapping
  9563. shadowmap_pars_fragment: [
  9564. "#ifdef USE_SHADOWMAP",
  9565. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  9566. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  9567. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  9568. "uniform float shadowBias[ MAX_SHADOWS ];",
  9569. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9570. "float unpackDepth( const in vec4 rgba_depth ) {",
  9571. "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 );",
  9572. "float depth = dot( rgba_depth, bit_shift );",
  9573. "return depth;",
  9574. "}",
  9575. "#endif"
  9576. ].join("\n"),
  9577. shadowmap_fragment: [
  9578. "#ifdef USE_SHADOWMAP",
  9579. "#ifdef SHADOWMAP_DEBUG",
  9580. "vec3 frustumColors[3];",
  9581. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  9582. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  9583. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  9584. "#endif",
  9585. "#ifdef SHADOWMAP_CASCADE",
  9586. "int inFrustumCount = 0;",
  9587. "#endif",
  9588. "float fDepth;",
  9589. "vec3 shadowColor = vec3( 1.0 );",
  9590. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9591. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  9592. // "if ( something && something )" breaks ATI OpenGL shader compiler
  9593. // "if ( all( something, something ) )" using this instead
  9594. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  9595. "bool inFrustum = all( inFrustumVec );",
  9596. // don't shadow pixels outside of light frustum
  9597. // use just first frustum (for cascades)
  9598. // don't shadow pixels behind far plane of light frustum
  9599. "#ifdef SHADOWMAP_CASCADE",
  9600. "inFrustumCount += int( inFrustum );",
  9601. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  9602. "#else",
  9603. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  9604. "#endif",
  9605. "bool frustumTest = all( frustumTestVec );",
  9606. "if ( frustumTest ) {",
  9607. "shadowCoord.z += shadowBias[ i ];",
  9608. "#if defined( SHADOWMAP_TYPE_PCF )",
  9609. // Percentage-close filtering
  9610. // (9 pixel kernel)
  9611. // http://fabiensanglard.net/shadowmappingPCF/
  9612. "float shadow = 0.0;",
  9613. /*
  9614. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  9615. // must enroll loop manually
  9616. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  9617. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  9618. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  9619. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  9620. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  9621. "float fDepth = unpackDepth( rgbaDepth );",
  9622. "if ( fDepth < shadowCoord.z )",
  9623. "shadow += 1.0;",
  9624. "}",
  9625. "shadow /= 9.0;",
  9626. */
  9627. "const float shadowDelta = 1.0 / 9.0;",
  9628. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9629. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9630. "float dx0 = -1.25 * xPixelOffset;",
  9631. "float dy0 = -1.25 * yPixelOffset;",
  9632. "float dx1 = 1.25 * xPixelOffset;",
  9633. "float dy1 = 1.25 * yPixelOffset;",
  9634. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9635. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9636. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9637. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9638. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9639. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9640. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9641. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9642. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9643. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9644. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9645. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9646. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9647. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9648. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9649. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9650. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9651. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9652. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9653. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  9654. // Percentage-close filtering
  9655. // (9 pixel kernel)
  9656. // http://fabiensanglard.net/shadowmappingPCF/
  9657. "float shadow = 0.0;",
  9658. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9659. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9660. "float dx0 = -1.0 * xPixelOffset;",
  9661. "float dy0 = -1.0 * yPixelOffset;",
  9662. "float dx1 = 1.0 * xPixelOffset;",
  9663. "float dy1 = 1.0 * yPixelOffset;",
  9664. "mat3 shadowKernel;",
  9665. "mat3 depthKernel;",
  9666. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9667. "if ( depthKernel[0][0] < shadowCoord.z ) shadowKernel[0][0] = 0.25;",
  9668. "else shadowKernel[0][0] = 0.0;",
  9669. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9670. "if ( depthKernel[0][1] < shadowCoord.z ) shadowKernel[0][1] = 0.25;",
  9671. "else shadowKernel[0][1] = 0.0;",
  9672. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9673. "if ( depthKernel[0][2] < shadowCoord.z ) shadowKernel[0][2] = 0.25;",
  9674. "else shadowKernel[0][2] = 0.0;",
  9675. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9676. "if ( depthKernel[1][0] < shadowCoord.z ) shadowKernel[1][0] = 0.25;",
  9677. "else shadowKernel[1][0] = 0.0;",
  9678. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9679. "if ( depthKernel[1][1] < shadowCoord.z ) shadowKernel[1][1] = 0.25;",
  9680. "else shadowKernel[1][1] = 0.0;",
  9681. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9682. "if ( depthKernel[1][2] < shadowCoord.z ) shadowKernel[1][2] = 0.25;",
  9683. "else shadowKernel[1][2] = 0.0;",
  9684. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9685. "if ( depthKernel[2][0] < shadowCoord.z ) shadowKernel[2][0] = 0.25;",
  9686. "else shadowKernel[2][0] = 0.0;",
  9687. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9688. "if ( depthKernel[2][1] < shadowCoord.z ) shadowKernel[2][1] = 0.25;",
  9689. "else shadowKernel[2][1] = 0.0;",
  9690. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9691. "if ( depthKernel[2][2] < shadowCoord.z ) shadowKernel[2][2] = 0.25;",
  9692. "else shadowKernel[2][2] = 0.0;",
  9693. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  9694. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  9695. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  9696. "vec4 shadowValues;",
  9697. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  9698. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  9699. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  9700. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  9701. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  9702. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9703. "#else",
  9704. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  9705. "float fDepth = unpackDepth( rgbaDepth );",
  9706. "if ( fDepth < shadowCoord.z )",
  9707. // spot with multiple shadows is darker
  9708. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  9709. // spot with multiple shadows has the same color as single shadow spot
  9710. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  9711. "#endif",
  9712. "}",
  9713. "#ifdef SHADOWMAP_DEBUG",
  9714. "#ifdef SHADOWMAP_CASCADE",
  9715. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  9716. "#else",
  9717. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  9718. "#endif",
  9719. "#endif",
  9720. "}",
  9721. "#ifdef GAMMA_OUTPUT",
  9722. "shadowColor *= shadowColor;",
  9723. "#endif",
  9724. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  9725. "#endif"
  9726. ].join("\n"),
  9727. shadowmap_pars_vertex: [
  9728. "#ifdef USE_SHADOWMAP",
  9729. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9730. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  9731. "#endif"
  9732. ].join("\n"),
  9733. shadowmap_vertex: [
  9734. "#ifdef USE_SHADOWMAP",
  9735. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9736. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  9737. "}",
  9738. "#endif"
  9739. ].join("\n"),
  9740. // ALPHATEST
  9741. alphatest_fragment: [
  9742. "#ifdef ALPHATEST",
  9743. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  9744. "#endif"
  9745. ].join("\n"),
  9746. // LINEAR SPACE
  9747. linear_to_gamma_fragment: [
  9748. "#ifdef GAMMA_OUTPUT",
  9749. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  9750. "#endif"
  9751. ].join("\n")
  9752. };
  9753. THREE.UniformsUtils = {
  9754. merge: function ( uniforms ) {
  9755. var u, p, tmp, merged = {};
  9756. for ( u = 0; u < uniforms.length; u ++ ) {
  9757. tmp = this.clone( uniforms[ u ] );
  9758. for ( p in tmp ) {
  9759. merged[ p ] = tmp[ p ];
  9760. }
  9761. }
  9762. return merged;
  9763. },
  9764. clone: function ( uniforms_src ) {
  9765. var u, p, parameter, parameter_src, uniforms_dst = {};
  9766. for ( u in uniforms_src ) {
  9767. uniforms_dst[ u ] = {};
  9768. for ( p in uniforms_src[ u ] ) {
  9769. parameter_src = uniforms_src[ u ][ p ];
  9770. if ( parameter_src instanceof THREE.Color ||
  9771. parameter_src instanceof THREE.Vector2 ||
  9772. parameter_src instanceof THREE.Vector3 ||
  9773. parameter_src instanceof THREE.Vector4 ||
  9774. parameter_src instanceof THREE.Matrix4 ||
  9775. parameter_src instanceof THREE.Texture ) {
  9776. uniforms_dst[ u ][ p ] = parameter_src.clone();
  9777. } else if ( parameter_src instanceof Array ) {
  9778. uniforms_dst[ u ][ p ] = parameter_src.slice();
  9779. } else {
  9780. uniforms_dst[ u ][ p ] = parameter_src;
  9781. }
  9782. }
  9783. }
  9784. return uniforms_dst;
  9785. }
  9786. };
  9787. THREE.UniformsLib = {
  9788. common: {
  9789. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9790. "opacity" : { type: "f", value: 1.0 },
  9791. "map" : { type: "t", value: null },
  9792. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  9793. "lightMap" : { type: "t", value: null },
  9794. "specularMap" : { type: "t", value: null },
  9795. "envMap" : { type: "t", value: null },
  9796. "flipEnvMap" : { type: "f", value: -1 },
  9797. "useRefract" : { type: "i", value: 0 },
  9798. "reflectivity" : { type: "f", value: 1.0 },
  9799. "refractionRatio" : { type: "f", value: 0.98 },
  9800. "combine" : { type: "i", value: 0 },
  9801. "morphTargetInfluences" : { type: "f", value: 0 }
  9802. },
  9803. bump: {
  9804. "bumpMap" : { type: "t", value: null },
  9805. "bumpScale" : { type: "f", value: 1 }
  9806. },
  9807. normalmap: {
  9808. "normalMap" : { type: "t", value: null },
  9809. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  9810. },
  9811. fog : {
  9812. "fogDensity" : { type: "f", value: 0.00025 },
  9813. "fogNear" : { type: "f", value: 1 },
  9814. "fogFar" : { type: "f", value: 2000 },
  9815. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9816. },
  9817. lights: {
  9818. "ambientLightColor" : { type: "fv", value: [] },
  9819. "directionalLightDirection" : { type: "fv", value: [] },
  9820. "directionalLightColor" : { type: "fv", value: [] },
  9821. "hemisphereLightDirection" : { type: "fv", value: [] },
  9822. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  9823. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  9824. "pointLightColor" : { type: "fv", value: [] },
  9825. "pointLightPosition" : { type: "fv", value: [] },
  9826. "pointLightDistance" : { type: "fv1", value: [] },
  9827. "spotLightColor" : { type: "fv", value: [] },
  9828. "spotLightPosition" : { type: "fv", value: [] },
  9829. "spotLightDirection" : { type: "fv", value: [] },
  9830. "spotLightDistance" : { type: "fv1", value: [] },
  9831. "spotLightAngleCos" : { type: "fv1", value: [] },
  9832. "spotLightExponent" : { type: "fv1", value: [] }
  9833. },
  9834. particle: {
  9835. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9836. "opacity" : { type: "f", value: 1.0 },
  9837. "size" : { type: "f", value: 1.0 },
  9838. "scale" : { type: "f", value: 1.0 },
  9839. "map" : { type: "t", value: null },
  9840. "fogDensity" : { type: "f", value: 0.00025 },
  9841. "fogNear" : { type: "f", value: 1 },
  9842. "fogFar" : { type: "f", value: 2000 },
  9843. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9844. },
  9845. shadowmap: {
  9846. "shadowMap": { type: "tv", value: [] },
  9847. "shadowMapSize": { type: "v2v", value: [] },
  9848. "shadowBias" : { type: "fv1", value: [] },
  9849. "shadowDarkness": { type: "fv1", value: [] },
  9850. "shadowMatrix" : { type: "m4v", value: [] }
  9851. }
  9852. };
  9853. THREE.ShaderLib = {
  9854. 'basic': {
  9855. uniforms: THREE.UniformsUtils.merge( [
  9856. THREE.UniformsLib[ "common" ],
  9857. THREE.UniformsLib[ "fog" ],
  9858. THREE.UniformsLib[ "shadowmap" ]
  9859. ] ),
  9860. vertexShader: [
  9861. THREE.ShaderChunk[ "map_pars_vertex" ],
  9862. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9863. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9864. THREE.ShaderChunk[ "color_pars_vertex" ],
  9865. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9866. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9867. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9868. "void main() {",
  9869. THREE.ShaderChunk[ "map_vertex" ],
  9870. THREE.ShaderChunk[ "lightmap_vertex" ],
  9871. THREE.ShaderChunk[ "color_vertex" ],
  9872. THREE.ShaderChunk[ "skinbase_vertex" ],
  9873. "#ifdef USE_ENVMAP",
  9874. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9875. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9876. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9877. "#endif",
  9878. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9879. THREE.ShaderChunk[ "skinning_vertex" ],
  9880. THREE.ShaderChunk[ "default_vertex" ],
  9881. THREE.ShaderChunk[ "worldpos_vertex" ],
  9882. THREE.ShaderChunk[ "envmap_vertex" ],
  9883. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9884. "}"
  9885. ].join("\n"),
  9886. fragmentShader: [
  9887. "uniform vec3 diffuse;",
  9888. "uniform float opacity;",
  9889. THREE.ShaderChunk[ "color_pars_fragment" ],
  9890. THREE.ShaderChunk[ "map_pars_fragment" ],
  9891. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9892. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9893. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9894. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9895. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9896. "void main() {",
  9897. "gl_FragColor = vec4( diffuse, opacity );",
  9898. THREE.ShaderChunk[ "map_fragment" ],
  9899. THREE.ShaderChunk[ "alphatest_fragment" ],
  9900. THREE.ShaderChunk[ "specularmap_fragment" ],
  9901. THREE.ShaderChunk[ "lightmap_fragment" ],
  9902. THREE.ShaderChunk[ "color_fragment" ],
  9903. THREE.ShaderChunk[ "envmap_fragment" ],
  9904. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9905. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9906. THREE.ShaderChunk[ "fog_fragment" ],
  9907. "}"
  9908. ].join("\n")
  9909. },
  9910. 'lambert': {
  9911. uniforms: THREE.UniformsUtils.merge( [
  9912. THREE.UniformsLib[ "common" ],
  9913. THREE.UniformsLib[ "fog" ],
  9914. THREE.UniformsLib[ "lights" ],
  9915. THREE.UniformsLib[ "shadowmap" ],
  9916. {
  9917. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9918. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9919. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9920. }
  9921. ] ),
  9922. vertexShader: [
  9923. "#define LAMBERT",
  9924. "varying vec3 vLightFront;",
  9925. "#ifdef DOUBLE_SIDED",
  9926. "varying vec3 vLightBack;",
  9927. "#endif",
  9928. THREE.ShaderChunk[ "map_pars_vertex" ],
  9929. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9930. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9931. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  9932. THREE.ShaderChunk[ "color_pars_vertex" ],
  9933. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9934. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9935. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9936. "void main() {",
  9937. THREE.ShaderChunk[ "map_vertex" ],
  9938. THREE.ShaderChunk[ "lightmap_vertex" ],
  9939. THREE.ShaderChunk[ "color_vertex" ],
  9940. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9941. THREE.ShaderChunk[ "skinbase_vertex" ],
  9942. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9943. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9944. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9945. THREE.ShaderChunk[ "skinning_vertex" ],
  9946. THREE.ShaderChunk[ "default_vertex" ],
  9947. THREE.ShaderChunk[ "worldpos_vertex" ],
  9948. THREE.ShaderChunk[ "envmap_vertex" ],
  9949. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  9950. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9951. "}"
  9952. ].join("\n"),
  9953. fragmentShader: [
  9954. "uniform float opacity;",
  9955. "varying vec3 vLightFront;",
  9956. "#ifdef DOUBLE_SIDED",
  9957. "varying vec3 vLightBack;",
  9958. "#endif",
  9959. THREE.ShaderChunk[ "color_pars_fragment" ],
  9960. THREE.ShaderChunk[ "map_pars_fragment" ],
  9961. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9962. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9963. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9964. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9965. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9966. "void main() {",
  9967. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9968. THREE.ShaderChunk[ "map_fragment" ],
  9969. THREE.ShaderChunk[ "alphatest_fragment" ],
  9970. THREE.ShaderChunk[ "specularmap_fragment" ],
  9971. "#ifdef DOUBLE_SIDED",
  9972. //"float isFront = float( gl_FrontFacing );",
  9973. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  9974. "if ( gl_FrontFacing )",
  9975. "gl_FragColor.xyz *= vLightFront;",
  9976. "else",
  9977. "gl_FragColor.xyz *= vLightBack;",
  9978. "#else",
  9979. "gl_FragColor.xyz *= vLightFront;",
  9980. "#endif",
  9981. THREE.ShaderChunk[ "lightmap_fragment" ],
  9982. THREE.ShaderChunk[ "color_fragment" ],
  9983. THREE.ShaderChunk[ "envmap_fragment" ],
  9984. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9985. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9986. THREE.ShaderChunk[ "fog_fragment" ],
  9987. "}"
  9988. ].join("\n")
  9989. },
  9990. 'phong': {
  9991. uniforms: THREE.UniformsUtils.merge( [
  9992. THREE.UniformsLib[ "common" ],
  9993. THREE.UniformsLib[ "bump" ],
  9994. THREE.UniformsLib[ "normalmap" ],
  9995. THREE.UniformsLib[ "fog" ],
  9996. THREE.UniformsLib[ "lights" ],
  9997. THREE.UniformsLib[ "shadowmap" ],
  9998. {
  9999. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10000. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10001. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10002. "shininess": { type: "f", value: 30 },
  10003. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10004. }
  10005. ] ),
  10006. vertexShader: [
  10007. "#define PHONG",
  10008. "varying vec3 vViewPosition;",
  10009. "varying vec3 vNormal;",
  10010. THREE.ShaderChunk[ "map_pars_vertex" ],
  10011. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10012. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10013. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10014. THREE.ShaderChunk[ "color_pars_vertex" ],
  10015. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10016. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10017. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10018. "void main() {",
  10019. THREE.ShaderChunk[ "map_vertex" ],
  10020. THREE.ShaderChunk[ "lightmap_vertex" ],
  10021. THREE.ShaderChunk[ "color_vertex" ],
  10022. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10023. THREE.ShaderChunk[ "skinbase_vertex" ],
  10024. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10025. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10026. "vNormal = normalize( transformedNormal );",
  10027. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10028. THREE.ShaderChunk[ "skinning_vertex" ],
  10029. THREE.ShaderChunk[ "default_vertex" ],
  10030. "vViewPosition = -mvPosition.xyz;",
  10031. THREE.ShaderChunk[ "worldpos_vertex" ],
  10032. THREE.ShaderChunk[ "envmap_vertex" ],
  10033. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10034. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10035. "}"
  10036. ].join("\n"),
  10037. fragmentShader: [
  10038. "uniform vec3 diffuse;",
  10039. "uniform float opacity;",
  10040. "uniform vec3 ambient;",
  10041. "uniform vec3 emissive;",
  10042. "uniform vec3 specular;",
  10043. "uniform float shininess;",
  10044. THREE.ShaderChunk[ "color_pars_fragment" ],
  10045. THREE.ShaderChunk[ "map_pars_fragment" ],
  10046. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10047. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10048. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10049. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10050. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10051. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10052. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10053. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10054. "void main() {",
  10055. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10056. THREE.ShaderChunk[ "map_fragment" ],
  10057. THREE.ShaderChunk[ "alphatest_fragment" ],
  10058. THREE.ShaderChunk[ "specularmap_fragment" ],
  10059. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10060. THREE.ShaderChunk[ "lightmap_fragment" ],
  10061. THREE.ShaderChunk[ "color_fragment" ],
  10062. THREE.ShaderChunk[ "envmap_fragment" ],
  10063. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10064. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10065. THREE.ShaderChunk[ "fog_fragment" ],
  10066. "}"
  10067. ].join("\n")
  10068. },
  10069. 'particle_basic': {
  10070. uniforms: THREE.UniformsUtils.merge( [
  10071. THREE.UniformsLib[ "particle" ],
  10072. THREE.UniformsLib[ "shadowmap" ]
  10073. ] ),
  10074. vertexShader: [
  10075. "uniform float size;",
  10076. "uniform float scale;",
  10077. THREE.ShaderChunk[ "color_pars_vertex" ],
  10078. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10079. "void main() {",
  10080. THREE.ShaderChunk[ "color_vertex" ],
  10081. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10082. "#ifdef USE_SIZEATTENUATION",
  10083. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10084. "#else",
  10085. "gl_PointSize = size;",
  10086. "#endif",
  10087. "gl_Position = projectionMatrix * mvPosition;",
  10088. THREE.ShaderChunk[ "worldpos_vertex" ],
  10089. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10090. "}"
  10091. ].join("\n"),
  10092. fragmentShader: [
  10093. "uniform vec3 psColor;",
  10094. "uniform float opacity;",
  10095. THREE.ShaderChunk[ "color_pars_fragment" ],
  10096. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10097. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10098. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10099. "void main() {",
  10100. "gl_FragColor = vec4( psColor, opacity );",
  10101. THREE.ShaderChunk[ "map_particle_fragment" ],
  10102. THREE.ShaderChunk[ "alphatest_fragment" ],
  10103. THREE.ShaderChunk[ "color_fragment" ],
  10104. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10105. THREE.ShaderChunk[ "fog_fragment" ],
  10106. "}"
  10107. ].join("\n")
  10108. },
  10109. 'dashed': {
  10110. uniforms: THREE.UniformsUtils.merge( [
  10111. THREE.UniformsLib[ "common" ],
  10112. THREE.UniformsLib[ "fog" ],
  10113. {
  10114. "scale": { type: "f", value: 1 },
  10115. "dashSize": { type: "f", value: 1 },
  10116. "totalSize": { type: "f", value: 2 }
  10117. }
  10118. ] ),
  10119. vertexShader: [
  10120. "uniform float scale;",
  10121. "attribute float lineDistance;",
  10122. "varying float vLineDistance;",
  10123. THREE.ShaderChunk[ "color_pars_vertex" ],
  10124. "void main() {",
  10125. THREE.ShaderChunk[ "color_vertex" ],
  10126. "vLineDistance = scale * lineDistance;",
  10127. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10128. "gl_Position = projectionMatrix * mvPosition;",
  10129. "}"
  10130. ].join("\n"),
  10131. fragmentShader: [
  10132. "uniform vec3 diffuse;",
  10133. "uniform float opacity;",
  10134. "uniform float dashSize;",
  10135. "uniform float totalSize;",
  10136. "varying float vLineDistance;",
  10137. THREE.ShaderChunk[ "color_pars_fragment" ],
  10138. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10139. "void main() {",
  10140. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10141. "discard;",
  10142. "}",
  10143. "gl_FragColor = vec4( diffuse, opacity );",
  10144. THREE.ShaderChunk[ "color_fragment" ],
  10145. THREE.ShaderChunk[ "fog_fragment" ],
  10146. "}"
  10147. ].join("\n")
  10148. },
  10149. 'depth': {
  10150. uniforms: {
  10151. "mNear": { type: "f", value: 1.0 },
  10152. "mFar" : { type: "f", value: 2000.0 },
  10153. "opacity" : { type: "f", value: 1.0 }
  10154. },
  10155. vertexShader: [
  10156. "void main() {",
  10157. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10158. "}"
  10159. ].join("\n"),
  10160. fragmentShader: [
  10161. "uniform float mNear;",
  10162. "uniform float mFar;",
  10163. "uniform float opacity;",
  10164. "void main() {",
  10165. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10166. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  10167. "gl_FragColor = vec4( vec3( color ), opacity );",
  10168. "}"
  10169. ].join("\n")
  10170. },
  10171. 'normal': {
  10172. uniforms: {
  10173. "opacity" : { type: "f", value: 1.0 }
  10174. },
  10175. vertexShader: [
  10176. "varying vec3 vNormal;",
  10177. "void main() {",
  10178. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10179. "vNormal = normalize( normalMatrix * normal );",
  10180. "gl_Position = projectionMatrix * mvPosition;",
  10181. "}"
  10182. ].join("\n"),
  10183. fragmentShader: [
  10184. "uniform float opacity;",
  10185. "varying vec3 vNormal;",
  10186. "void main() {",
  10187. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  10188. "}"
  10189. ].join("\n")
  10190. },
  10191. /* -------------------------------------------------------------------------
  10192. // Normal map shader
  10193. // - Blinn-Phong
  10194. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  10195. // - point and directional lights (use with "lights: true" material option)
  10196. ------------------------------------------------------------------------- */
  10197. 'normalmap' : {
  10198. uniforms: THREE.UniformsUtils.merge( [
  10199. THREE.UniformsLib[ "fog" ],
  10200. THREE.UniformsLib[ "lights" ],
  10201. THREE.UniformsLib[ "shadowmap" ],
  10202. {
  10203. "enableAO" : { type: "i", value: 0 },
  10204. "enableDiffuse" : { type: "i", value: 0 },
  10205. "enableSpecular" : { type: "i", value: 0 },
  10206. "enableReflection": { type: "i", value: 0 },
  10207. "enableDisplacement": { type: "i", value: 0 },
  10208. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  10209. "tDiffuse" : { type: "t", value: null },
  10210. "tCube" : { type: "t", value: null },
  10211. "tNormal" : { type: "t", value: null },
  10212. "tSpecular" : { type: "t", value: null },
  10213. "tAO" : { type: "t", value: null },
  10214. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  10215. "uDisplacementBias": { type: "f", value: 0.0 },
  10216. "uDisplacementScale": { type: "f", value: 1.0 },
  10217. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10218. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  10219. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10220. "uShininess": { type: "f", value: 30 },
  10221. "uOpacity": { type: "f", value: 1 },
  10222. "useRefract": { type: "i", value: 0 },
  10223. "uRefractionRatio": { type: "f", value: 0.98 },
  10224. "uReflectivity": { type: "f", value: 0.5 },
  10225. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  10226. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  10227. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10228. }
  10229. ] ),
  10230. fragmentShader: [
  10231. "uniform vec3 uAmbientColor;",
  10232. "uniform vec3 uDiffuseColor;",
  10233. "uniform vec3 uSpecularColor;",
  10234. "uniform float uShininess;",
  10235. "uniform float uOpacity;",
  10236. "uniform bool enableDiffuse;",
  10237. "uniform bool enableSpecular;",
  10238. "uniform bool enableAO;",
  10239. "uniform bool enableReflection;",
  10240. "uniform sampler2D tDiffuse;",
  10241. "uniform sampler2D tNormal;",
  10242. "uniform sampler2D tSpecular;",
  10243. "uniform sampler2D tAO;",
  10244. "uniform samplerCube tCube;",
  10245. "uniform vec2 uNormalScale;",
  10246. "uniform bool useRefract;",
  10247. "uniform float uRefractionRatio;",
  10248. "uniform float uReflectivity;",
  10249. "varying vec3 vTangent;",
  10250. "varying vec3 vBinormal;",
  10251. "varying vec3 vNormal;",
  10252. "varying vec2 vUv;",
  10253. "uniform vec3 ambientLightColor;",
  10254. "#if MAX_DIR_LIGHTS > 0",
  10255. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10256. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10257. "#endif",
  10258. "#if MAX_HEMI_LIGHTS > 0",
  10259. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10260. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10261. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10262. "#endif",
  10263. "#if MAX_POINT_LIGHTS > 0",
  10264. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10265. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10266. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10267. "#endif",
  10268. "#if MAX_SPOT_LIGHTS > 0",
  10269. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10270. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10271. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10272. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10273. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10274. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10275. "#endif",
  10276. "#ifdef WRAP_AROUND",
  10277. "uniform vec3 wrapRGB;",
  10278. "#endif",
  10279. "varying vec3 vWorldPosition;",
  10280. "varying vec3 vViewPosition;",
  10281. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10282. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10283. "void main() {",
  10284. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  10285. "vec3 specularTex = vec3( 1.0 );",
  10286. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  10287. "normalTex.xy *= uNormalScale;",
  10288. "normalTex = normalize( normalTex );",
  10289. "if( enableDiffuse ) {",
  10290. "#ifdef GAMMA_INPUT",
  10291. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  10292. "texelColor.xyz *= texelColor.xyz;",
  10293. "gl_FragColor = gl_FragColor * texelColor;",
  10294. "#else",
  10295. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  10296. "#endif",
  10297. "}",
  10298. "if( enableAO ) {",
  10299. "#ifdef GAMMA_INPUT",
  10300. "vec4 aoColor = texture2D( tAO, vUv );",
  10301. "aoColor.xyz *= aoColor.xyz;",
  10302. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  10303. "#else",
  10304. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  10305. "#endif",
  10306. "}",
  10307. "if( enableSpecular )",
  10308. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  10309. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  10310. "vec3 finalNormal = tsb * normalTex;",
  10311. "#ifdef FLIP_SIDED",
  10312. "finalNormal = -finalNormal;",
  10313. "#endif",
  10314. "vec3 normal = normalize( finalNormal );",
  10315. "vec3 viewPosition = normalize( vViewPosition );",
  10316. // point lights
  10317. "#if MAX_POINT_LIGHTS > 0",
  10318. "vec3 pointDiffuse = vec3( 0.0 );",
  10319. "vec3 pointSpecular = vec3( 0.0 );",
  10320. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10321. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10322. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  10323. "float pointDistance = 1.0;",
  10324. "if ( pointLightDistance[ i ] > 0.0 )",
  10325. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  10326. "pointVector = normalize( pointVector );",
  10327. // diffuse
  10328. "#ifdef WRAP_AROUND",
  10329. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  10330. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  10331. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10332. "#else",
  10333. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  10334. "#endif",
  10335. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  10336. // specular
  10337. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  10338. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10339. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  10340. "#ifdef PHYSICALLY_BASED_SHADING",
  10341. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10342. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10343. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  10344. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  10345. "#else",
  10346. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  10347. "#endif",
  10348. "}",
  10349. "#endif",
  10350. // spot lights
  10351. "#if MAX_SPOT_LIGHTS > 0",
  10352. "vec3 spotDiffuse = vec3( 0.0 );",
  10353. "vec3 spotSpecular = vec3( 0.0 );",
  10354. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10355. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10356. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  10357. "float spotDistance = 1.0;",
  10358. "if ( spotLightDistance[ i ] > 0.0 )",
  10359. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  10360. "spotVector = normalize( spotVector );",
  10361. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10362. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10363. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10364. // diffuse
  10365. "#ifdef WRAP_AROUND",
  10366. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  10367. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  10368. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10369. "#else",
  10370. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  10371. "#endif",
  10372. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  10373. // specular
  10374. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  10375. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10376. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  10377. "#ifdef PHYSICALLY_BASED_SHADING",
  10378. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10379. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10380. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  10381. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  10382. "#else",
  10383. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  10384. "#endif",
  10385. "}",
  10386. "}",
  10387. "#endif",
  10388. // directional lights
  10389. "#if MAX_DIR_LIGHTS > 0",
  10390. "vec3 dirDiffuse = vec3( 0.0 );",
  10391. "vec3 dirSpecular = vec3( 0.0 );",
  10392. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  10393. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10394. "vec3 dirVector = normalize( lDirection.xyz );",
  10395. // diffuse
  10396. "#ifdef WRAP_AROUND",
  10397. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  10398. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  10399. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  10400. "#else",
  10401. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  10402. "#endif",
  10403. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  10404. // specular
  10405. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10406. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10407. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  10408. "#ifdef PHYSICALLY_BASED_SHADING",
  10409. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10410. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10411. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10412. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10413. "#else",
  10414. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  10415. "#endif",
  10416. "}",
  10417. "#endif",
  10418. // hemisphere lights
  10419. "#if MAX_HEMI_LIGHTS > 0",
  10420. "vec3 hemiDiffuse = vec3( 0.0 );",
  10421. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10422. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10423. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10424. "vec3 lVector = normalize( lDirection.xyz );",
  10425. // diffuse
  10426. "float dotProduct = dot( normal, lVector );",
  10427. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10428. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10429. "hemiDiffuse += uDiffuseColor * hemiColor;",
  10430. // specular (sky light)
  10431. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10432. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10433. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  10434. // specular (ground light)
  10435. "vec3 lVectorGround = -lVector;",
  10436. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10437. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10438. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  10439. "#ifdef PHYSICALLY_BASED_SHADING",
  10440. "float dotProductGround = dot( normal, lVectorGround );",
  10441. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10442. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10443. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10444. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10445. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10446. "#else",
  10447. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  10448. "#endif",
  10449. "}",
  10450. "#endif",
  10451. // all lights contribution summation
  10452. "vec3 totalDiffuse = vec3( 0.0 );",
  10453. "vec3 totalSpecular = vec3( 0.0 );",
  10454. "#if MAX_DIR_LIGHTS > 0",
  10455. "totalDiffuse += dirDiffuse;",
  10456. "totalSpecular += dirSpecular;",
  10457. "#endif",
  10458. "#if MAX_HEMI_LIGHTS > 0",
  10459. "totalDiffuse += hemiDiffuse;",
  10460. "totalSpecular += hemiSpecular;",
  10461. "#endif",
  10462. "#if MAX_POINT_LIGHTS > 0",
  10463. "totalDiffuse += pointDiffuse;",
  10464. "totalSpecular += pointSpecular;",
  10465. "#endif",
  10466. "#if MAX_SPOT_LIGHTS > 0",
  10467. "totalDiffuse += spotDiffuse;",
  10468. "totalSpecular += spotSpecular;",
  10469. "#endif",
  10470. "#ifdef METAL",
  10471. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  10472. "#else",
  10473. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  10474. "#endif",
  10475. "if ( enableReflection ) {",
  10476. "vec3 vReflect;",
  10477. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  10478. "if ( useRefract ) {",
  10479. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  10480. "} else {",
  10481. "vReflect = reflect( cameraToVertex, normal );",
  10482. "}",
  10483. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  10484. "#ifdef GAMMA_INPUT",
  10485. "cubeColor.xyz *= cubeColor.xyz;",
  10486. "#endif",
  10487. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  10488. "}",
  10489. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10490. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10491. THREE.ShaderChunk[ "fog_fragment" ],
  10492. "}"
  10493. ].join("\n"),
  10494. vertexShader: [
  10495. "attribute vec4 tangent;",
  10496. "uniform vec2 uOffset;",
  10497. "uniform vec2 uRepeat;",
  10498. "uniform bool enableDisplacement;",
  10499. "#ifdef VERTEX_TEXTURES",
  10500. "uniform sampler2D tDisplacement;",
  10501. "uniform float uDisplacementScale;",
  10502. "uniform float uDisplacementBias;",
  10503. "#endif",
  10504. "varying vec3 vTangent;",
  10505. "varying vec3 vBinormal;",
  10506. "varying vec3 vNormal;",
  10507. "varying vec2 vUv;",
  10508. "varying vec3 vWorldPosition;",
  10509. "varying vec3 vViewPosition;",
  10510. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10511. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10512. "void main() {",
  10513. THREE.ShaderChunk[ "skinbase_vertex" ],
  10514. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10515. // normal, tangent and binormal vectors
  10516. "#ifdef USE_SKINNING",
  10517. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  10518. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  10519. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  10520. "#else",
  10521. "vNormal = normalize( normalMatrix * normal );",
  10522. "vTangent = normalize( normalMatrix * tangent.xyz );",
  10523. "#endif",
  10524. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  10525. "vUv = uv * uRepeat + uOffset;",
  10526. // displacement mapping
  10527. "vec3 displacedPosition;",
  10528. "#ifdef VERTEX_TEXTURES",
  10529. "if ( enableDisplacement ) {",
  10530. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  10531. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  10532. "displacedPosition = position + normalize( normal ) * df;",
  10533. "} else {",
  10534. "#ifdef USE_SKINNING",
  10535. "vec4 skinVertex = vec4( position, 1.0 );",
  10536. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10537. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10538. "displacedPosition = skinned.xyz;",
  10539. "#else",
  10540. "displacedPosition = position;",
  10541. "#endif",
  10542. "}",
  10543. "#else",
  10544. "#ifdef USE_SKINNING",
  10545. "vec4 skinVertex = vec4( position, 1.0 );",
  10546. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10547. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10548. "displacedPosition = skinned.xyz;",
  10549. "#else",
  10550. "displacedPosition = position;",
  10551. "#endif",
  10552. "#endif",
  10553. //
  10554. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  10555. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  10556. "gl_Position = projectionMatrix * mvPosition;",
  10557. //
  10558. "vWorldPosition = worldPosition.xyz;",
  10559. "vViewPosition = -mvPosition.xyz;",
  10560. // shadows
  10561. "#ifdef USE_SHADOWMAP",
  10562. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10563. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10564. "}",
  10565. "#endif",
  10566. "}"
  10567. ].join("\n")
  10568. },
  10569. /* -------------------------------------------------------------------------
  10570. // Cube map shader
  10571. ------------------------------------------------------------------------- */
  10572. 'cube': {
  10573. uniforms: { "tCube": { type: "t", value: null },
  10574. "tFlip": { type: "f", value: -1 } },
  10575. vertexShader: [
  10576. "varying vec3 vWorldPosition;",
  10577. "void main() {",
  10578. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  10579. "vWorldPosition = worldPosition.xyz;",
  10580. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10581. "}"
  10582. ].join("\n"),
  10583. fragmentShader: [
  10584. "uniform samplerCube tCube;",
  10585. "uniform float tFlip;",
  10586. "varying vec3 vWorldPosition;",
  10587. "void main() {",
  10588. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  10589. "}"
  10590. ].join("\n")
  10591. },
  10592. // Depth encoding into RGBA texture
  10593. // based on SpiderGL shadow map example
  10594. // http://spidergl.org/example.php?id=6
  10595. // originally from
  10596. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  10597. // see also here:
  10598. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  10599. 'depthRGBA': {
  10600. uniforms: {},
  10601. vertexShader: [
  10602. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10603. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10604. "void main() {",
  10605. THREE.ShaderChunk[ "skinbase_vertex" ],
  10606. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10607. THREE.ShaderChunk[ "skinning_vertex" ],
  10608. THREE.ShaderChunk[ "default_vertex" ],
  10609. "}"
  10610. ].join("\n"),
  10611. fragmentShader: [
  10612. "vec4 pack_depth( const in float depth ) {",
  10613. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  10614. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  10615. "vec4 res = fract( depth * bit_shift );",
  10616. "res -= res.xxyz * bit_mask;",
  10617. "return res;",
  10618. "}",
  10619. "void main() {",
  10620. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  10621. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  10622. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  10623. //"gl_FragData[ 0 ] = pack_depth( z );",
  10624. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  10625. "}"
  10626. ].join("\n")
  10627. }
  10628. };
  10629. /**
  10630. * @author supereggbert / http://www.paulbrunt.co.uk/
  10631. * @author mrdoob / http://mrdoob.com/
  10632. * @author alteredq / http://alteredqualia.com/
  10633. * @author szimek / https://github.com/szimek/
  10634. * @author gero3 / https://github.com/gero3/
  10635. */
  10636. THREE.WebGLRenderer = function ( parameters ) {
  10637. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10638. parameters = parameters || {};
  10639. var info = {
  10640. memory: {
  10641. programs: 0,
  10642. geometries: 0,
  10643. textures: 0
  10644. },
  10645. render: {
  10646. calls: 0,
  10647. vertices: 0,
  10648. faces: 0,
  10649. points: 0
  10650. }
  10651. };
  10652. var renderer = new THREE.WebGLRenderer.LowLevelRenderer(parameters);
  10653. var meshRenderer = new THREE.WebGLRenderer.MeshRenderer(renderer, info);
  10654. var particleRenderer = new THREE.WebGLRenderer.ParticleRenderer(renderer, info);
  10655. var lineRenderer = new THREE.WebGLRenderer.LineRenderer(renderer, info);
  10656. var ribbonRenderer = new THREE.WebGLRenderer.RibbonRenderer(renderer, info);
  10657. var shaderBuilder = new THREE.WebGLRenderer.ShaderBuilder(renderer, info);
  10658. // clearing
  10659. this.autoClear = true;
  10660. this.autoClearColor = true;
  10661. this.autoClearDepth = true;
  10662. this.autoClearStencil = true;
  10663. // scene graph
  10664. this.sortObjects = true;
  10665. this.autoUpdateObjects = true;
  10666. this.autoUpdateScene = true;
  10667. // physically based shading
  10668. this.gammaInput = false;
  10669. this.gammaOutput = false;
  10670. this.physicallyBasedShading = false;
  10671. // shadow map
  10672. this.shadowMapEnabled = false;
  10673. this.shadowMapAutoUpdate = true;
  10674. this.shadowMapType = THREE.PCFShadowMap;
  10675. this.shadowMapCullFace = THREE.CullFaceFront;
  10676. this.shadowMapDebug = false;
  10677. this.shadowMapCascade = false;
  10678. // morphs
  10679. this.maxMorphTargets = 8;
  10680. this.maxMorphNormals = 4;
  10681. // flags
  10682. this.autoScaleCubemaps = true;
  10683. // custom render plugins
  10684. this.renderPluginsPre = [];
  10685. this.renderPluginsPost = [];
  10686. // info
  10687. this.info = info;
  10688. // internal properties
  10689. var _this = this,
  10690. // internal state cache
  10691. _currentProgram = null,
  10692. _currentFramebuffer = null,
  10693. _currentMaterialId = -1,
  10694. _currentGeometryGroupHash = null,
  10695. _currentCamera = null,
  10696. _geometryGroupCounter = 0,
  10697. _usedTextureUnits = 0,
  10698. // GL state
  10699. _viewportX = 0,
  10700. _viewportY = 0,
  10701. _viewportWidth = 0,
  10702. _viewportHeight = 0,
  10703. _currentWidth = 0,
  10704. _currentHeight = 0,
  10705. _enabledAttributes = {},
  10706. // frustum
  10707. _frustum = new THREE.Frustum(),
  10708. // camera matrices cache
  10709. _projScreenMatrix = new THREE.Matrix4(),
  10710. _projScreenMatrixPS = new THREE.Matrix4(),
  10711. _vector3 = new THREE.Vector3(),
  10712. // light arrays cache
  10713. _direction = new THREE.Vector3(),
  10714. _lightsNeedUpdate = true,
  10715. _lights = {
  10716. ambient: [ 0, 0, 0 ],
  10717. directional: { length: 0, colors: [], positions: [] },
  10718. point: { length: 0, colors: [], positions: [], distances: [] },
  10719. spot: { length: 0, colors: [], positions: [], distances: [], directions: [], anglesCos: [], exponents: [] },
  10720. hemi: { length: 0, skyColors: [], groundColors: [], positions: [] }
  10721. };
  10722. // initialize
  10723. this.context = renderer.getContext();
  10724. this.domElement = renderer.getDomElement();
  10725. this.getPrecision = renderer.getPrecision;
  10726. // low level API
  10727. this.getPrecision = renderer.getPrecision;
  10728. this.getContext = renderer.getContext;
  10729. this.supportsVertexTextures = renderer.supportsVertexTextures;
  10730. this.supportsFloatTextures = renderer.supportsFloatTextures;
  10731. this.supportsStandardDerivatives = renderer.supportsStandardDerivatives;
  10732. this.supportsCompressedTextureS3TC = renderer.supportsCompressedTextureS3TC;
  10733. this.getMaxAnisotropy = renderer.getMaxAnisotropy;
  10734. this.setSize = renderer.setSize;
  10735. this.setViewport = renderer.setViewport;
  10736. this.setScissor = renderer.setScissor;
  10737. this.enableScissorTest = renderer.enableScissorTest;
  10738. this.setDepthWrite = renderer.setDepthWrite;
  10739. this.setDepthTest = renderer.setDepthTest;
  10740. this.setRenderTarget = renderer.setRenderTarget;
  10741. this.setBlending = renderer.setBlending;
  10742. this.setTexture = renderer.setTexture;
  10743. this.setMaterialFaces = renderer.setMaterialFaces;
  10744. this.setFaceCulling = renderer.setFaceCulling;
  10745. // Clearing
  10746. this.setClearColorHex = renderer.setClearColorHex;
  10747. this.setClearColor = renderer.setClearColor;
  10748. this.getClearColor = renderer.getClearColor;
  10749. this.getClearAlpha = renderer.getClearAlpha;
  10750. this.clear = renderer.clear;
  10751. this.clearTarget = renderer.clearTarget;
  10752. // Plugins
  10753. this.addPostPlugin = function ( plugin ) {
  10754. plugin.init( this );
  10755. this.renderPluginsPost.push( plugin );
  10756. };
  10757. this.addPrePlugin = function ( plugin ) {
  10758. plugin.init( this );
  10759. this.renderPluginsPre.push( plugin );
  10760. };
  10761. // Rendering
  10762. this.updateShadowMap = function ( scene, camera ) {
  10763. _currentProgram = null;
  10764. _currentGeometryGroupHash = -1;
  10765. _currentMaterialId = -1;
  10766. _lightsNeedUpdate = true;
  10767. renderer.resetState();
  10768. this.shadowMapPlugin.update( scene, camera );
  10769. };
  10770. // Events
  10771. var onGeometryDispose = function ( event ) {
  10772. var geometry = event.target;
  10773. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10774. deallocateGeometry( geometry );
  10775. _this.info.memory.geometries --;
  10776. };
  10777. var onTextureDispose = function ( event ) {
  10778. var texture = event.target;
  10779. texture.removeEventListener( 'dispose', onTextureDispose );
  10780. deallocateTexture( texture );
  10781. _this.info.memory.textures --;
  10782. };
  10783. var onRenderTargetDispose = function ( event ) {
  10784. var renderTarget = event.target;
  10785. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10786. deallocateRenderTarget( renderTarget );
  10787. _this.info.memory.textures --;
  10788. };
  10789. var onMaterialDispose = function ( event ) {
  10790. var material = event.target;
  10791. material.removeEventListener( 'dispose', onMaterialDispose );
  10792. deallocateMaterial( material );
  10793. };
  10794. // Buffer deallocation
  10795. var deallocateGeometry = function ( geometry ) {
  10796. var m,ml;
  10797. geometry.__webglInit = undefined;
  10798. if ( geometry.__webglVertexBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglVertexBuffer );
  10799. if ( geometry.__webglNormalBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglNormalBuffer );
  10800. if ( geometry.__webglTangentBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglTangentBuffer );
  10801. if ( geometry.__webglColorBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglColorBuffer );
  10802. if ( geometry.__webglUVBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglUVBuffer );
  10803. if ( geometry.__webglUV2Buffer !== undefined ) renderer.deleteBuffer( geometry.__webglUV2Buffer );
  10804. if ( geometry.__webglSkinIndicesBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  10805. if ( geometry.__webglSkinWeightsBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  10806. if ( geometry.__webglFaceBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglFaceBuffer );
  10807. if ( geometry.__webglLineBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglLineBuffer );
  10808. if ( geometry.__webglLineDistanceBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglLineDistanceBuffer );
  10809. // geometry groups
  10810. if ( geometry.geometryGroups !== undefined ) {
  10811. for ( var g in geometry.geometryGroups ) {
  10812. var geometryGroup = geometry.geometryGroups[ g ];
  10813. if ( geometryGroup.numMorphTargets !== undefined ) {
  10814. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10815. renderer.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  10816. }
  10817. }
  10818. if ( geometryGroup.numMorphNormals !== undefined ) {
  10819. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10820. renderer.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  10821. }
  10822. }
  10823. deleteCustomAttributesBuffers( geometryGroup );
  10824. }
  10825. }
  10826. deleteCustomAttributesBuffers( geometry );
  10827. };
  10828. var deallocateTexture = function ( texture ) {
  10829. if ( texture.image && texture.image.__webglTextureCube ) {
  10830. // cube texture
  10831. renderer.deleteTexture( texture.image.__webglTextureCube );
  10832. } else {
  10833. // 2D texture
  10834. if ( ! texture.__webglInit ) return;
  10835. texture.__webglInit = false;
  10836. renderer.deleteTexture( texture.__webglTexture );
  10837. }
  10838. };
  10839. var deallocateRenderTarget = function ( renderTarget ) {
  10840. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  10841. renderer.deleteTexture( renderTarget.__webglTexture );
  10842. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  10843. for ( var i = 0; i < 6; i ++ ) {
  10844. renderer.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  10845. renderer.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  10846. }
  10847. } else {
  10848. renderer.deleteFramebuffer( renderTarget.__webglFramebuffer );
  10849. renderer.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  10850. }
  10851. };
  10852. var deallocateMaterial = function ( material ) {
  10853. var program = material.program;
  10854. if ( program === undefined ) return;
  10855. material.program = undefined;
  10856. // only deallocate GL program if this was the last use of shared program
  10857. // assumed there is only single copy of any program in the _programs list
  10858. // (that's how it's constructed)
  10859. shaderBuilder.removeProgram(program)
  10860. };
  10861. function deleteCustomAttributesBuffers( geometry ) {
  10862. if ( geometry.__webglCustomAttributesList ) {
  10863. for ( var id in geometry.__webglCustomAttributesList ) {
  10864. renderer.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  10865. }
  10866. }
  10867. };
  10868. // Buffer initialization
  10869. function initCustomAttributes ( geometry, object ) {
  10870. var nvertices = geometry.vertices.length;
  10871. var material = object.material;
  10872. if ( material.attributes ) {
  10873. if ( geometry.__webglCustomAttributesList === undefined ) {
  10874. geometry.__webglCustomAttributesList = [];
  10875. }
  10876. for ( var a in material.attributes ) {
  10877. var attribute = material.attributes[ a ];
  10878. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  10879. attribute.__webglInitialized = true;
  10880. var size = 1; // "f" and "i"
  10881. if ( attribute.type === "v2" ) size = 2;
  10882. else if ( attribute.type === "v3" ) size = 3;
  10883. else if ( attribute.type === "v4" ) size = 4;
  10884. else if ( attribute.type === "c" ) size = 3;
  10885. attribute.size = size;
  10886. attribute.array = new Float32Array( nvertices * size );
  10887. attribute.buffer = renderer.createBuffer();
  10888. attribute.buffer.belongsToAttribute = a;
  10889. attribute.needsUpdate = true;
  10890. }
  10891. geometry.__webglCustomAttributesList.push( attribute );
  10892. }
  10893. }
  10894. };
  10895. function getBufferMaterial( object, geometryGroup ) {
  10896. return object.material instanceof THREE.MeshFaceMaterial
  10897. ? object.material.materials[ geometryGroup.materialIndex ]
  10898. : object.material;
  10899. };
  10900. //
  10901. function initDirectBuffers( geometry ) {
  10902. var a, attribute;
  10903. for ( a in geometry.attributes ) {
  10904. attribute = geometry.attributes[ a ];
  10905. attribute.buffer = renderer.createBuffer();
  10906. if ( a === "index" ) {
  10907. renderer.setStaticIndexBuffer(attribute.buffer,attribute.array);
  10908. } else {
  10909. renderer.setStaticArrayBuffer(attribute.buffer,attribute.array);
  10910. }
  10911. }
  10912. };
  10913. // Buffer setting
  10914. function setDirectBuffers ( geometry, dispose ) {
  10915. var attributes = geometry.attributes;
  10916. var attributeName, attributeItem;
  10917. for ( attributeName in attributes ) {
  10918. attributeItem = attributes[ attributeName ];
  10919. if ( attributeItem.needsUpdate ) {
  10920. if ( attributeName === 'index' ) {
  10921. renderer.setDynamicIndexBuffer( attributeItem.buffer, attributeItem.array );
  10922. } else {
  10923. renderer.setDynamicArrayBuffer( attributeItem.buffer, attributeItem.array );
  10924. }
  10925. attributeItem.needsUpdate = false;
  10926. }
  10927. if ( dispose && ! attributeItem.dynamic ) {
  10928. delete attributeItem.array;
  10929. }
  10930. }
  10931. };
  10932. // Buffer rendering
  10933. this.renderBufferImmediate = function ( object, program, material ) {
  10934. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = renderer.createBuffer();
  10935. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = renderer.createBuffer();
  10936. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = renderer.createBuffer();
  10937. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = renderer.createBuffer();
  10938. if ( object.hasPositions ) {
  10939. renderer.setDynamicArrayBuffer( object.__webglVertexBuffer, object.positionArray);
  10940. renderer.setFloatAttribute(program.attributes.position, object.__webglVertexBuffer, 3, 0);
  10941. }
  10942. if ( object.hasNormals ) {
  10943. if ( material.shading === THREE.FlatShading ) {
  10944. var nx, ny, nz,
  10945. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  10946. normalArray,
  10947. i, il = object.count * 3;
  10948. for( i = 0; i < il; i += 9 ) {
  10949. normalArray = object.normalArray;
  10950. nax = normalArray[ i ];
  10951. nay = normalArray[ i + 1 ];
  10952. naz = normalArray[ i + 2 ];
  10953. nbx = normalArray[ i + 3 ];
  10954. nby = normalArray[ i + 4 ];
  10955. nbz = normalArray[ i + 5 ];
  10956. ncx = normalArray[ i + 6 ];
  10957. ncy = normalArray[ i + 7 ];
  10958. ncz = normalArray[ i + 8 ];
  10959. nx = ( nax + nbx + ncx ) / 3;
  10960. ny = ( nay + nby + ncy ) / 3;
  10961. nz = ( naz + nbz + ncz ) / 3;
  10962. normalArray[ i ] = nx;
  10963. normalArray[ i + 1 ] = ny;
  10964. normalArray[ i + 2 ] = nz;
  10965. normalArray[ i + 3 ] = nx;
  10966. normalArray[ i + 4 ] = ny;
  10967. normalArray[ i + 5 ] = nz;
  10968. normalArray[ i + 6 ] = nx;
  10969. normalArray[ i + 7 ] = ny;
  10970. normalArray[ i + 8 ] = nz;
  10971. }
  10972. }
  10973. renderer.setDynamicArrayBuffer( object.__webglNormalBuffer, object.normalArray);
  10974. renderer.setFloatAttribute(program.attributes.normal, object.__webglNormalBuffer, 3, 0);
  10975. }
  10976. if ( object.hasUvs && material.map ) {
  10977. renderer.setDynamicArrayBuffer( object.__webglUvBuffer, object.uvArray);
  10978. renderer.setFloatAttribute(program.attributes.uv, object.__webglUvBuffer, 2, 0);
  10979. }
  10980. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  10981. renderer.setDynamicArrayBuffer( object.__webglColorBuffer, object.colorArray);
  10982. renderer.setFloatAttribute(program.attributes.color, object.__webglColorBuffer, 3, 0);
  10983. }
  10984. renderer.drawTriangles(object.count );
  10985. object.count = 0;
  10986. };
  10987. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  10988. if ( material.visible === false ) return;
  10989. var program, programAttributes, linewidth, primitives, a, attribute, geometryAttributes;
  10990. var attributeItem, attributeName, attributePointer, attributeSize;
  10991. program = setProgram( camera, lights, fog, material, object );
  10992. programAttributes = program.attributes;
  10993. geometryAttributes = geometry.attributes;
  10994. var updateBuffers = false,
  10995. wireframeBit = material.wireframe ? 1 : 0,
  10996. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  10997. if ( geometryHash !== _currentGeometryGroupHash ) {
  10998. _currentGeometryGroupHash = geometryHash;
  10999. updateBuffers = true;
  11000. }
  11001. if ( updateBuffers ) {
  11002. renderer.disableAttributes();
  11003. }
  11004. // render mesh
  11005. if ( object instanceof THREE.Mesh ) {
  11006. var index = geometryAttributes[ "index" ];
  11007. // indexed triangles
  11008. if ( index ) {
  11009. var offsets = geometry.offsets;
  11010. // if there is more than 1 chunk
  11011. // must set attribute pointers to use new offsets for each chunk
  11012. // even if geometry and materials didn't change
  11013. if ( offsets.length > 1 ) updateBuffers = true;
  11014. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  11015. var startIndex = offsets[ i ].index;
  11016. if ( updateBuffers ) {
  11017. for ( attributeName in geometryAttributes ) {
  11018. if ( attributeName === 'index' ) continue;
  11019. attributePointer = programAttributes[ attributeName ];
  11020. attributeItem = geometryAttributes[ attributeName ];
  11021. attributeSize = attributeItem.itemSize;
  11022. if ( attributePointer >= 0 ) {
  11023. renderer.setFloatAttribute( attributePointer , attributeItem.buffer, attributeSize, startIndex * attributeSize * 4 );
  11024. }
  11025. }
  11026. }
  11027. // render indexed triangles
  11028. renderer.drawTriangleElements(index.buffer, offsets[ i ].count, offsets[ i ].start * 2);
  11029. _this.info.render.calls ++;
  11030. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  11031. _this.info.render.faces += offsets[ i ].count / 3;
  11032. }
  11033. // non-indexed triangles
  11034. } else {
  11035. if ( updateBuffers ) {
  11036. for ( attributeName in geometryAttributes ) {
  11037. attributePointer = programAttributes[ attributeName ];
  11038. attributeItem = geometryAttributes[ attributeName ];
  11039. attributeSize = attributeItem.itemSize;
  11040. if ( attributePointer >= 0 ) {
  11041. renderer.setFloatAttribute( attributePointer , attributeItem.buffer, attributeSize, 0 );
  11042. }
  11043. }
  11044. }
  11045. var position = geometry.attributes[ "position" ];
  11046. // render non-indexed triangles
  11047. renderer.drawTriangles( position.numItems / 3)
  11048. _this.info.render.calls ++;
  11049. _this.info.render.vertices += position.numItems / 3;
  11050. _this.info.render.faces += position.numItems / 3 / 3;
  11051. }
  11052. // render particles
  11053. } else if ( object instanceof THREE.ParticleSystem ) {
  11054. if ( updateBuffers ) {
  11055. for ( attributeName in geometryAttributes ) {
  11056. attributePointer = programAttributes[ attributeName ];
  11057. attributeItem = geometryAttributes[ attributeName ];
  11058. attributeSize = attributeItem.itemSize;
  11059. if ( attributePointer >= 0 ) {
  11060. renderer.setFloatAttribute( attributePointer , attributeItem.buffer, attributeSize, 0 );
  11061. }
  11062. }
  11063. var position = geometryAttributes[ "position" ];
  11064. // render particles
  11065. renderer.drawPoints(position.numItems / 3);
  11066. _this.info.render.calls ++;
  11067. _this.info.render.points += position.numItems / 3;
  11068. }
  11069. } else if ( object instanceof THREE.Line ) {
  11070. if ( updateBuffers ) {
  11071. for ( attributeName in geometryAttributes ) {
  11072. attributePointer = programAttributes[ attributeName ];
  11073. attributeItem = geometryAttributes[ attributeName ];
  11074. attributeSize = attributeItem.itemSize;
  11075. if ( attributePointer >= 0 ) {
  11076. renderer.setFloatAttribute( attributePointer , attributeItem.buffer, attributeSize, 0 );
  11077. }
  11078. }
  11079. var position = geometryAttributes[ "position" ];
  11080. // render lines
  11081. renderer.setLineWidth( material.linewidth );
  11082. renderer.drawLineStrip(position.numItems / 3);
  11083. _this.info.render.calls ++;
  11084. _this.info.render.points += position.numItems;
  11085. }
  11086. }
  11087. };
  11088. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  11089. if ( material.visible === false ) return;
  11090. var program, attributes, linewidth, primitives, a, attribute, i, il;
  11091. program = setProgram( camera, lights, fog, material, object );
  11092. attributes = program.attributes;
  11093. var updateBuffers = false,
  11094. wireframeBit = material.wireframe ? 1 : 0,
  11095. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  11096. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  11097. _currentGeometryGroupHash = geometryGroupHash;
  11098. updateBuffers = true;
  11099. }
  11100. if ( updateBuffers ) {
  11101. renderer.disableAttributes();
  11102. }
  11103. // vertices
  11104. if ( !material.morphTargets && attributes.position >= 0 ) {
  11105. if ( updateBuffers ) {
  11106. renderer.setFloatAttribute(attributes.position , geometryGroup.__webglVertexBuffer, 3, 0);
  11107. }
  11108. } else {
  11109. if ( object.morphTargetBase ) {
  11110. setupMorphTargets( material, geometryGroup, object );
  11111. }
  11112. }
  11113. if ( updateBuffers ) {
  11114. // custom attributes
  11115. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  11116. if ( geometryGroup.__webglCustomAttributesList ) {
  11117. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  11118. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  11119. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  11120. renderer.setFloatAttribute(attributes[ attribute.buffer.belongsToAttribute ] , attribute.buffer, attribute.size, 0);
  11121. }
  11122. }
  11123. }
  11124. // colors
  11125. if ( attributes.color >= 0 ) {
  11126. renderer.setFloatAttribute(attributes.color , geometryGroup.__webglColorBuffer,3, 0);
  11127. }
  11128. // normals
  11129. if ( attributes.normal >= 0 ) {
  11130. renderer.setFloatAttribute(attributes.normal, geometryGroup.__webglNormalBuffer, 3, 0);
  11131. }
  11132. // tangents
  11133. if ( attributes.tangent >= 0 ) {
  11134. renderer.setFloatAttribute(attributes.tangent, geometryGroup.__webglTangentBuffer, 4, 0);
  11135. }
  11136. // uvs
  11137. if ( attributes.uv >= 0 ) {
  11138. renderer.setFloatAttribute(attributes.uv, geometryGroup.__webglUVBuffer, 2, 0);
  11139. }
  11140. if ( attributes.uv2 >= 0 ) {
  11141. renderer.setFloatAttribute(attributes.uv2, geometryGroup.__webglUV2Buffer, 2, 0);
  11142. }
  11143. if ( material.skinning &&
  11144. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  11145. renderer.setFloatAttribute(attributes.skinIndex, geometryGroup.__webglSkinIndicesBuffer, 4, 0);
  11146. renderer.setFloatAttribute(attributes.skinWeight, geometryGroup.__webglSkinWeightsBuffer, 4, 0);
  11147. }
  11148. // line distances
  11149. if ( attributes.lineDistance >= 0 ) {
  11150. renderer.setFloatAttribute(attributes.lineDistance, geometryGroup.__webglLineDistanceBuffer, 1, 0);
  11151. }
  11152. }
  11153. // render mesh
  11154. if ( object instanceof THREE.Mesh ) {
  11155. // wireframe
  11156. if ( material.wireframe ) {
  11157. renderer.setLineWidth( material.wireframeLinewidth );
  11158. renderer.drawLineElements(geometryGroup.__webglLineBuffer,geometryGroup.__webglLineCount,0);
  11159. // triangles
  11160. } else {
  11161. renderer.drawTriangleElements( geometryGroup.__webglFaceBuffer, geometryGroup.__webglFaceCount, 0);
  11162. }
  11163. _this.info.render.calls ++;
  11164. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  11165. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  11166. // render lines
  11167. } else if ( object instanceof THREE.Line ) {
  11168. renderer.setLineWidth( material.linewidth );
  11169. if (object.type === THREE.LineStrip) {
  11170. renderer.drawLineStrip(geometryGroup.__webglLineCount);
  11171. } else {
  11172. renderer.drawLines(geometryGroup.__webglLineCount);
  11173. }
  11174. _this.info.render.calls ++;
  11175. // render particles
  11176. } else if ( object instanceof THREE.ParticleSystem ) {
  11177. renderer.drawPoints(geometryGroup.__webglParticleCount);
  11178. _this.info.render.calls ++;
  11179. _this.info.render.points += geometryGroup.__webglParticleCount;
  11180. // render ribbon
  11181. } else if ( object instanceof THREE.Ribbon ) {
  11182. renderer.drawTriangleStrip(geometryGroup.__webglVertexCount);
  11183. _this.info.render.calls ++;
  11184. }
  11185. };
  11186. function setupMorphTargets ( material, geometryGroup, object ) {
  11187. // set base
  11188. var attributes = material.program.attributes;
  11189. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  11190. renderer.setFloatAttribute(attributes.position, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ], 3, 0);
  11191. } else if ( attributes.position >= 0 ) {
  11192. renderer.setFloatAttribute(attributes.position, geometryGroup.__webglVertexBuffer, 3, 0);
  11193. }
  11194. if ( object.morphTargetForcedOrder.length ) {
  11195. // set forced order
  11196. var m = 0;
  11197. var order = object.morphTargetForcedOrder;
  11198. var influences = object.morphTargetInfluences;
  11199. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  11200. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  11201. renderer.setFloatAttribute(attributes[ "morphTarget" + m ], geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ], 3, 0);
  11202. }
  11203. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  11204. renderer.setFloatAttribute(attributes[ "morphNormal" + m ], geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ], 3, 0);
  11205. }
  11206. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  11207. m ++;
  11208. }
  11209. } else {
  11210. // find the most influencing
  11211. var influence, activeInfluenceIndices = [];
  11212. var influences = object.morphTargetInfluences;
  11213. var i, il = influences.length;
  11214. for ( i = 0; i < il; i ++ ) {
  11215. influence = influences[ i ];
  11216. if ( influence > 0 ) {
  11217. activeInfluenceIndices.push( [ influence, i ] );
  11218. }
  11219. }
  11220. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  11221. activeInfluenceIndices.sort( numericalSort );
  11222. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  11223. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  11224. activeInfluenceIndices.sort( numericalSort );
  11225. } else if ( activeInfluenceIndices.length === 0 ) {
  11226. activeInfluenceIndices.push( [ 0, 0 ] );
  11227. };
  11228. var influenceIndex, m = 0;
  11229. while ( m < material.numSupportedMorphTargets ) {
  11230. if ( activeInfluenceIndices[ m ] ) {
  11231. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  11232. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  11233. renderer.setFloatAttribute(attributes[ "morphTarget" + m ], geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ], 3, 0);
  11234. }
  11235. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  11236. renderer.setFloatAttribute(attributes[ "morphNormal" + m ], geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ], 3, 0);
  11237. }
  11238. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  11239. } else {
  11240. /*
  11241. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11242. if ( material.morphNormals ) {
  11243. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11244. }
  11245. */
  11246. object.__webglMorphTargetInfluences[ m ] = 0;
  11247. }
  11248. m ++;
  11249. }
  11250. }
  11251. // load updated influences uniform
  11252. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  11253. renderer.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  11254. }
  11255. };
  11256. // Sorting
  11257. function painterSortStable ( a, b ) {
  11258. if ( a.z !== b.z ) {
  11259. return b.z - a.z;
  11260. } else {
  11261. return a.id - b.id;
  11262. }
  11263. };
  11264. function numericalSort ( a, b ) {
  11265. return b[ 0 ] - a[ 0 ];
  11266. };
  11267. // Rendering
  11268. this.render = function ( scene, camera, renderTarget, forceClear ) {
  11269. if ( camera instanceof THREE.Camera === false ) {
  11270. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  11271. return;
  11272. }
  11273. var i, il,
  11274. webglObject, object,
  11275. renderList,
  11276. lights = scene.__lights,
  11277. fog = scene.fog;
  11278. // reset caching for this frame
  11279. _currentMaterialId = -1;
  11280. _lightsNeedUpdate = true;
  11281. // update scene graph
  11282. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  11283. // update camera matrices and frustum
  11284. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  11285. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  11286. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  11287. _frustum.setFromMatrix( _projScreenMatrix );
  11288. // update WebGL objects
  11289. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  11290. // custom render plugins (pre pass)
  11291. renderPlugins( this.renderPluginsPre, scene, camera );
  11292. //
  11293. _this.info.render.calls = 0;
  11294. _this.info.render.vertices = 0;
  11295. _this.info.render.faces = 0;
  11296. _this.info.render.points = 0;
  11297. renderer.setRenderTarget( renderTarget );
  11298. if ( this.autoClear || forceClear ) {
  11299. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  11300. }
  11301. // set matrices for regular objects (frustum culled)
  11302. renderList = scene.__webglObjects;
  11303. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11304. webglObject = renderList[ i ];
  11305. object = webglObject.object;
  11306. webglObject.id = i;
  11307. webglObject.render = false;
  11308. if ( object.visible ) {
  11309. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  11310. setupMatrices( object, camera );
  11311. unrollBufferMaterial( webglObject );
  11312. webglObject.render = true;
  11313. if ( this.sortObjects === true ) {
  11314. if ( object.renderDepth !== null ) {
  11315. webglObject.z = object.renderDepth;
  11316. } else {
  11317. _vector3.getPositionFromMatrix( object.matrixWorld );
  11318. _vector3.applyProjection(_projScreenMatrix);
  11319. webglObject.z = _vector3.z;
  11320. }
  11321. }
  11322. }
  11323. }
  11324. }
  11325. if ( this.sortObjects ) {
  11326. renderList.sort( painterSortStable );
  11327. }
  11328. // set matrices for immediate objects
  11329. renderList = scene.__webglObjectsImmediate;
  11330. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11331. webglObject = renderList[ i ];
  11332. object = webglObject.object;
  11333. if ( object.visible ) {
  11334. setupMatrices( object, camera );
  11335. unrollImmediateBufferMaterial( webglObject );
  11336. }
  11337. }
  11338. if ( scene.overrideMaterial ) {
  11339. var material = scene.overrideMaterial;
  11340. renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11341. renderer.setDepthTest( material.depthTest );
  11342. renderer.setDepthWrite( material.depthWrite );
  11343. renderer.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11344. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  11345. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  11346. } else {
  11347. var material = null;
  11348. // opaque pass (front-to-back order)
  11349. renderer.setBlending( THREE.NoBlending );
  11350. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  11351. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  11352. // transparent pass (back-to-front order)
  11353. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  11354. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  11355. }
  11356. // custom render plugins (post pass)
  11357. renderPlugins( this.renderPluginsPost, scene, camera );
  11358. // Generate mipmap if we're using any kind of mipmap filtering
  11359. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  11360. renderer.updateRenderTargetMipmap( renderTarget );
  11361. }
  11362. // Ensure depth buffer writing is enabled so it can be cleared on next render
  11363. renderer.setDepthTest( true );
  11364. renderer.setDepthWrite( true );
  11365. // _gl.finish();
  11366. };
  11367. function renderPlugins( plugins, scene, camera ) {
  11368. if ( ! plugins.length ) return;
  11369. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  11370. // reset state for plugin (to start from clean slate)
  11371. _currentProgram = null;
  11372. _currentCamera = null;
  11373. _currentGeometryGroupHash = -1;
  11374. _currentMaterialId = -1;
  11375. _lightsNeedUpdate = true;
  11376. renderer.resetState();
  11377. plugins[ i ].render( scene, camera, renderer.getCurrentWidth(), renderer.getCurrentWidth() );
  11378. // reset state after plugin (anything could have changed)
  11379. _currentProgram = null;
  11380. _currentCamera = null;
  11381. _currentGeometryGroupHash = -1;
  11382. _currentMaterialId = -1;
  11383. _lightsNeedUpdate = true;
  11384. renderer.resetState();
  11385. }
  11386. };
  11387. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11388. var webglObject, object, buffer, material, start, end, delta;
  11389. if ( reverse ) {
  11390. start = renderList.length - 1;
  11391. end = -1;
  11392. delta = -1;
  11393. } else {
  11394. start = 0;
  11395. end = renderList.length;
  11396. delta = 1;
  11397. }
  11398. for ( var i = start; i !== end; i += delta ) {
  11399. webglObject = renderList[ i ];
  11400. if ( webglObject.render ) {
  11401. object = webglObject.object;
  11402. buffer = webglObject.buffer;
  11403. if ( overrideMaterial ) {
  11404. material = overrideMaterial;
  11405. } else {
  11406. material = webglObject[ materialType ];
  11407. if ( ! material ) continue;
  11408. if ( useBlending ) renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11409. renderer.setDepthTest( material.depthTest );
  11410. renderer.setDepthWrite( material.depthWrite );
  11411. renderer.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11412. }
  11413. renderer.setMaterialFaces( material );
  11414. if ( buffer instanceof THREE.BufferGeometry ) {
  11415. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  11416. } else {
  11417. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  11418. }
  11419. }
  11420. }
  11421. };
  11422. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11423. var webglObject, object, material, program;
  11424. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  11425. webglObject = renderList[ i ];
  11426. object = webglObject.object;
  11427. if ( object.visible ) {
  11428. if ( overrideMaterial ) {
  11429. material = overrideMaterial;
  11430. } else {
  11431. material = webglObject[ materialType ];
  11432. if ( ! material ) continue;
  11433. if ( useBlending ) renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11434. renderer.setDepthTest( material.depthTest );
  11435. renderer.setDepthWrite( material.depthWrite );
  11436. renderer.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11437. }
  11438. _this.renderImmediateObject( camera, lights, fog, material, object );
  11439. }
  11440. }
  11441. };
  11442. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  11443. var program = setProgram( camera, lights, fog, material, object );
  11444. _currentGeometryGroupHash = -1;
  11445. renderer.setMaterialFaces( material );
  11446. if ( object.immediateRenderCallback ) {
  11447. object.immediateRenderCallback( program, renderer.getContext(), _frustum );
  11448. } else {
  11449. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  11450. }
  11451. };
  11452. function unrollImmediateBufferMaterial ( globject ) {
  11453. var object = globject.object,
  11454. material = object.material;
  11455. if ( material.transparent ) {
  11456. globject.transparent = material;
  11457. globject.opaque = null;
  11458. } else {
  11459. globject.opaque = material;
  11460. globject.transparent = null;
  11461. }
  11462. };
  11463. function unrollBufferMaterial ( globject ) {
  11464. var object = globject.object,
  11465. buffer = globject.buffer,
  11466. material, materialIndex, meshMaterial;
  11467. meshMaterial = object.material;
  11468. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  11469. materialIndex = buffer.materialIndex;
  11470. material = meshMaterial.materials[ materialIndex ];
  11471. if ( material.transparent ) {
  11472. globject.transparent = material;
  11473. globject.opaque = null;
  11474. } else {
  11475. globject.opaque = material;
  11476. globject.transparent = null;
  11477. }
  11478. } else {
  11479. material = meshMaterial;
  11480. if ( material ) {
  11481. if ( material.transparent ) {
  11482. globject.transparent = material;
  11483. globject.opaque = null;
  11484. } else {
  11485. globject.opaque = material;
  11486. globject.transparent = null;
  11487. }
  11488. }
  11489. }
  11490. };
  11491. // Geometry splitting
  11492. function sortFacesByMaterial ( geometry, material ) {
  11493. var f, fl, face, materialIndex, vertices,
  11494. groupHash, hash_map = {};
  11495. var numMorphTargets = geometry.morphTargets.length;
  11496. var numMorphNormals = geometry.morphNormals.length;
  11497. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  11498. geometry.geometryGroups = {};
  11499. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  11500. face = geometry.faces[ f ];
  11501. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  11502. if ( hash_map[ materialIndex ] === undefined ) {
  11503. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  11504. }
  11505. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  11506. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  11507. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  11508. }
  11509. vertices = face instanceof THREE.Face3 ? 3 : 4;
  11510. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  11511. hash_map[ materialIndex ].counter += 1;
  11512. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  11513. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  11514. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  11515. }
  11516. }
  11517. if ( face instanceof THREE.Face3 ) {
  11518. geometry.geometryGroups[ groupHash ].faces3.push( f );
  11519. } else {
  11520. geometry.geometryGroups[ groupHash ].faces4.push( f );
  11521. }
  11522. geometry.geometryGroups[ groupHash ].vertices += vertices;
  11523. }
  11524. geometry.geometryGroupsList = [];
  11525. for ( var g in geometry.geometryGroups ) {
  11526. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  11527. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  11528. }
  11529. };
  11530. // Objects refresh
  11531. this.initWebGLObjects = function ( scene ) {
  11532. if ( !scene.__webglObjects ) {
  11533. scene.__webglObjects = [];
  11534. scene.__webglObjectsImmediate = [];
  11535. scene.__webglSprites = [];
  11536. scene.__webglFlares = [];
  11537. }
  11538. while ( scene.__objectsAdded.length ) {
  11539. addObject( scene.__objectsAdded[ 0 ], scene );
  11540. scene.__objectsAdded.splice( 0, 1 );
  11541. }
  11542. while ( scene.__objectsRemoved.length ) {
  11543. removeObject( scene.__objectsRemoved[ 0 ], scene );
  11544. scene.__objectsRemoved.splice( 0, 1 );
  11545. }
  11546. // update must be called after objects adding / removal
  11547. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  11548. updateObject( scene.__webglObjects[ o ].object );
  11549. }
  11550. };
  11551. // Objects adding
  11552. function addObject( object, scene ) {
  11553. var g, geometry, material, geometryGroup;
  11554. if ( ! object.__webglInit ) {
  11555. object.__webglInit = true;
  11556. object._modelViewMatrix = new THREE.Matrix4();
  11557. object._normalMatrix = new THREE.Matrix3();
  11558. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  11559. object.geometry.__webglInit = true;
  11560. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  11561. }
  11562. if ( object instanceof THREE.Mesh ) {
  11563. geometry = object.geometry;
  11564. material = object.material;
  11565. if ( geometry instanceof THREE.Geometry ) {
  11566. if ( geometry.geometryGroups === undefined ) {
  11567. sortFacesByMaterial( geometry, material );
  11568. }
  11569. // create separate VBOs per geometry chunk
  11570. for ( g in geometry.geometryGroups ) {
  11571. geometryGroup = geometry.geometryGroups[ g ];
  11572. // initialise VBO on the first access
  11573. if ( ! geometryGroup.__webglVertexBuffer ) {
  11574. meshRenderer.createBuffers( geometryGroup );
  11575. meshRenderer.initBuffers( geometryGroup, object );
  11576. geometry.verticesNeedUpdate = true;
  11577. geometry.morphTargetsNeedUpdate = true;
  11578. geometry.elementsNeedUpdate = true;
  11579. geometry.uvsNeedUpdate = true;
  11580. geometry.normalsNeedUpdate = true;
  11581. geometry.tangentsNeedUpdate = true;
  11582. geometry.colorsNeedUpdate = true;
  11583. }
  11584. }
  11585. } else if ( geometry instanceof THREE.BufferGeometry ) {
  11586. initDirectBuffers( geometry );
  11587. }
  11588. } else if ( object instanceof THREE.Ribbon ) {
  11589. geometry = object.geometry;
  11590. if ( ! geometry.__webglVertexBuffer ) {
  11591. ribbonRenderer.createBuffers( geometry );
  11592. ribbonRenderer.initBuffers( geometry, object );
  11593. geometry.verticesNeedUpdate = true;
  11594. geometry.colorsNeedUpdate = true;
  11595. geometry.normalsNeedUpdate = true;
  11596. }
  11597. } else if ( object instanceof THREE.Line ) {
  11598. geometry = object.geometry;
  11599. if ( ! geometry.__webglVertexBuffer ) {
  11600. if ( geometry instanceof THREE.Geometry ) {
  11601. lineRenderer.createBuffers( geometry );
  11602. lineRenderer.initBuffers( geometry, object );
  11603. geometry.verticesNeedUpdate = true;
  11604. geometry.colorsNeedUpdate = true;
  11605. geometry.lineDistancesNeedUpdate = true;
  11606. } else if ( geometry instanceof THREE.BufferGeometry ) {
  11607. initDirectBuffers( geometry );
  11608. }
  11609. }
  11610. } else if ( object instanceof THREE.ParticleSystem ) {
  11611. geometry = object.geometry;
  11612. if ( ! geometry.__webglVertexBuffer ) {
  11613. if ( geometry instanceof THREE.Geometry ) {
  11614. particleRenderer.createBuffers( geometry );
  11615. particleRenderer.initBuffers( geometry, object );
  11616. geometry.verticesNeedUpdate = true;
  11617. geometry.colorsNeedUpdate = true;
  11618. } else if ( geometry instanceof THREE.BufferGeometry ) {
  11619. initDirectBuffers( geometry );
  11620. }
  11621. }
  11622. }
  11623. }
  11624. if ( ! object.__webglActive ) {
  11625. if ( object instanceof THREE.Mesh ) {
  11626. geometry = object.geometry;
  11627. if ( geometry instanceof THREE.BufferGeometry ) {
  11628. addBuffer( scene.__webglObjects, geometry, object );
  11629. } else if ( geometry instanceof THREE.Geometry ) {
  11630. for ( g in geometry.geometryGroups ) {
  11631. geometryGroup = geometry.geometryGroups[ g ];
  11632. addBuffer( scene.__webglObjects, geometryGroup, object );
  11633. }
  11634. }
  11635. } else if ( object instanceof THREE.Ribbon ||
  11636. object instanceof THREE.Line ||
  11637. object instanceof THREE.ParticleSystem ) {
  11638. geometry = object.geometry;
  11639. addBuffer( scene.__webglObjects, geometry, object );
  11640. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  11641. addBufferImmediate( scene.__webglObjectsImmediate, object );
  11642. } else if ( object instanceof THREE.Sprite ) {
  11643. scene.__webglSprites.push( object );
  11644. } else if ( object instanceof THREE.LensFlare ) {
  11645. scene.__webglFlares.push( object );
  11646. }
  11647. object.__webglActive = true;
  11648. }
  11649. };
  11650. function addBuffer ( objlist, buffer, object ) {
  11651. objlist.push(
  11652. {
  11653. id: null,
  11654. buffer: buffer,
  11655. object: object,
  11656. opaque: null,
  11657. transparent: null,
  11658. render: false,
  11659. z: 0
  11660. }
  11661. );
  11662. };
  11663. function addBufferImmediate ( objlist, object ) {
  11664. objlist.push(
  11665. {
  11666. object: object,
  11667. opaque: null,
  11668. transparent: null
  11669. }
  11670. );
  11671. };
  11672. // Objects updates
  11673. function updateObject ( object ) {
  11674. var geometry = object.geometry,
  11675. geometryGroup, customAttributesDirty, material;
  11676. if ( object instanceof THREE.Mesh ) {
  11677. if ( geometry instanceof THREE.BufferGeometry ) {
  11678. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  11679. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  11680. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  11681. setDirectBuffers( geometry, !geometry.dynamic );
  11682. }
  11683. geometry.verticesNeedUpdate = false;
  11684. geometry.elementsNeedUpdate = false;
  11685. geometry.uvsNeedUpdate = false;
  11686. geometry.normalsNeedUpdate = false;
  11687. geometry.colorsNeedUpdate = false;
  11688. geometry.tangentsNeedUpdate = false;
  11689. } else {
  11690. // check all geometry groups
  11691. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  11692. geometryGroup = geometry.geometryGroupsList[ i ];
  11693. material = getBufferMaterial( object, geometryGroup );
  11694. if ( geometry.buffersNeedUpdate ) {
  11695. meshRenderer.initBuffers( geometryGroup, object );
  11696. }
  11697. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11698. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  11699. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  11700. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  11701. meshRenderer.setBuffers( geometryGroup, object, !geometry.dynamic, material );
  11702. }
  11703. }
  11704. geometry.verticesNeedUpdate = false;
  11705. geometry.morphTargetsNeedUpdate = false;
  11706. geometry.elementsNeedUpdate = false;
  11707. geometry.uvsNeedUpdate = false;
  11708. geometry.normalsNeedUpdate = false;
  11709. geometry.colorsNeedUpdate = false;
  11710. geometry.tangentsNeedUpdate = false;
  11711. geometry.buffersNeedUpdate = false;
  11712. material.attributes && clearCustomAttributes( material );
  11713. }
  11714. } else if ( object instanceof THREE.Ribbon ) {
  11715. material = getBufferMaterial( object, geometry );
  11716. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11717. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  11718. ribbonRenderer.setBuffers( geometry);
  11719. }
  11720. geometry.verticesNeedUpdate = false;
  11721. geometry.colorsNeedUpdate = false;
  11722. geometry.normalsNeedUpdate = false;
  11723. material.attributes && clearCustomAttributes( material );
  11724. } else if ( object instanceof THREE.Line ) {
  11725. if ( geometry instanceof THREE.BufferGeometry ) {
  11726. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  11727. setDirectBuffers( geometry, !geometry.dynamic );
  11728. }
  11729. geometry.verticesNeedUpdate = false;
  11730. geometry.colorsNeedUpdate = false;
  11731. } else {
  11732. material = getBufferMaterial( object, geometry );
  11733. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11734. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  11735. lineRenderer.setBuffers( geometry);
  11736. }
  11737. geometry.verticesNeedUpdate = false;
  11738. geometry.colorsNeedUpdate = false;
  11739. geometry.lineDistancesNeedUpdate = false;
  11740. material.attributes && clearCustomAttributes( material );
  11741. }
  11742. } else if ( object instanceof THREE.ParticleSystem ) {
  11743. if ( geometry instanceof THREE.BufferGeometry ) {
  11744. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  11745. setDirectBuffers( geometry, !geometry.dynamic );
  11746. }
  11747. geometry.verticesNeedUpdate = false;
  11748. geometry.colorsNeedUpdate = false;
  11749. } else {
  11750. material = getBufferMaterial( object, geometry );
  11751. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11752. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  11753. particleRenderer.setBuffers( geometry, object, _projScreenMatrix);
  11754. }
  11755. geometry.verticesNeedUpdate = false;
  11756. geometry.colorsNeedUpdate = false;
  11757. material.attributes && clearCustomAttributes( material );
  11758. }
  11759. }
  11760. };
  11761. // Objects updates - custom attributes check
  11762. function areCustomAttributesDirty ( material ) {
  11763. for ( var a in material.attributes ) {
  11764. if ( material.attributes[ a ].needsUpdate ) return true;
  11765. }
  11766. return false;
  11767. };
  11768. function clearCustomAttributes ( material ) {
  11769. for ( var a in material.attributes ) {
  11770. material.attributes[ a ].needsUpdate = false;
  11771. }
  11772. };
  11773. // Objects removal
  11774. function removeObject ( object, scene ) {
  11775. if ( object instanceof THREE.Mesh ||
  11776. object instanceof THREE.ParticleSystem ||
  11777. object instanceof THREE.Ribbon ||
  11778. object instanceof THREE.Line ) {
  11779. removeInstances( scene.__webglObjects, object );
  11780. } else if ( object instanceof THREE.Sprite ) {
  11781. removeInstancesDirect( scene.__webglSprites, object );
  11782. } else if ( object instanceof THREE.LensFlare ) {
  11783. removeInstancesDirect( scene.__webglFlares, object );
  11784. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  11785. removeInstances( scene.__webglObjectsImmediate, object );
  11786. }
  11787. object.__webglActive = false;
  11788. };
  11789. function removeInstances ( objlist, object ) {
  11790. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  11791. if ( objlist[ o ].object === object ) {
  11792. objlist.splice( o, 1 );
  11793. }
  11794. }
  11795. };
  11796. function removeInstancesDirect ( objlist, object ) {
  11797. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  11798. if ( objlist[ o ] === object ) {
  11799. objlist.splice( o, 1 );
  11800. }
  11801. }
  11802. };
  11803. // Materials
  11804. this.initMaterial = function ( material, lights, fog, object ) {
  11805. material.addEventListener( 'dispose', onMaterialDispose );
  11806. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  11807. if ( material instanceof THREE.MeshDepthMaterial ) {
  11808. shaderID = 'depth';
  11809. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  11810. shaderID = 'normal';
  11811. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  11812. shaderID = 'basic';
  11813. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  11814. shaderID = 'lambert';
  11815. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  11816. shaderID = 'phong';
  11817. } else if ( material instanceof THREE.LineBasicMaterial ) {
  11818. shaderID = 'basic';
  11819. } else if ( material instanceof THREE.LineDashedMaterial ) {
  11820. shaderID = 'dashed';
  11821. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  11822. shaderID = 'particle_basic';
  11823. }
  11824. if ( shaderID ) {
  11825. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  11826. }
  11827. // heuristics to create shader parameters according to lights in the scene
  11828. // (not to blow over maxLights budget)
  11829. maxLightCount = allocateLights( lights );
  11830. maxShadows = allocateShadows( lights );
  11831. maxBones = allocateBones( object );
  11832. parameters = {
  11833. map: !!material.map,
  11834. envMap: !!material.envMap,
  11835. lightMap: !!material.lightMap,
  11836. bumpMap: !!material.bumpMap,
  11837. normalMap: !!material.normalMap,
  11838. specularMap: !!material.specularMap,
  11839. vertexColors: material.vertexColors,
  11840. fog: fog,
  11841. useFog: material.fog,
  11842. fogExp: fog instanceof THREE.FogExp2,
  11843. sizeAttenuation: material.sizeAttenuation,
  11844. skinning: material.skinning,
  11845. maxBones: maxBones,
  11846. useVertexTexture: renderer.supportsBoneTextures && object && object.useVertexTexture,
  11847. boneTextureWidth: object && object.boneTextureWidth,
  11848. boneTextureHeight: object && object.boneTextureHeight,
  11849. morphTargets: material.morphTargets,
  11850. morphNormals: material.morphNormals,
  11851. maxMorphTargets: this.maxMorphTargets,
  11852. maxMorphNormals: this.maxMorphNormals,
  11853. maxDirLights: maxLightCount.directional,
  11854. maxPointLights: maxLightCount.point,
  11855. maxSpotLights: maxLightCount.spot,
  11856. maxHemiLights: maxLightCount.hemi,
  11857. maxShadows: maxShadows,
  11858. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  11859. shadowMapType: this.shadowMapType,
  11860. shadowMapDebug: this.shadowMapDebug,
  11861. shadowMapCascade: this.shadowMapCascade,
  11862. alphaTest: material.alphaTest,
  11863. metal: material.metal,
  11864. perPixel: material.perPixel,
  11865. wrapAround: material.wrapAround,
  11866. doubleSided: material.side === THREE.DoubleSide,
  11867. flipSided: material.side === THREE.BackSide,
  11868. gammaInput : this.gammaInput,
  11869. gammaOutput : this.gammaOutput ,
  11870. physicallyBasedShading : this.physicallyBasedShading
  11871. };
  11872. material.program = shaderBuilder.buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  11873. var attributes = material.program.attributes;
  11874. if ( material.morphTargets ) {
  11875. material.numSupportedMorphTargets = 0;
  11876. var id, base = "morphTarget";
  11877. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  11878. id = base + i;
  11879. if ( attributes[ id ] >= 0 ) {
  11880. material.numSupportedMorphTargets ++;
  11881. }
  11882. }
  11883. }
  11884. if ( material.morphNormals ) {
  11885. material.numSupportedMorphNormals = 0;
  11886. var id, base = "morphNormal";
  11887. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  11888. id = base + i;
  11889. if ( attributes[ id ] >= 0 ) {
  11890. material.numSupportedMorphNormals ++;
  11891. }
  11892. }
  11893. }
  11894. material.uniformsList = [];
  11895. for ( u in material.uniforms ) {
  11896. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  11897. }
  11898. };
  11899. function setMaterialShaders( material, shaders ) {
  11900. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  11901. material.vertexShader = shaders.vertexShader;
  11902. material.fragmentShader = shaders.fragmentShader;
  11903. };
  11904. function setProgram( camera, lights, fog, material, object ) {
  11905. _usedTextureUnits = 0;
  11906. if ( material.needsUpdate ) {
  11907. if ( material.program ) deallocateMaterial( material );
  11908. _this.initMaterial( material, lights, fog, object );
  11909. material.needsUpdate = false;
  11910. }
  11911. if ( material.morphTargets ) {
  11912. if ( ! object.__webglMorphTargetInfluences ) {
  11913. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  11914. }
  11915. }
  11916. var refreshMaterial = false;
  11917. var program = material.program,
  11918. p_uniforms = program.uniforms,
  11919. m_uniforms = material.uniforms;
  11920. if ( program !== _currentProgram ) {
  11921. renderer.useProgram( program );
  11922. _currentProgram = program;
  11923. refreshMaterial = true;
  11924. }
  11925. if ( material.id !== _currentMaterialId ) {
  11926. _currentMaterialId = material.id;
  11927. refreshMaterial = true;
  11928. }
  11929. if ( refreshMaterial || camera !== _currentCamera ) {
  11930. renderer.uniformMatrix4fv( p_uniforms.projectionMatrix, camera.projectionMatrix.elements );
  11931. if ( camera !== _currentCamera ) _currentCamera = camera;
  11932. }
  11933. // skinning uniforms must be set even if material didn't change
  11934. // auto-setting of texture unit for bone texture must go before other textures
  11935. // not sure why, but otherwise weird things happen
  11936. if ( material.skinning ) {
  11937. if ( renderer.supportsBoneTextures && object.useVertexTexture ) {
  11938. if ( p_uniforms.boneTexture !== null ) {
  11939. var textureUnit = getTextureUnit();
  11940. renderer.uniform1i( p_uniforms.boneTexture, textureUnit );
  11941. renderer.setTexture( object.boneTexture, textureUnit );
  11942. }
  11943. } else {
  11944. if ( p_uniforms.boneGlobalMatrices !== null ) {
  11945. renderer.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, object.boneMatrices );
  11946. }
  11947. }
  11948. }
  11949. if ( refreshMaterial ) {
  11950. // refresh uniforms common to several materials
  11951. if ( fog && material.fog ) {
  11952. refreshUniformsFog( m_uniforms, fog );
  11953. }
  11954. if ( material instanceof THREE.MeshPhongMaterial ||
  11955. material instanceof THREE.MeshLambertMaterial ||
  11956. material.lights ) {
  11957. if ( _lightsNeedUpdate ) {
  11958. setupLights( program, lights );
  11959. _lightsNeedUpdate = false;
  11960. }
  11961. refreshUniformsLights( m_uniforms, _lights );
  11962. }
  11963. if ( material instanceof THREE.MeshBasicMaterial ||
  11964. material instanceof THREE.MeshLambertMaterial ||
  11965. material instanceof THREE.MeshPhongMaterial ) {
  11966. refreshUniformsCommon( m_uniforms, material );
  11967. }
  11968. // refresh single material specific uniforms
  11969. if ( material instanceof THREE.LineBasicMaterial ) {
  11970. refreshUniformsLine( m_uniforms, material );
  11971. } else if ( material instanceof THREE.LineDashedMaterial ) {
  11972. refreshUniformsLine( m_uniforms, material );
  11973. refreshUniformsDash( m_uniforms, material );
  11974. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  11975. refreshUniformsParticle( m_uniforms, material );
  11976. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  11977. refreshUniformsPhong( m_uniforms, material );
  11978. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  11979. refreshUniformsLambert( m_uniforms, material );
  11980. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  11981. m_uniforms.mNear.value = camera.near;
  11982. m_uniforms.mFar.value = camera.far;
  11983. m_uniforms.opacity.value = material.opacity;
  11984. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  11985. m_uniforms.opacity.value = material.opacity;
  11986. }
  11987. if ( object.receiveShadow && ! material._shadowPass ) {
  11988. refreshUniformsShadow( m_uniforms, lights );
  11989. }
  11990. // load common uniforms
  11991. loadUniformsGeneric( program, material.uniformsList );
  11992. // load material specific uniforms
  11993. // (shader material also gets them for the sake of genericity)
  11994. if ( material instanceof THREE.ShaderMaterial ||
  11995. material instanceof THREE.MeshPhongMaterial ||
  11996. material.envMap ) {
  11997. if ( p_uniforms.cameraPosition !== null ) {
  11998. _vector3.getPositionFromMatrix( camera.matrixWorld );
  11999. renderer.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  12000. }
  12001. }
  12002. if ( material instanceof THREE.MeshPhongMaterial ||
  12003. material instanceof THREE.MeshLambertMaterial ||
  12004. material instanceof THREE.ShaderMaterial ||
  12005. material.skinning ) {
  12006. if ( p_uniforms.viewMatrix !== null ) {
  12007. renderer.uniformMatrix4fv( p_uniforms.viewMatrix, camera.matrixWorldInverse.elements );
  12008. }
  12009. }
  12010. }
  12011. loadUniformsMatrices( p_uniforms, object );
  12012. if ( p_uniforms.modelMatrix !== null ) {
  12013. renderer.uniformMatrix4fv( p_uniforms.modelMatrix, object.matrixWorld.elements );
  12014. }
  12015. return program;
  12016. };
  12017. // Uniforms (refresh uniforms objects)
  12018. function refreshUniformsCommon ( uniforms, material ) {
  12019. uniforms.opacity.value = material.opacity;
  12020. if ( _this.gammaInput ) {
  12021. uniforms.diffuse.value.copyGammaToLinear( material.color );
  12022. } else {
  12023. uniforms.diffuse.value = material.color;
  12024. }
  12025. uniforms.map.value = material.map;
  12026. uniforms.lightMap.value = material.lightMap;
  12027. uniforms.specularMap.value = material.specularMap;
  12028. if ( material.bumpMap ) {
  12029. uniforms.bumpMap.value = material.bumpMap;
  12030. uniforms.bumpScale.value = material.bumpScale;
  12031. }
  12032. if ( material.normalMap ) {
  12033. uniforms.normalMap.value = material.normalMap;
  12034. uniforms.normalScale.value.copy( material.normalScale );
  12035. }
  12036. // uv repeat and offset setting priorities
  12037. // 1. color map
  12038. // 2. specular map
  12039. // 3. normal map
  12040. // 4. bump map
  12041. var uvScaleMap;
  12042. if ( material.map ) {
  12043. uvScaleMap = material.map;
  12044. } else if ( material.specularMap ) {
  12045. uvScaleMap = material.specularMap;
  12046. } else if ( material.normalMap ) {
  12047. uvScaleMap = material.normalMap;
  12048. } else if ( material.bumpMap ) {
  12049. uvScaleMap = material.bumpMap;
  12050. }
  12051. if ( uvScaleMap !== undefined ) {
  12052. var offset = uvScaleMap.offset;
  12053. var repeat = uvScaleMap.repeat;
  12054. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12055. }
  12056. uniforms.envMap.value = material.envMap;
  12057. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  12058. if ( _this.gammaInput ) {
  12059. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  12060. uniforms.reflectivity.value = material.reflectivity;
  12061. } else {
  12062. uniforms.reflectivity.value = material.reflectivity;
  12063. }
  12064. uniforms.refractionRatio.value = material.refractionRatio;
  12065. uniforms.combine.value = material.combine;
  12066. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  12067. };
  12068. function refreshUniformsLine ( uniforms, material ) {
  12069. uniforms.diffuse.value = material.color;
  12070. uniforms.opacity.value = material.opacity;
  12071. };
  12072. function refreshUniformsDash ( uniforms, material ) {
  12073. uniforms.dashSize.value = material.dashSize;
  12074. uniforms.totalSize.value = material.dashSize + material.gapSize;
  12075. uniforms.scale.value = material.scale;
  12076. };
  12077. function refreshUniformsParticle ( uniforms, material ) {
  12078. uniforms.psColor.value = material.color;
  12079. uniforms.opacity.value = material.opacity;
  12080. uniforms.size.value = material.size;
  12081. uniforms.scale.value = renderer.getDomElement().height / 2.0; // TODO: Cache this.
  12082. uniforms.map.value = material.map;
  12083. };
  12084. function refreshUniformsFog ( uniforms, fog ) {
  12085. uniforms.fogColor.value = fog.color;
  12086. if ( fog instanceof THREE.Fog ) {
  12087. uniforms.fogNear.value = fog.near;
  12088. uniforms.fogFar.value = fog.far;
  12089. } else if ( fog instanceof THREE.FogExp2 ) {
  12090. uniforms.fogDensity.value = fog.density;
  12091. }
  12092. };
  12093. function refreshUniformsPhong ( uniforms, material ) {
  12094. uniforms.shininess.value = material.shininess;
  12095. if ( _this.gammaInput ) {
  12096. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  12097. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  12098. uniforms.specular.value.copyGammaToLinear( material.specular );
  12099. } else {
  12100. uniforms.ambient.value = material.ambient;
  12101. uniforms.emissive.value = material.emissive;
  12102. uniforms.specular.value = material.specular;
  12103. }
  12104. if ( material.wrapAround ) {
  12105. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12106. }
  12107. };
  12108. function refreshUniformsLambert ( uniforms, material ) {
  12109. if ( _this.gammaInput ) {
  12110. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  12111. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  12112. } else {
  12113. uniforms.ambient.value = material.ambient;
  12114. uniforms.emissive.value = material.emissive;
  12115. }
  12116. if ( material.wrapAround ) {
  12117. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12118. }
  12119. };
  12120. function refreshUniformsLights ( uniforms, lights ) {
  12121. uniforms.ambientLightColor.value = lights.ambient;
  12122. uniforms.directionalLightColor.value = lights.directional.colors;
  12123. uniforms.directionalLightDirection.value = lights.directional.positions;
  12124. uniforms.pointLightColor.value = lights.point.colors;
  12125. uniforms.pointLightPosition.value = lights.point.positions;
  12126. uniforms.pointLightDistance.value = lights.point.distances;
  12127. uniforms.spotLightColor.value = lights.spot.colors;
  12128. uniforms.spotLightPosition.value = lights.spot.positions;
  12129. uniforms.spotLightDistance.value = lights.spot.distances;
  12130. uniforms.spotLightDirection.value = lights.spot.directions;
  12131. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  12132. uniforms.spotLightExponent.value = lights.spot.exponents;
  12133. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  12134. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  12135. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  12136. };
  12137. function refreshUniformsShadow ( uniforms, lights ) {
  12138. if ( uniforms.shadowMatrix ) {
  12139. var j = 0;
  12140. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  12141. var light = lights[ i ];
  12142. if ( ! light.castShadow ) continue;
  12143. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  12144. uniforms.shadowMap.value[ j ] = light.shadowMap;
  12145. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  12146. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  12147. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  12148. uniforms.shadowBias.value[ j ] = light.shadowBias;
  12149. j ++;
  12150. }
  12151. }
  12152. }
  12153. };
  12154. // Uniforms (load to GPU)
  12155. function loadUniformsMatrices ( uniforms, object ) {
  12156. renderer.uniformMatrix4fv( uniforms.modelViewMatrix, object._modelViewMatrix.elements );
  12157. if ( uniforms.normalMatrix ) {
  12158. renderer.uniformMatrix3fv( uniforms.normalMatrix, object._normalMatrix.elements );
  12159. }
  12160. };
  12161. function getTextureUnit() {
  12162. var textureUnit = _usedTextureUnits;
  12163. if ( textureUnit >= renderer.maxTextures ) {
  12164. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + renderer.maxTextures );
  12165. }
  12166. _usedTextureUnits += 1;
  12167. return textureUnit;
  12168. };
  12169. function loadUniformsGeneric ( program, uniforms ) {
  12170. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  12171. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  12172. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  12173. if ( !location ) continue;
  12174. uniform = uniforms[ j ][ 0 ];
  12175. type = uniform.type;
  12176. value = uniform.value;
  12177. if ( type === "i" ) { // single integer
  12178. renderer.uniform1i( location, value );
  12179. } else if ( type === "f" ) { // single float
  12180. renderer.uniform1f( location, value );
  12181. } else if ( type === "v2" ) { // single THREE.Vector2
  12182. renderer.uniform2f( location, value.x, value.y );
  12183. } else if ( type === "v3" ) { // single THREE.Vector3
  12184. renderer.uniform3f( location, value.x, value.y, value.z );
  12185. } else if ( type === "v4" ) { // single THREE.Vector4
  12186. renderer.uniform4f( location, value.x, value.y, value.z, value.w );
  12187. } else if ( type === "c" ) { // single THREE.Color
  12188. renderer.uniform3f( location, value.r, value.g, value.b );
  12189. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  12190. renderer.uniform1iv( location, value );
  12191. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  12192. renderer.uniform3iv( location, value );
  12193. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  12194. renderer.uniform1fv( location, value );
  12195. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  12196. renderer.uniform3fv( location, value );
  12197. } else if ( type === "v2v" ) { // array of THREE.Vector2
  12198. if ( uniform._array === undefined ) {
  12199. uniform._array = new Float32Array( 2 * value.length );
  12200. }
  12201. for ( i = 0, il = value.length; i < il; i ++ ) {
  12202. offset = i * 2;
  12203. uniform._array[ offset ] = value[ i ].x;
  12204. uniform._array[ offset + 1 ] = value[ i ].y;
  12205. }
  12206. renderer.uniform2fv( location, uniform._array );
  12207. } else if ( type === "v3v" ) { // array of THREE.Vector3
  12208. if ( uniform._array === undefined ) {
  12209. uniform._array = new Float32Array( 3 * value.length );
  12210. }
  12211. for ( i = 0, il = value.length; i < il; i ++ ) {
  12212. offset = i * 3;
  12213. uniform._array[ offset ] = value[ i ].x;
  12214. uniform._array[ offset + 1 ] = value[ i ].y;
  12215. uniform._array[ offset + 2 ] = value[ i ].z;
  12216. }
  12217. renderer.uniform3fv( location, uniform._array );
  12218. } else if ( type === "v4v" ) { // array of THREE.Vector4
  12219. if ( uniform._array === undefined ) {
  12220. uniform._array = new Float32Array( 4 * value.length );
  12221. }
  12222. for ( i = 0, il = value.length; i < il; i ++ ) {
  12223. offset = i * 4;
  12224. uniform._array[ offset ] = value[ i ].x;
  12225. uniform._array[ offset + 1 ] = value[ i ].y;
  12226. uniform._array[ offset + 2 ] = value[ i ].z;
  12227. uniform._array[ offset + 3 ] = value[ i ].w;
  12228. }
  12229. renderer.uniform4fv( location, uniform._array );
  12230. } else if ( type === "m4") { // single THREE.Matrix4
  12231. if ( uniform._array === undefined ) {
  12232. uniform._array = new Float32Array( 16 );
  12233. }
  12234. value.flattenToArray( uniform._array );
  12235. renderer.uniformMatrix4fv( location, uniform._array );
  12236. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  12237. if ( uniform._array === undefined ) {
  12238. uniform._array = new Float32Array( 16 * value.length );
  12239. }
  12240. for ( i = 0, il = value.length; i < il; i ++ ) {
  12241. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  12242. }
  12243. renderer.uniformMatrix4fv( location, uniform._array );
  12244. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  12245. texture = value;
  12246. textureUnit = getTextureUnit();
  12247. renderer.uniform1i( location, textureUnit );
  12248. if ( !texture ) continue;
  12249. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  12250. renderer.setCubeTexture( texture, textureUnit );
  12251. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  12252. renderer.setCubeTextureDynamic( texture, textureUnit );
  12253. } else {
  12254. renderer.setTexture( texture, textureUnit );
  12255. }
  12256. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  12257. if ( uniform._array === undefined ) {
  12258. uniform._array = [];
  12259. }
  12260. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12261. uniform._array[ i ] = getTextureUnit();
  12262. }
  12263. renderer.uniform1iv( location, uniform._array );
  12264. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12265. texture = uniform.value[ i ];
  12266. textureUnit = uniform._array[ i ];
  12267. if ( !texture ) continue;
  12268. renderer.setTexture( texture, textureUnit );
  12269. }
  12270. }
  12271. }
  12272. };
  12273. function setupMatrices ( object, camera ) {
  12274. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  12275. object._normalMatrix.getInverse( object._modelViewMatrix );
  12276. object._normalMatrix.transpose();
  12277. };
  12278. //
  12279. function setColorGamma( array, offset, color, intensitySq ) {
  12280. array[ offset ] = color.r * color.r * intensitySq;
  12281. array[ offset + 1 ] = color.g * color.g * intensitySq;
  12282. array[ offset + 2 ] = color.b * color.b * intensitySq;
  12283. };
  12284. function setColorLinear( array, offset, color, intensity ) {
  12285. array[ offset ] = color.r * intensity;
  12286. array[ offset + 1 ] = color.g * intensity;
  12287. array[ offset + 2 ] = color.b * intensity;
  12288. };
  12289. function setupLights ( program, lights ) {
  12290. var l, ll, light, n,
  12291. r = 0, g = 0, b = 0,
  12292. color, skyColor, groundColor,
  12293. intensity, intensitySq,
  12294. position,
  12295. distance,
  12296. zlights = _lights,
  12297. dirColors = zlights.directional.colors,
  12298. dirPositions = zlights.directional.positions,
  12299. pointColors = zlights.point.colors,
  12300. pointPositions = zlights.point.positions,
  12301. pointDistances = zlights.point.distances,
  12302. spotColors = zlights.spot.colors,
  12303. spotPositions = zlights.spot.positions,
  12304. spotDistances = zlights.spot.distances,
  12305. spotDirections = zlights.spot.directions,
  12306. spotAnglesCos = zlights.spot.anglesCos,
  12307. spotExponents = zlights.spot.exponents,
  12308. hemiSkyColors = zlights.hemi.skyColors,
  12309. hemiGroundColors = zlights.hemi.groundColors,
  12310. hemiPositions = zlights.hemi.positions,
  12311. dirLength = 0,
  12312. pointLength = 0,
  12313. spotLength = 0,
  12314. hemiLength = 0,
  12315. dirCount = 0,
  12316. pointCount = 0,
  12317. spotCount = 0,
  12318. hemiCount = 0,
  12319. dirOffset = 0,
  12320. pointOffset = 0,
  12321. spotOffset = 0,
  12322. hemiOffset = 0;
  12323. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12324. light = lights[ l ];
  12325. if ( light.onlyShadow ) continue;
  12326. color = light.color;
  12327. intensity = light.intensity;
  12328. distance = light.distance;
  12329. if ( light instanceof THREE.AmbientLight ) {
  12330. if ( ! light.visible ) continue;
  12331. if ( _this.gammaInput ) {
  12332. r += color.r * color.r;
  12333. g += color.g * color.g;
  12334. b += color.b * color.b;
  12335. } else {
  12336. r += color.r;
  12337. g += color.g;
  12338. b += color.b;
  12339. }
  12340. } else if ( light instanceof THREE.DirectionalLight ) {
  12341. dirCount += 1;
  12342. if ( ! light.visible ) continue;
  12343. _direction.getPositionFromMatrix( light.matrixWorld );
  12344. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  12345. _direction.sub( _vector3 );
  12346. _direction.normalize();
  12347. // skip lights with undefined direction
  12348. // these create troubles in OpenGL (making pixel black)
  12349. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  12350. dirOffset = dirLength * 3;
  12351. dirPositions[ dirOffset ] = _direction.x;
  12352. dirPositions[ dirOffset + 1 ] = _direction.y;
  12353. dirPositions[ dirOffset + 2 ] = _direction.z;
  12354. if ( _this.gammaInput ) {
  12355. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  12356. } else {
  12357. setColorLinear( dirColors, dirOffset, color, intensity );
  12358. }
  12359. dirLength += 1;
  12360. } else if ( light instanceof THREE.PointLight ) {
  12361. pointCount += 1;
  12362. if ( ! light.visible ) continue;
  12363. pointOffset = pointLength * 3;
  12364. if ( _this.gammaInput ) {
  12365. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  12366. } else {
  12367. setColorLinear( pointColors, pointOffset, color, intensity );
  12368. }
  12369. _vector3.getPositionFromMatrix( light.matrixWorld );
  12370. pointPositions[ pointOffset ] = _vector3.x;
  12371. pointPositions[ pointOffset + 1 ] = _vector3.y;
  12372. pointPositions[ pointOffset + 2 ] = _vector3.z;
  12373. pointDistances[ pointLength ] = distance;
  12374. pointLength += 1;
  12375. } else if ( light instanceof THREE.SpotLight ) {
  12376. spotCount += 1;
  12377. if ( ! light.visible ) continue;
  12378. spotOffset = spotLength * 3;
  12379. if ( _this.gammaInput ) {
  12380. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  12381. } else {
  12382. setColorLinear( spotColors, spotOffset, color, intensity );
  12383. }
  12384. _vector3.getPositionFromMatrix( light.matrixWorld );
  12385. spotPositions[ spotOffset ] = _vector3.x;
  12386. spotPositions[ spotOffset + 1 ] = _vector3.y;
  12387. spotPositions[ spotOffset + 2 ] = _vector3.z;
  12388. spotDistances[ spotLength ] = distance;
  12389. _direction.copy( _vector3 );
  12390. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  12391. _direction.sub( _vector3 );
  12392. _direction.normalize();
  12393. spotDirections[ spotOffset ] = _direction.x;
  12394. spotDirections[ spotOffset + 1 ] = _direction.y;
  12395. spotDirections[ spotOffset + 2 ] = _direction.z;
  12396. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  12397. spotExponents[ spotLength ] = light.exponent;
  12398. spotLength += 1;
  12399. } else if ( light instanceof THREE.HemisphereLight ) {
  12400. hemiCount += 1;
  12401. if ( ! light.visible ) continue;
  12402. _direction.getPositionFromMatrix( light.matrixWorld );
  12403. _direction.normalize();
  12404. // skip lights with undefined direction
  12405. // these create troubles in OpenGL (making pixel black)
  12406. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  12407. hemiOffset = hemiLength * 3;
  12408. hemiPositions[ hemiOffset ] = _direction.x;
  12409. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  12410. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  12411. skyColor = light.color;
  12412. groundColor = light.groundColor;
  12413. if ( _this.gammaInput ) {
  12414. intensitySq = intensity * intensity;
  12415. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  12416. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  12417. } else {
  12418. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  12419. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  12420. }
  12421. hemiLength += 1;
  12422. }
  12423. }
  12424. // null eventual remains from removed lights
  12425. // (this is to avoid if in shader)
  12426. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  12427. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  12428. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  12429. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  12430. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  12431. zlights.directional.length = dirLength;
  12432. zlights.point.length = pointLength;
  12433. zlights.spot.length = spotLength;
  12434. zlights.hemi.length = hemiLength;
  12435. zlights.ambient[ 0 ] = r;
  12436. zlights.ambient[ 1 ] = g;
  12437. zlights.ambient[ 2 ] = b;
  12438. };
  12439. // Allocations
  12440. function allocateBones ( object ) {
  12441. if ( renderer.supportsBoneTextures && object && object.useVertexTexture ) {
  12442. return 1024;
  12443. } else {
  12444. // default for when object is not specified
  12445. // ( for example when prebuilding shader
  12446. // to be used with multiple objects )
  12447. //
  12448. // - leave some extra space for other uniforms
  12449. // - limit here is ANGLE's 254 max uniform vectors
  12450. // (up to 54 should be safe)
  12451. var nVertexUniforms = renderer.maxVertexUniformVectors
  12452. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  12453. var maxBones = nVertexMatrices;
  12454. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  12455. maxBones = Math.min( object.bones.length, maxBones );
  12456. if ( maxBones < object.bones.length ) {
  12457. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  12458. }
  12459. }
  12460. return maxBones;
  12461. }
  12462. };
  12463. function allocateLights ( lights ) {
  12464. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  12465. dirLights = pointLights = spotLights = hemiLights = 0;
  12466. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12467. light = lights[ l ];
  12468. if ( light.onlyShadow ) continue;
  12469. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  12470. if ( light instanceof THREE.PointLight ) pointLights ++;
  12471. if ( light instanceof THREE.SpotLight ) spotLights ++;
  12472. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  12473. }
  12474. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  12475. };
  12476. function allocateShadows ( lights ) {
  12477. var l, ll, light, maxShadows = 0;
  12478. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  12479. light = lights[ l ];
  12480. if ( ! light.castShadow ) continue;
  12481. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  12482. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  12483. }
  12484. return maxShadows;
  12485. };
  12486. // default plugins (order is important)
  12487. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  12488. this.addPrePlugin( this.shadowMapPlugin );
  12489. this.addPostPlugin( new THREE.SpritePlugin() );
  12490. this.addPostPlugin( new THREE.LensFlarePlugin() );
  12491. };
  12492. /*global THREE:false */
  12493. THREE.WebGLRenderer.LowLevelRenderer = function ( parameters ) {
  12494. parameters = parameters || {};
  12495. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  12496. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  12497. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  12498. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  12499. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  12500. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  12501. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  12502. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  12503. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0,
  12504. _autoScaleCubemaps = true;
  12505. this.devicePixelRatio = parameters.devicePixelRatio !== undefined ? parameters.devicePixelRatio : window.devicePixelRatio !== undefined ? window.devicePixelRatio : 1;
  12506. var _currentWidth = 0, _currentHeight = 0;
  12507. var _gl;
  12508. var _glExtensionTextureFloat;
  12509. var _glExtensionStandardDerivatives;
  12510. var _glExtensionTextureFilterAnisotropic;
  12511. var _glExtensionCompressedTextureS3TC;
  12512. initGL();
  12513. setDefaultGLState();
  12514. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  12515. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  12516. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  12517. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  12518. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  12519. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  12520. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  12521. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  12522. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  12523. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  12524. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  12525. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  12526. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  12527. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  12528. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  12529. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  12530. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  12531. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  12532. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  12533. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  12534. // clamp precision to maximum available
  12535. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  12536. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  12537. if ( _precision === "highp" && ! highpAvailable ) {
  12538. if ( mediumpAvailable ) {
  12539. _precision = "mediump";
  12540. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  12541. } else {
  12542. _precision = "lowp";
  12543. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  12544. }
  12545. }
  12546. if ( _precision === "mediump" && ! mediumpAvailable ) {
  12547. _precision = "lowp";
  12548. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  12549. }
  12550. var _enabledAttributes = {},
  12551. _oldBlending,
  12552. _oldBlendEquation,
  12553. _oldBlendSrc,
  12554. _oldBlendDst,
  12555. _oldDoubleSided = -1,
  12556. _oldFlipSided = -1,
  12557. _oldDepthTest = -1,
  12558. _oldDepthWrite = -1,
  12559. _oldLineWidth = -1,
  12560. _viewportX = 0,
  12561. _viewportY = 0,
  12562. _viewportWidth = 0,
  12563. _viewportHeight = 0,
  12564. // GL state cache
  12565. _oldPolygonOffset = null,
  12566. _oldPolygonOffsetFactor = null,
  12567. _oldPolygonOffsetUnits = null,
  12568. _currentFramebuffer = null;
  12569. function initGL () {
  12570. try {
  12571. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  12572. throw 'Error creating WebGL context.';
  12573. }
  12574. } catch ( error ) {
  12575. console.error( error );
  12576. }
  12577. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  12578. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  12579. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  12580. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  12581. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  12582. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  12583. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  12584. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  12585. if ( ! _glExtensionTextureFloat ) {
  12586. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  12587. }
  12588. if ( ! _glExtensionStandardDerivatives ) {
  12589. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  12590. }
  12591. if ( ! _glExtensionTextureFilterAnisotropic ) {
  12592. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  12593. }
  12594. if ( ! _glExtensionCompressedTextureS3TC ) {
  12595. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  12596. }
  12597. if ( _gl.getShaderPrecisionFormat === undefined ) {
  12598. _gl.getShaderPrecisionFormat = function() {
  12599. return {
  12600. "rangeMin" : 1,
  12601. "rangeMax" : 1,
  12602. "precision" : 1
  12603. };
  12604. }
  12605. }
  12606. }
  12607. function setDefaultGLState () {
  12608. _gl.clearColor( 0, 0, 0, 1 );
  12609. _gl.clearDepth( 1 );
  12610. _gl.clearStencil( 0 );
  12611. _gl.enable( _gl.DEPTH_TEST );
  12612. _gl.depthFunc( _gl.LEQUAL );
  12613. _gl.frontFace( _gl.CCW );
  12614. _gl.cullFace( _gl.BACK );
  12615. _gl.enable( _gl.CULL_FACE );
  12616. _gl.enable( _gl.BLEND );
  12617. _gl.blendEquation( _gl.FUNC_ADD );
  12618. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  12619. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12620. }
  12621. // Fallback filters for non-power-of-2 textures
  12622. function filterFallback ( f ) {
  12623. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  12624. return _gl.NEAREST;
  12625. }
  12626. return _gl.LINEAR;
  12627. }
  12628. function getContext() {
  12629. return _gl;
  12630. }
  12631. function getDomElement(){
  12632. return _canvas;
  12633. }
  12634. function getPrecision() {
  12635. return _precision;
  12636. }
  12637. function getCurrentWidth(){
  12638. return _currentWidth;
  12639. }
  12640. function getCurrentHeight(){
  12641. return _currentHeight;
  12642. }
  12643. function supportsVertexTextures() {
  12644. return _supportsVertexTextures;
  12645. }
  12646. function supportsFloatTextures() {
  12647. return _glExtensionTextureFloat;
  12648. }
  12649. function supportsStandardDerivatives() {
  12650. return _glExtensionStandardDerivatives;
  12651. }
  12652. function supportsCompressedTextureS3TC() {
  12653. return _glExtensionCompressedTextureS3TC;
  12654. }
  12655. function getMaxAnisotropy() {
  12656. return _maxAnisotropy;
  12657. }
  12658. function setSize( width, height ) {
  12659. _canvas.width = width;
  12660. _canvas.height = height;
  12661. setViewport( 0, 0, _canvas.width, _canvas.height );
  12662. }
  12663. function setViewport( x, y, width, height ) {
  12664. _viewportX = x !== undefined ? x : 0;
  12665. _viewportY = y !== undefined ? y : 0;
  12666. _viewportWidth = width !== undefined ? width : _canvas.width;
  12667. _viewportHeight = height !== undefined ? height : _canvas.height;
  12668. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  12669. }
  12670. function setScissor( x, y, width, height ) {
  12671. _gl.scissor( x, y, width, height );
  12672. }
  12673. function enableScissorTest( enable ) {
  12674. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  12675. }
  12676. // Clearing
  12677. function setClearColorHex( hex, alpha ) {
  12678. _clearColor.setHex( hex );
  12679. _clearAlpha = alpha;
  12680. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12681. }
  12682. function setClearColor( color, alpha ) {
  12683. _clearColor.copy( color );
  12684. _clearAlpha = alpha;
  12685. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12686. }
  12687. function getClearColor() {
  12688. return _clearColor;
  12689. }
  12690. function getClearAlpha() {
  12691. return _clearAlpha;
  12692. }
  12693. function clear( color, depth, stencil ) {
  12694. var bits = 0;
  12695. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  12696. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  12697. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  12698. _gl.clear( bits );
  12699. }
  12700. function clearTarget( renderTarget, color, depth, stencil ) {
  12701. setRenderTarget( renderTarget );
  12702. clear( color, depth, stencil );
  12703. }
  12704. function deleteBuffer(buffer){
  12705. _gl.deleteBuffer(buffer);
  12706. }
  12707. function deleteTexture(texture){
  12708. _gl.deleteTexture( texture );
  12709. }
  12710. function deleteFramebuffer(Framebuffer){
  12711. _gl.deleteFramebuffer(Framebuffer);
  12712. }
  12713. function deleteRenderbuffer(RenderBuffer){
  12714. _gl.deleteRenderbuffer(RenderBuffer);
  12715. }
  12716. function deleteProgram(RenderBuffer){
  12717. _gl.deleteProgram(RenderBuffer);
  12718. }
  12719. function createBuffer(){
  12720. return _gl.createBuffer();
  12721. }
  12722. function setStaticArrayBuffer(buffer,data){
  12723. bindArrayBuffer( buffer );
  12724. _gl.bufferData( _gl.ARRAY_BUFFER, data, _gl.STATIC_DRAW );
  12725. }
  12726. function setStaticIndexBuffer(buffer,data){
  12727. bindElementArrayBuffer( buffer );
  12728. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, data, _gl.STATIC_DRAW );
  12729. }
  12730. function setDynamicArrayBuffer(buffer,data){
  12731. bindArrayBuffer( buffer );
  12732. _gl.bufferData( _gl.ARRAY_BUFFER, data, _gl.DYNAMIC_DRAW );
  12733. }
  12734. function setDynamicIndexBuffer(buffer,data){
  12735. bindElementArrayBuffer( buffer );
  12736. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, data, _gl.DYNAMIC_DRAW );
  12737. }
  12738. function drawTriangles(count){
  12739. _gl.drawArrays( _gl.TRIANGLES, 0, count );
  12740. }
  12741. function drawTriangleStrip(count){
  12742. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, count );
  12743. }
  12744. function drawLines(count){
  12745. _gl.drawArrays( _gl.LINES, 0, count );
  12746. }
  12747. function drawLineStrip(count){
  12748. _gl.drawArrays( _gl.LINE_STRIP, 0, count );
  12749. }
  12750. function drawPoints(count){
  12751. _gl.drawArrays( _gl.POINTS, 0, count );
  12752. }
  12753. function drawTriangleElements(buffer,count,offset){
  12754. bindElementArrayBuffer( buffer );
  12755. _gl.drawElements( _gl.TRIANGLES, count, _gl.UNSIGNED_SHORT, offset ); // 2 bytes per Uint16
  12756. }
  12757. function drawLineElements(buffer,count,offset){
  12758. bindElementArrayBuffer( buffer );
  12759. _gl.drawElements( _gl.LINES, count, _gl.UNSIGNED_SHORT, offset ); // 2 bytes per Uint16
  12760. }
  12761. var _boundBuffer;
  12762. function bindArrayBuffer(buffer){
  12763. if (_boundBuffer != buffer){
  12764. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12765. _boundBuffer = buffer;
  12766. }
  12767. }
  12768. function bindElementArrayBuffer(buffer){
  12769. if (_boundBuffer != buffer){
  12770. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, buffer );
  12771. _boundBuffer = buffer;
  12772. }
  12773. }
  12774. function enableAttribute( attribute ) {
  12775. if ( ! _enabledAttributes[ attribute ] ) {
  12776. _gl.enableVertexAttribArray( attribute );
  12777. _enabledAttributes[ attribute ] = true;
  12778. }
  12779. }
  12780. function disableAttributes() {
  12781. for ( var attribute in _enabledAttributes ) {
  12782. if ( _enabledAttributes[ attribute ] ) {
  12783. _gl.disableVertexAttribArray( attribute );
  12784. _enabledAttributes[ attribute ] = false;
  12785. }
  12786. }
  12787. }
  12788. function getAttribLocation( program, id ){
  12789. return _gl.getAttribLocation( program, id );
  12790. }
  12791. function setFloatAttribute(index,buffer,size,offset){
  12792. bindArrayBuffer( buffer );
  12793. enableAttribute( index );
  12794. _gl.vertexAttribPointer( index, size, _gl.FLOAT, false, 0, offset );
  12795. }
  12796. function getUniformLocation( program, id ){
  12797. return _gl.getUniformLocation( program, id );
  12798. }
  12799. function uniform1i(uniform,value){
  12800. _gl.uniform1i( uniform, value );
  12801. }
  12802. function uniform1f(uniform,value){
  12803. _gl.uniform1f( uniform, value );
  12804. }
  12805. function uniform2f(uniform,value1, value2){
  12806. _gl.uniform2f( uniform, value1, value2 );
  12807. }
  12808. function uniform3f(uniform, value1, value2, value3){
  12809. _gl.uniform3f( uniform, value1, value2, value3 );
  12810. }
  12811. function uniform4f(uniform, value1, value2, value3, value4){
  12812. _gl.uniform4f( uniform, value1, value2, value3, value4);
  12813. }
  12814. function uniform1iv(uniform,value){
  12815. _gl.uniform1iv( uniform, value );
  12816. }
  12817. function uniform2iv(uniform,value){
  12818. _gl.uniform2iv( uniform, value );
  12819. }
  12820. function uniform3iv(uniform,value){
  12821. _gl.uniform3iv( uniform, value );
  12822. }
  12823. function uniform1fv(uniform,value){
  12824. _gl.uniform1fv( uniform, value );
  12825. }
  12826. function uniform2fv(uniform,value){
  12827. _gl.uniform2fv( uniform, value );
  12828. }
  12829. function uniform3fv(uniform,value){
  12830. _gl.uniform3fv( uniform, value );
  12831. }
  12832. function uniform4fv(uniform,value){
  12833. _gl.uniform3fv( uniform, value );
  12834. }
  12835. function uniformMatrix3fv(location,value){
  12836. _gl.uniformMatrix3fv( location, false, value );
  12837. }
  12838. function uniformMatrix4fv(location,value){
  12839. _gl.uniformMatrix4fv( location, false, value );
  12840. }
  12841. function useProgram(program){
  12842. _gl.useProgram( program );
  12843. }
  12844. function setFaceCulling( cullFace, frontFaceDirection ) {
  12845. if ( cullFace === THREE.CullFaceNone ) {
  12846. _gl.disable( _gl.CULL_FACE );
  12847. } else {
  12848. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  12849. _gl.frontFace( _gl.CW );
  12850. } else {
  12851. _gl.frontFace( _gl.CCW );
  12852. }
  12853. if ( cullFace === THREE.CullFaceBack ) {
  12854. _gl.cullFace( _gl.BACK );
  12855. } else if ( cullFace === THREE.CullFaceFront ) {
  12856. _gl.cullFace( _gl.FRONT );
  12857. } else {
  12858. _gl.cullFace( _gl.FRONT_AND_BACK );
  12859. }
  12860. _gl.enable( _gl.CULL_FACE );
  12861. }
  12862. }
  12863. function setMaterialFaces( material ) {
  12864. var doubleSided = material.side === THREE.DoubleSide;
  12865. var flipSided = material.side === THREE.BackSide;
  12866. if ( _oldDoubleSided !== doubleSided ) {
  12867. if ( doubleSided ) {
  12868. _gl.disable( _gl.CULL_FACE );
  12869. } else {
  12870. _gl.enable( _gl.CULL_FACE );
  12871. }
  12872. _oldDoubleSided = doubleSided;
  12873. }
  12874. if ( _oldFlipSided !== flipSided ) {
  12875. if ( flipSided ) {
  12876. _gl.frontFace( _gl.CW );
  12877. } else {
  12878. _gl.frontFace( _gl.CCW );
  12879. }
  12880. _oldFlipSided = flipSided;
  12881. }
  12882. }
  12883. function setPolygonOffset ( polygonoffset, factor, units ) {
  12884. if ( _oldPolygonOffset !== polygonoffset ) {
  12885. if ( polygonoffset ) {
  12886. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  12887. } else {
  12888. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  12889. }
  12890. _oldPolygonOffset = polygonoffset;
  12891. }
  12892. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  12893. _gl.polygonOffset( factor, units );
  12894. _oldPolygonOffsetFactor = factor;
  12895. _oldPolygonOffsetUnits = units;
  12896. }
  12897. }
  12898. function setBlending( blending, blendEquation, blendSrc, blendDst ) {
  12899. if ( blending !== _oldBlending ) {
  12900. if ( blending === THREE.NoBlending ) {
  12901. _gl.disable( _gl.BLEND );
  12902. } else if ( blending === THREE.AdditiveBlending ) {
  12903. _gl.enable( _gl.BLEND );
  12904. _gl.blendEquation( _gl.FUNC_ADD );
  12905. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  12906. } else if ( blending === THREE.SubtractiveBlending ) {
  12907. // TODO: Find blendFuncSeparate() combination
  12908. _gl.enable( _gl.BLEND );
  12909. _gl.blendEquation( _gl.FUNC_ADD );
  12910. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  12911. } else if ( blending === THREE.MultiplyBlending ) {
  12912. // TODO: Find blendFuncSeparate() combination
  12913. _gl.enable( _gl.BLEND );
  12914. _gl.blendEquation( _gl.FUNC_ADD );
  12915. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  12916. } else if ( blending === THREE.CustomBlending ) {
  12917. _gl.enable( _gl.BLEND );
  12918. } else {
  12919. _gl.enable( _gl.BLEND );
  12920. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  12921. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  12922. }
  12923. _oldBlending = blending;
  12924. }
  12925. if ( blending === THREE.CustomBlending ) {
  12926. if ( blendEquation !== _oldBlendEquation ) {
  12927. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  12928. _oldBlendEquation = blendEquation;
  12929. }
  12930. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  12931. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  12932. _oldBlendSrc = blendSrc;
  12933. _oldBlendDst = blendDst;
  12934. }
  12935. } else {
  12936. _oldBlendEquation = null;
  12937. _oldBlendSrc = null;
  12938. _oldBlendDst = null;
  12939. }
  12940. }
  12941. function setDepthTest( depthTest ) {
  12942. if ( _oldDepthTest !== depthTest ) {
  12943. if ( depthTest ) {
  12944. _gl.enable( _gl.DEPTH_TEST );
  12945. } else {
  12946. _gl.disable( _gl.DEPTH_TEST );
  12947. }
  12948. _oldDepthTest = depthTest;
  12949. }
  12950. }
  12951. function setDepthWrite( depthWrite ) {
  12952. if ( _oldDepthWrite !== depthWrite ) {
  12953. _gl.depthMask( depthWrite );
  12954. _oldDepthWrite = depthWrite;
  12955. }
  12956. }
  12957. function setTexture( texture, slot ) {
  12958. if ( texture.needsUpdate ) {
  12959. if ( ! texture.__webglInit ) {
  12960. texture.__webglInit = true;
  12961. //texture.addEventListener( 'dispose', onTextureDispose );
  12962. texture.__webglTexture = _gl.createTexture();
  12963. //_this.info.memory.textures ++;
  12964. }
  12965. _gl.activeTexture( _gl.TEXTURE0 + slot );
  12966. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  12967. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  12968. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  12969. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  12970. var image = texture.image,
  12971. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  12972. glFormat = paramThreeToGL( texture.format ),
  12973. glType = paramThreeToGL( texture.type );
  12974. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  12975. var mipmap, mipmaps = texture.mipmaps;
  12976. if ( texture instanceof THREE.DataTexture ) {
  12977. // use manually created mipmaps if available
  12978. // if there are no manual mipmaps
  12979. // set 0 level mipmap and then use GL to generate other mipmap levels
  12980. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  12981. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  12982. mipmap = mipmaps[ i ];
  12983. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  12984. }
  12985. texture.generateMipmaps = false;
  12986. } else {
  12987. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  12988. }
  12989. } else if ( texture instanceof THREE.CompressedTexture ) {
  12990. // compressed textures can only use manually created mipmaps
  12991. // WebGL can't generate mipmaps for DDS textures
  12992. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  12993. mipmap = mipmaps[ i ];
  12994. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  12995. }
  12996. } else { // regular Texture (image, video, canvas)
  12997. // use manually created mipmaps if available
  12998. // if there are no manual mipmaps
  12999. // set 0 level mipmap and then use GL to generate other mipmap levels
  13000. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  13001. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13002. mipmap = mipmaps[ i ];
  13003. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  13004. }
  13005. texture.generateMipmaps = false;
  13006. } else {
  13007. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  13008. }
  13009. }
  13010. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13011. texture.needsUpdate = false;
  13012. if ( texture.onUpdate ) texture.onUpdate();
  13013. } else {
  13014. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13015. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13016. }
  13017. }
  13018. function setCubeTexture ( texture, slot ) {
  13019. if ( texture.image.length === 6 ) {
  13020. if ( texture.needsUpdate ) {
  13021. if ( ! texture.image.__webglTextureCube ) {
  13022. texture.image.__webglTextureCube = _gl.createTexture();
  13023. }
  13024. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13025. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13026. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13027. var isCompressed = texture instanceof THREE.CompressedTexture;
  13028. var cubeImage = [];
  13029. for ( var i = 0; i < 6; i ++ ) {
  13030. if ( _autoScaleCubemaps && ! isCompressed ) {
  13031. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  13032. } else {
  13033. cubeImage[ i ] = texture.image[ i ];
  13034. }
  13035. }
  13036. var image = cubeImage[ 0 ],
  13037. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  13038. glFormat = paramThreeToGL( texture.format ),
  13039. glType = paramThreeToGL( texture.type );
  13040. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  13041. for ( var i = 0; i < 6; i ++ ) {
  13042. if ( isCompressed ) {
  13043. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  13044. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  13045. mipmap = mipmaps[ j ];
  13046. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13047. }
  13048. } else {
  13049. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  13050. }
  13051. }
  13052. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  13053. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13054. }
  13055. texture.needsUpdate = false;
  13056. if ( texture.onUpdate ) texture.onUpdate();
  13057. } else {
  13058. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13059. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13060. }
  13061. }
  13062. }
  13063. // Textures
  13064. function isPowerOfTwo ( value ) {
  13065. return ( value & ( value - 1 ) ) === 0;
  13066. }
  13067. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  13068. if ( isImagePowerOfTwo ) {
  13069. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  13070. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  13071. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  13072. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  13073. } else {
  13074. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  13075. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  13076. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  13077. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  13078. }
  13079. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  13080. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  13081. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  13082. texture.__oldAnisotropy = texture.anisotropy;
  13083. }
  13084. }
  13085. }
  13086. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  13087. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13088. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  13089. }
  13090. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  13091. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  13092. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13093. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  13094. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13095. /* For some reason this is not working. Defaulting to RGBA4.
  13096. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13097. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  13098. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13099. */
  13100. } else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13101. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  13102. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13103. } else {
  13104. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  13105. }
  13106. }
  13107. function setRenderTarget( renderTarget ) {
  13108. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  13109. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  13110. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  13111. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  13112. //renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  13113. renderTarget.__webglTexture = _gl.createTexture();
  13114. //_this.info.memory.textures ++;
  13115. // Setup texture, create render and frame buffers
  13116. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  13117. glFormat = paramThreeToGL( renderTarget.format ),
  13118. glType = paramThreeToGL( renderTarget.type );
  13119. if ( isCube ) {
  13120. renderTarget.__webglFramebuffer = [];
  13121. renderTarget.__webglRenderbuffer = [];
  13122. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13123. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  13124. for ( var i = 0; i < 6; i ++ ) {
  13125. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  13126. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  13127. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13128. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  13129. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  13130. }
  13131. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13132. } else {
  13133. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  13134. if ( renderTarget.shareDepthFrom ) {
  13135. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  13136. } else {
  13137. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  13138. }
  13139. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13140. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  13141. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13142. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  13143. if ( renderTarget.shareDepthFrom ) {
  13144. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13145. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  13146. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13147. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  13148. }
  13149. } else {
  13150. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  13151. }
  13152. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13153. }
  13154. // Release everything
  13155. if ( isCube ) {
  13156. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13157. } else {
  13158. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13159. }
  13160. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  13161. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  13162. }
  13163. var framebuffer, width, height, vx, vy;
  13164. if ( renderTarget ) {
  13165. if ( isCube ) {
  13166. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13167. } else {
  13168. framebuffer = renderTarget.__webglFramebuffer;
  13169. }
  13170. width = renderTarget.width;
  13171. height = renderTarget.height;
  13172. vx = 0;
  13173. vy = 0;
  13174. } else {
  13175. framebuffer = null;
  13176. width = _viewportWidth;
  13177. height = _viewportHeight;
  13178. vx = _viewportX;
  13179. vy = _viewportY;
  13180. }
  13181. if ( framebuffer !== _currentFramebuffer ) {
  13182. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13183. _gl.viewport( vx, vy, width, height );
  13184. _currentFramebuffer = framebuffer;
  13185. }
  13186. _currentWidth = width;
  13187. _currentHeight = height;
  13188. }
  13189. function clampToMaxSize ( image, maxSize ) {
  13190. if ( image.width <= maxSize && image.height <= maxSize ) {
  13191. return image;
  13192. }
  13193. // Warning: Scaling through the canvas will only work with images that use
  13194. // premultiplied alpha.
  13195. var maxDimension = Math.max( image.width, image.height );
  13196. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  13197. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  13198. var canvas = document.createElement( 'canvas' );
  13199. canvas.width = newWidth;
  13200. canvas.height = newHeight;
  13201. var ctx = canvas.getContext( "2d" );
  13202. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  13203. return canvas;
  13204. }
  13205. function updateRenderTargetMipmap ( renderTarget ) {
  13206. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  13207. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13208. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13209. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13210. } else {
  13211. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13212. _gl.generateMipmap( _gl.TEXTURE_2D );
  13213. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13214. }
  13215. }
  13216. function setCubeTextureDynamic ( texture, slot ) {
  13217. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13218. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  13219. }
  13220. // Map three.js constants to WebGL constants
  13221. function paramThreeToGL ( p ) {
  13222. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  13223. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13224. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13225. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  13226. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13227. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13228. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  13229. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13230. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13231. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13232. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13233. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13234. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13235. if ( p === THREE.ByteType ) return _gl.BYTE;
  13236. if ( p === THREE.ShortType ) return _gl.SHORT;
  13237. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13238. if ( p === THREE.IntType ) return _gl.INT;
  13239. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  13240. if ( p === THREE.FloatType ) return _gl.FLOAT;
  13241. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  13242. if ( p === THREE.RGBFormat ) return _gl.RGB;
  13243. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  13244. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  13245. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13246. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  13247. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13248. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13249. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  13250. if ( p === THREE.OneFactor ) return _gl.ONE;
  13251. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  13252. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13253. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13254. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13255. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  13256. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13257. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  13258. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13259. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13260. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  13261. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13262. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13263. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13264. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13265. }
  13266. return 0;
  13267. }
  13268. function compileShader(vertexShader, fragmentShader){
  13269. var program = _gl.createProgram();
  13270. var glFragmentShader = getShader( "fragment", fragmentShader );
  13271. var glVertexShader = getShader( "vertex", vertexShader );
  13272. _gl.attachShader( program, glVertexShader );
  13273. _gl.attachShader( program, glFragmentShader );
  13274. _gl.linkProgram( program );
  13275. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  13276. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  13277. }
  13278. // clean up
  13279. _gl.deleteShader( glFragmentShader );
  13280. _gl.deleteShader( glVertexShader );
  13281. return program;
  13282. }
  13283. function resetState(){
  13284. _oldBlending = -1;
  13285. _oldDepthTest = -1;
  13286. _oldDepthWrite = -1;
  13287. _oldDoubleSided = -1;
  13288. _oldFlipSided = -1;
  13289. }
  13290. function getShader ( type, string ) {
  13291. var shader;
  13292. if ( type === "fragment" ) {
  13293. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  13294. } else if ( type === "vertex" ) {
  13295. shader = _gl.createShader( _gl.VERTEX_SHADER );
  13296. }
  13297. _gl.shaderSource( shader, string );
  13298. _gl.compileShader( shader );
  13299. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  13300. console.error( _gl.getShaderInfoLog( shader ) );
  13301. console.error( addLineNumbers( string ) );
  13302. return null;
  13303. }
  13304. return shader;
  13305. }
  13306. function addLineNumbers ( string ) {
  13307. var chunks = string.split( "\n" );
  13308. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  13309. // Chrome reports shader errors on lines
  13310. // starting counting from 1
  13311. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  13312. }
  13313. return chunks.join( "\n" );
  13314. }
  13315. function setLineWidth ( width ) {
  13316. if ( width !== _oldLineWidth ) {
  13317. _gl.lineWidth( width );
  13318. _oldLineWidth = width;
  13319. }
  13320. }
  13321. return {
  13322. context: _gl,
  13323. autoScaleCubemaps: _autoScaleCubemaps,
  13324. supportsBoneTextures: _supportsBoneTextures,
  13325. precision: _precision,
  13326. maxVertexUniformVectors: _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS ),
  13327. // Methods
  13328. getContext: getContext,
  13329. getDomElement: getDomElement,
  13330. getPrecision: getPrecision,
  13331. getCurrentWidth: getCurrentWidth,
  13332. getCurrentHeight: getCurrentHeight,
  13333. supportsVertexTextures: supportsVertexTextures,
  13334. supportsFloatTextures: supportsFloatTextures,
  13335. supportsStandardDerivatives: supportsStandardDerivatives,
  13336. supportsCompressedTextureS3TC: supportsCompressedTextureS3TC,
  13337. getMaxAnisotropy: getMaxAnisotropy,
  13338. setRenderTarget: setRenderTarget,
  13339. setSize: setSize,
  13340. setViewport: setViewport,
  13341. setScissor: setScissor,
  13342. enableScissorTest: enableScissorTest,
  13343. setClearColorHex: setClearColorHex,
  13344. setClearColor: setClearColor,
  13345. getClearColor: getClearColor,
  13346. getClearAlpha: getClearAlpha,
  13347. clear: clear,
  13348. clearTarget: clearTarget,
  13349. deleteBuffer: deleteBuffer,
  13350. deleteTexture: deleteTexture,
  13351. deleteFramebuffer: deleteFramebuffer,
  13352. deleteRenderbuffer: deleteRenderbuffer,
  13353. deleteProgram: deleteProgram,
  13354. createBuffer: createBuffer,
  13355. setStaticArrayBuffer: setStaticArrayBuffer,
  13356. setStaticIndexBuffer: setStaticIndexBuffer,
  13357. setDynamicArrayBuffer: setDynamicArrayBuffer,
  13358. setDynamicIndexBuffer: setDynamicIndexBuffer,
  13359. drawTriangles: drawTriangles,
  13360. drawTriangleStrip: drawTriangleStrip,
  13361. drawLines: drawLines,
  13362. drawLineStrip: drawLineStrip,
  13363. drawPoints: drawPoints,
  13364. drawTriangleElements: drawTriangleElements,
  13365. drawLineElements: drawLineElements,
  13366. bindArrayBuffer: bindArrayBuffer,
  13367. bindElementArrayBuffer: bindElementArrayBuffer,
  13368. enableAttribute: enableAttribute,
  13369. disableAttributes: disableAttributes,
  13370. getAttribLocation: getAttribLocation,
  13371. setFloatAttribute: setFloatAttribute,
  13372. getUniformLocation: getUniformLocation,
  13373. uniform1i: uniform1i,
  13374. uniform1f: uniform1f,
  13375. uniform2f: uniform2f,
  13376. uniform3f: uniform3f,
  13377. uniform4f: uniform4f,
  13378. uniform1iv: uniform1iv,
  13379. uniform2iv: uniform2iv,
  13380. uniform3iv: uniform3iv,
  13381. uniform1fv: uniform1fv,
  13382. uniform2fv: uniform2fv,
  13383. uniform3fv: uniform3fv,
  13384. uniform4fv: uniform4fv,
  13385. uniformMatrix3fv: uniformMatrix3fv,
  13386. uniformMatrix4fv: uniformMatrix4fv,
  13387. useProgram: useProgram,
  13388. compileShader: compileShader,
  13389. setFaceCulling: setFaceCulling,
  13390. setMaterialFaces: setMaterialFaces,
  13391. setPolygonOffset: setPolygonOffset,
  13392. setBlending: setBlending,
  13393. setDepthTest: setDepthTest,
  13394. setDepthWrite: setDepthWrite,
  13395. setTexture: setTexture,
  13396. setCubeTexture: setCubeTexture,
  13397. updateRenderTargetMipmap: updateRenderTargetMipmap,
  13398. setCubeTextureDynamic: setCubeTextureDynamic,
  13399. paramThreeToGL: paramThreeToGL,
  13400. setLineWidth: setLineWidth,
  13401. resetState: resetState
  13402. }
  13403. };
  13404. THREE.WebGLRenderer.ShaderBuilder = function ( renderer, info ) {
  13405. this.renderer = renderer;
  13406. this.info = info;
  13407. this.programs = [],
  13408. this.programs_counter = 0;
  13409. };
  13410. THREE.extend( THREE.WebGLRenderer.ShaderBuilder.prototype, {
  13411. buildProgram: function ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  13412. var renderer = this.renderer;
  13413. var p, pl, d, program, code;
  13414. var chunks = [];
  13415. // Generate code
  13416. if ( shaderID ) {
  13417. chunks.push( shaderID );
  13418. } else {
  13419. chunks.push( fragmentShader );
  13420. chunks.push( vertexShader );
  13421. }
  13422. for ( d in defines ) {
  13423. chunks.push( d );
  13424. chunks.push( defines[ d ] );
  13425. }
  13426. for ( p in parameters ) {
  13427. chunks.push( p );
  13428. chunks.push( parameters[ p ] );
  13429. }
  13430. code = chunks.join();
  13431. // Check if code has been already compiled
  13432. for ( p = 0, pl = this.programs.length; p < pl; p ++ ) {
  13433. var programInfo = this.programs[ p ];
  13434. if ( programInfo.code === code ) {
  13435. //console.log( "Code already compiled." /*: \n\n" + code*/ );
  13436. programInfo.usedTimes ++;
  13437. return programInfo.program;
  13438. }
  13439. }
  13440. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  13441. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  13442. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  13443. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  13444. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  13445. }
  13446. //console.log( "building new program " );
  13447. //
  13448. var customDefines = this.generateDefines( defines );
  13449. //
  13450. var prefix_vertex = [
  13451. "precision " + renderer.precision + " float;",
  13452. customDefines,
  13453. renderer.supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  13454. parameters.gammaInput ? "#define GAMMA_INPUT" : "",
  13455. parameters.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13456. parameters.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13457. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13458. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13459. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13460. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13461. "#define MAX_SHADOWS " + parameters.maxShadows,
  13462. "#define MAX_BONES " + parameters.maxBones,
  13463. parameters.map ? "#define USE_MAP" : "",
  13464. parameters.envMap ? "#define USE_ENVMAP" : "",
  13465. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13466. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13467. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13468. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13469. parameters.vertexColors ? "#define USE_COLOR" : "",
  13470. parameters.skinning ? "#define USE_SKINNING" : "",
  13471. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  13472. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  13473. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  13474. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  13475. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  13476. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13477. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13478. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13479. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13480. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13481. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  13482. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13483. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13484. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  13485. "uniform mat4 modelMatrix;",
  13486. "uniform mat4 modelViewMatrix;",
  13487. "uniform mat4 projectionMatrix;",
  13488. "uniform mat4 viewMatrix;",
  13489. "uniform mat3 normalMatrix;",
  13490. "uniform vec3 cameraPosition;",
  13491. "attribute vec3 position;",
  13492. "attribute vec3 normal;",
  13493. "attribute vec2 uv;",
  13494. "attribute vec2 uv2;",
  13495. "#ifdef USE_COLOR",
  13496. "attribute vec3 color;",
  13497. "#endif",
  13498. "#ifdef USE_MORPHTARGETS",
  13499. "attribute vec3 morphTarget0;",
  13500. "attribute vec3 morphTarget1;",
  13501. "attribute vec3 morphTarget2;",
  13502. "attribute vec3 morphTarget3;",
  13503. "#ifdef USE_MORPHNORMALS",
  13504. "attribute vec3 morphNormal0;",
  13505. "attribute vec3 morphNormal1;",
  13506. "attribute vec3 morphNormal2;",
  13507. "attribute vec3 morphNormal3;",
  13508. "#else",
  13509. "attribute vec3 morphTarget4;",
  13510. "attribute vec3 morphTarget5;",
  13511. "attribute vec3 morphTarget6;",
  13512. "attribute vec3 morphTarget7;",
  13513. "#endif",
  13514. "#endif",
  13515. "#ifdef USE_SKINNING",
  13516. "attribute vec4 skinIndex;",
  13517. "attribute vec4 skinWeight;",
  13518. "#endif",
  13519. ""
  13520. ].join("\n");
  13521. var prefix_fragment = [
  13522. "precision " + renderer.precision + " float;",
  13523. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  13524. customDefines,
  13525. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13526. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13527. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13528. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13529. "#define MAX_SHADOWS " + parameters.maxShadows,
  13530. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  13531. parameters.gammaInput ? "#define GAMMA_INPUT" : "",
  13532. parameters.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13533. parameters.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13534. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  13535. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  13536. parameters.map ? "#define USE_MAP" : "",
  13537. parameters.envMap ? "#define USE_ENVMAP" : "",
  13538. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13539. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13540. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13541. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13542. parameters.vertexColors ? "#define USE_COLOR" : "",
  13543. parameters.metal ? "#define METAL" : "",
  13544. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13545. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13546. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13547. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13548. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13549. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  13550. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13551. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13552. "uniform mat4 viewMatrix;",
  13553. "uniform vec3 cameraPosition;",
  13554. ""
  13555. ].join("\n");
  13556. program = renderer.compileShader(prefix_vertex + vertexShader, prefix_fragment + fragmentShader);
  13557. //console.log( prefix_fragment + fragmentShader );
  13558. //console.log( prefix_vertex + vertexShader );
  13559. program.uniforms = {};
  13560. program.attributes = {};
  13561. var identifiers, u, a, i;
  13562. // cache uniform locations
  13563. identifiers = [
  13564. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  13565. 'morphTargetInfluences'
  13566. ];
  13567. if ( parameters.useVertexTexture ) {
  13568. identifiers.push( 'boneTexture' );
  13569. } else {
  13570. identifiers.push( 'boneGlobalMatrices' );
  13571. }
  13572. for ( u in uniforms ) {
  13573. identifiers.push( u );
  13574. }
  13575. this.cacheUniformLocations( program, identifiers );
  13576. // cache attributes locations
  13577. identifiers = [
  13578. "position", "normal", "uv", "uv2", "tangent", "color",
  13579. "skinIndex", "skinWeight", "lineDistance"
  13580. ];
  13581. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  13582. identifiers.push( "morphTarget" + i );
  13583. }
  13584. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  13585. identifiers.push( "morphNormal" + i );
  13586. }
  13587. for ( a in attributes ) {
  13588. identifiers.push( a );
  13589. }
  13590. this.cacheAttributeLocations( program, identifiers );
  13591. program.id = this.programs_counter ++;
  13592. this.programs.push( { program: program, code: code, usedTimes: 1 } );
  13593. this.info.memory.programs = this.programs.length;
  13594. return program;
  13595. },
  13596. generateDefines: function ( defines ) {
  13597. var value, chunk, chunks = [];
  13598. for ( var d in defines ) {
  13599. value = defines[ d ];
  13600. if ( value === false ) continue;
  13601. chunk = "#define " + d + " " + value;
  13602. chunks.push( chunk );
  13603. }
  13604. return chunks.join( "\n" );
  13605. },
  13606. // Shader parameters cache
  13607. cacheUniformLocations: function ( program, identifiers ) {
  13608. var i, l, id, renderer = this.renderer;
  13609. for ( i = 0, l = identifiers.length; i < l; i ++ ) {
  13610. id = identifiers[ i ];
  13611. program.uniforms[ id ] = renderer.getUniformLocation( program, id );
  13612. }
  13613. },
  13614. cacheAttributeLocations: function ( program, identifiers ) {
  13615. var i, l, id, renderer = this.renderer;
  13616. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  13617. id = identifiers[ i ];
  13618. program.attributes[ id ] = renderer.getAttribLocation( program, id );
  13619. }
  13620. },
  13621. removeProgram: function ( program ) {
  13622. var i, il, programInfo;
  13623. var deleteProgram = false;
  13624. var programs = this.programs;
  13625. for ( i = 0, il = programs.length; i < il; i ++ ) {
  13626. programInfo = programs[ i ];
  13627. if ( programInfo.program === program ) {
  13628. programInfo.usedTimes --;
  13629. if ( programInfo.usedTimes === 0 ) {
  13630. deleteProgram = true;
  13631. }
  13632. break;
  13633. }
  13634. }
  13635. if ( deleteProgram === true ) {
  13636. // avoid using array.splice, this is costlier than creating new array from scratch
  13637. var newPrograms = [];
  13638. for ( i = 0, il = programs.length; i < il; i ++ ) {
  13639. programInfo = programs[ i ];
  13640. if ( programInfo.program !== program ) {
  13641. newPrograms.push( programInfo );
  13642. }
  13643. }
  13644. this.programs = newPrograms;
  13645. this.renderer.deleteProgram( program );
  13646. this.info.memory.programs --;
  13647. }
  13648. }
  13649. } );
  13650. THREE.WebGLRenderer.Object3DRenderer = function ( lowlevelrenderer, info ) {
  13651. this.renderer = lowlevelrenderer;
  13652. this.info = info;
  13653. };
  13654. THREE.extend( THREE.WebGLRenderer.Object3DRenderer.prototype, {
  13655. getBufferMaterial: function ( object, geometryGroup ) {
  13656. return object.material instanceof THREE.MeshFaceMaterial
  13657. ? object.material.materials[ geometryGroup.materialIndex ]
  13658. : object.material;
  13659. },
  13660. bufferGuessUVType: function ( material ) {
  13661. // material must use some texture to require uvs
  13662. if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  13663. return true;
  13664. }
  13665. return false;
  13666. },
  13667. bufferGuessNormalType: function ( material ) {
  13668. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  13669. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  13670. return false;
  13671. }
  13672. if ( this.materialNeedsSmoothNormals( material ) ) {
  13673. return THREE.SmoothShading;
  13674. } else {
  13675. return THREE.FlatShading;
  13676. }
  13677. },
  13678. materialNeedsSmoothNormals: function ( material ) {
  13679. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  13680. },
  13681. bufferGuessVertexColorType: function ( material ) {
  13682. if ( material.vertexColors ) {
  13683. return material.vertexColors;
  13684. }
  13685. return false;
  13686. },
  13687. initCustomAttributes: function ( geometry, object ) {
  13688. var nvertices = geometry.vertices.length;
  13689. var material = object.material;
  13690. if ( material.attributes ) {
  13691. if ( geometry.__webglCustomAttributesList === undefined ) {
  13692. geometry.__webglCustomAttributesList = [];
  13693. }
  13694. for ( var a in material.attributes ) {
  13695. var attribute = material.attributes[ a ];
  13696. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  13697. attribute.__webglInitialized = true;
  13698. var size = 1; // "f" and "i"
  13699. if ( attribute.type === "v2" ) size = 2;
  13700. else if ( attribute.type === "v3" ) size = 3;
  13701. else if ( attribute.type === "v4" ) size = 4;
  13702. else if ( attribute.type === "c" ) size = 3;
  13703. attribute.size = size;
  13704. attribute.array = new Float32Array( nvertices * size );
  13705. attribute.buffer = this.renderer.createBuffer();
  13706. attribute.buffer.belongsToAttribute = a;
  13707. attribute.needsUpdate = true;
  13708. }
  13709. geometry.__webglCustomAttributesList.push( attribute );
  13710. }
  13711. }
  13712. },
  13713. numericalSort: function ( a, b ) {
  13714. return b[ 0 ] - a[ 0 ];
  13715. }
  13716. } );
  13717. THREE.WebGLRenderer.MeshRenderer = function ( lowlevelrenderer, info ) {
  13718. THREE.WebGLRenderer.Object3DRenderer.call( this, lowlevelrenderer, info );
  13719. };
  13720. THREE.WebGLRenderer.MeshRenderer.prototype = Object.create( THREE.WebGLRenderer.Object3DRenderer.prototype );
  13721. THREE.extend( THREE.WebGLRenderer.MeshRenderer.prototype, {
  13722. createBuffers: function ( geometryGroup ) {
  13723. var renderer = this.renderer;
  13724. geometryGroup.__webglVertexBuffer = renderer.createBuffer();
  13725. geometryGroup.__webglNormalBuffer = renderer.createBuffer();
  13726. geometryGroup.__webglTangentBuffer = renderer.createBuffer();
  13727. geometryGroup.__webglColorBuffer = renderer.createBuffer();
  13728. geometryGroup.__webglUVBuffer = renderer.createBuffer();
  13729. geometryGroup.__webglUV2Buffer = renderer.createBuffer();
  13730. geometryGroup.__webglSkinIndicesBuffer = renderer.createBuffer();
  13731. geometryGroup.__webglSkinWeightsBuffer = renderer.createBuffer();
  13732. geometryGroup.__webglFaceBuffer = renderer.createBuffer();
  13733. geometryGroup.__webglLineBuffer = renderer.createBuffer();
  13734. var m, ml;
  13735. if ( geometryGroup.numMorphTargets ) {
  13736. geometryGroup.__webglMorphTargetsBuffers = [];
  13737. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  13738. geometryGroup.__webglMorphTargetsBuffers.push( renderer.createBuffer() );
  13739. }
  13740. }
  13741. if ( geometryGroup.numMorphNormals ) {
  13742. geometryGroup.__webglMorphNormalsBuffers = [];
  13743. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  13744. geometryGroup.__webglMorphNormalsBuffers.push( renderer.createBuffer() );
  13745. }
  13746. }
  13747. this.info.memory.geometries ++;
  13748. },
  13749. initBuffers: function ( geometryGroup, object ) {
  13750. var geometry = object.geometry,
  13751. faces3 = geometryGroup.faces3,
  13752. faces4 = geometryGroup.faces4,
  13753. nvertices = faces3.length * 3 + faces4.length * 4,
  13754. ntris = faces3.length * 1 + faces4.length * 2,
  13755. nlines = faces3.length * 3 + faces4.length * 4,
  13756. material = this.getBufferMaterial( object, geometryGroup ),
  13757. uvType = this.bufferGuessUVType( material ),
  13758. normalType = this.bufferGuessNormalType( material ),
  13759. vertexColorType = this.bufferGuessVertexColorType( material );
  13760. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  13761. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  13762. if ( normalType ) {
  13763. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  13764. }
  13765. if ( geometry.hasTangents ) {
  13766. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  13767. }
  13768. if ( vertexColorType ) {
  13769. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  13770. }
  13771. if ( uvType ) {
  13772. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  13773. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  13774. }
  13775. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  13776. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  13777. }
  13778. }
  13779. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  13780. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  13781. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  13782. }
  13783. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  13784. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  13785. var m, ml;
  13786. if ( geometryGroup.numMorphTargets ) {
  13787. geometryGroup.__morphTargetsArrays = [];
  13788. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  13789. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  13790. }
  13791. }
  13792. if ( geometryGroup.numMorphNormals ) {
  13793. geometryGroup.__morphNormalsArrays = [];
  13794. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  13795. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  13796. }
  13797. }
  13798. geometryGroup.__webglFaceCount = ntris * 3;
  13799. geometryGroup.__webglLineCount = nlines * 2;
  13800. // custom attributes
  13801. if ( material.attributes ) {
  13802. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  13803. geometryGroup.__webglCustomAttributesList = [];
  13804. }
  13805. for ( var a in material.attributes ) {
  13806. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  13807. // attribute buffers which are correctly indexed in the setMeshBuffers function
  13808. var originalAttribute = material.attributes[ a ];
  13809. var attribute = {};
  13810. for ( var property in originalAttribute ) {
  13811. attribute[ property ] = originalAttribute[ property ];
  13812. }
  13813. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  13814. attribute.__webglInitialized = true;
  13815. var size = 1; // "f" and "i"
  13816. if( attribute.type === "v2" ) size = 2;
  13817. else if( attribute.type === "v3" ) size = 3;
  13818. else if( attribute.type === "v4" ) size = 4;
  13819. else if( attribute.type === "c" ) size = 3;
  13820. attribute.size = size;
  13821. attribute.array = new Float32Array( nvertices * size );
  13822. attribute.buffer = this.renderer.createBuffer();
  13823. attribute.buffer.belongsToAttribute = a;
  13824. originalAttribute.needsUpdate = true;
  13825. attribute.__original = originalAttribute;
  13826. }
  13827. geometryGroup.__webglCustomAttributesList.push( attribute );
  13828. }
  13829. }
  13830. geometryGroup.__inittedArrays = true;
  13831. },
  13832. setBuffers: function ( geometryGroup, object, dispose, material ) {
  13833. if ( ! geometryGroup.__inittedArrays ) {
  13834. return;
  13835. }
  13836. var renderer = this.renderer;
  13837. var normalType = this.bufferGuessNormalType( material ),
  13838. vertexColorType = this.bufferGuessVertexColorType( material ),
  13839. uvType = this.bufferGuessUVType( material ),
  13840. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  13841. var f, fl, fi, face,
  13842. vertexNormals, faceNormal, normal,
  13843. vertexColors, faceColor,
  13844. vertexTangents,
  13845. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  13846. c1, c2, c3, c4,
  13847. sw1, sw2, sw3, sw4,
  13848. si1, si2, si3, si4,
  13849. sa1, sa2, sa3, sa4,
  13850. sb1, sb2, sb3, sb4,
  13851. m, ml, i, il,
  13852. vn, uvi, uv2i,
  13853. vk, vkl, vka,
  13854. nka, chf, faceVertexNormals,
  13855. a,
  13856. vertexIndex = 0,
  13857. offset = 0,
  13858. offset_uv = 0,
  13859. offset_uv2 = 0,
  13860. offset_face = 0,
  13861. offset_normal = 0,
  13862. offset_tangent = 0,
  13863. offset_line = 0,
  13864. offset_color = 0,
  13865. offset_skin = 0,
  13866. offset_morphTarget = 0,
  13867. offset_custom = 0,
  13868. offset_customSrc = 0,
  13869. value,
  13870. vertexArray = geometryGroup.__vertexArray,
  13871. uvArray = geometryGroup.__uvArray,
  13872. uv2Array = geometryGroup.__uv2Array,
  13873. normalArray = geometryGroup.__normalArray,
  13874. tangentArray = geometryGroup.__tangentArray,
  13875. colorArray = geometryGroup.__colorArray,
  13876. skinIndexArray = geometryGroup.__skinIndexArray,
  13877. skinWeightArray = geometryGroup.__skinWeightArray,
  13878. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  13879. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  13880. customAttributes = geometryGroup.__webglCustomAttributesList,
  13881. customAttribute,
  13882. faceArray = geometryGroup.__faceArray,
  13883. lineArray = geometryGroup.__lineArray,
  13884. geometry = object.geometry, // this is shared for all chunks
  13885. dirtyVertices = geometry.verticesNeedUpdate,
  13886. dirtyElements = geometry.elementsNeedUpdate,
  13887. dirtyUvs = geometry.uvsNeedUpdate,
  13888. dirtyNormals = geometry.normalsNeedUpdate,
  13889. dirtyTangents = geometry.tangentsNeedUpdate,
  13890. dirtyColors = geometry.colorsNeedUpdate,
  13891. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  13892. vertices = geometry.vertices,
  13893. chunk_faces3 = geometryGroup.faces3,
  13894. chunk_faces4 = geometryGroup.faces4,
  13895. obj_faces = geometry.faces,
  13896. obj_uvs = geometry.faceVertexUvs[ 0 ],
  13897. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  13898. obj_colors = geometry.colors,
  13899. obj_skinIndices = geometry.skinIndices,
  13900. obj_skinWeights = geometry.skinWeights,
  13901. morphTargets = geometry.morphTargets,
  13902. morphNormals = geometry.morphNormals;
  13903. if ( dirtyVertices ) {
  13904. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13905. face = obj_faces[ chunk_faces3[ f ] ];
  13906. v1 = vertices[ face.a ];
  13907. v2 = vertices[ face.b ];
  13908. v3 = vertices[ face.c ];
  13909. vertexArray[ offset ] = v1.x;
  13910. vertexArray[ offset + 1 ] = v1.y;
  13911. vertexArray[ offset + 2 ] = v1.z;
  13912. vertexArray[ offset + 3 ] = v2.x;
  13913. vertexArray[ offset + 4 ] = v2.y;
  13914. vertexArray[ offset + 5 ] = v2.z;
  13915. vertexArray[ offset + 6 ] = v3.x;
  13916. vertexArray[ offset + 7 ] = v3.y;
  13917. vertexArray[ offset + 8 ] = v3.z;
  13918. offset += 9;
  13919. }
  13920. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13921. face = obj_faces[ chunk_faces4[ f ] ];
  13922. v1 = vertices[ face.a ];
  13923. v2 = vertices[ face.b ];
  13924. v3 = vertices[ face.c ];
  13925. v4 = vertices[ face.d ];
  13926. vertexArray[ offset ] = v1.x;
  13927. vertexArray[ offset + 1 ] = v1.y;
  13928. vertexArray[ offset + 2 ] = v1.z;
  13929. vertexArray[ offset + 3 ] = v2.x;
  13930. vertexArray[ offset + 4 ] = v2.y;
  13931. vertexArray[ offset + 5 ] = v2.z;
  13932. vertexArray[ offset + 6 ] = v3.x;
  13933. vertexArray[ offset + 7 ] = v3.y;
  13934. vertexArray[ offset + 8 ] = v3.z;
  13935. vertexArray[ offset + 9 ] = v4.x;
  13936. vertexArray[ offset + 10 ] = v4.y;
  13937. vertexArray[ offset + 11 ] = v4.z;
  13938. offset += 12;
  13939. }
  13940. renderer.setDynamicArrayBuffer( geometryGroup.__webglVertexBuffer, vertexArray);
  13941. }
  13942. if ( dirtyMorphTargets ) {
  13943. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  13944. offset_morphTarget = 0;
  13945. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13946. chf = chunk_faces3[ f ];
  13947. face = obj_faces[ chf ];
  13948. // morph positions
  13949. v1 = morphTargets[ vk ].vertices[ face.a ];
  13950. v2 = morphTargets[ vk ].vertices[ face.b ];
  13951. v3 = morphTargets[ vk ].vertices[ face.c ];
  13952. vka = morphTargetsArrays[ vk ];
  13953. vka[ offset_morphTarget ] = v1.x;
  13954. vka[ offset_morphTarget + 1 ] = v1.y;
  13955. vka[ offset_morphTarget + 2 ] = v1.z;
  13956. vka[ offset_morphTarget + 3 ] = v2.x;
  13957. vka[ offset_morphTarget + 4 ] = v2.y;
  13958. vka[ offset_morphTarget + 5 ] = v2.z;
  13959. vka[ offset_morphTarget + 6 ] = v3.x;
  13960. vka[ offset_morphTarget + 7 ] = v3.y;
  13961. vka[ offset_morphTarget + 8 ] = v3.z;
  13962. // morph normals
  13963. if ( material.morphNormals ) {
  13964. if ( needsSmoothNormals ) {
  13965. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  13966. n1 = faceVertexNormals.a;
  13967. n2 = faceVertexNormals.b;
  13968. n3 = faceVertexNormals.c;
  13969. } else {
  13970. n1 = morphNormals[ vk ].faceNormals[ chf ];
  13971. n2 = n1;
  13972. n3 = n1;
  13973. }
  13974. nka = morphNormalsArrays[ vk ];
  13975. nka[ offset_morphTarget ] = n1.x;
  13976. nka[ offset_morphTarget + 1 ] = n1.y;
  13977. nka[ offset_morphTarget + 2 ] = n1.z;
  13978. nka[ offset_morphTarget + 3 ] = n2.x;
  13979. nka[ offset_morphTarget + 4 ] = n2.y;
  13980. nka[ offset_morphTarget + 5 ] = n2.z;
  13981. nka[ offset_morphTarget + 6 ] = n3.x;
  13982. nka[ offset_morphTarget + 7 ] = n3.y;
  13983. nka[ offset_morphTarget + 8 ] = n3.z;
  13984. }
  13985. //
  13986. offset_morphTarget += 9;
  13987. }
  13988. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13989. chf = chunk_faces4[ f ];
  13990. face = obj_faces[ chf ];
  13991. // morph positions
  13992. v1 = morphTargets[ vk ].vertices[ face.a ];
  13993. v2 = morphTargets[ vk ].vertices[ face.b ];
  13994. v3 = morphTargets[ vk ].vertices[ face.c ];
  13995. v4 = morphTargets[ vk ].vertices[ face.d ];
  13996. vka = morphTargetsArrays[ vk ];
  13997. vka[ offset_morphTarget ] = v1.x;
  13998. vka[ offset_morphTarget + 1 ] = v1.y;
  13999. vka[ offset_morphTarget + 2 ] = v1.z;
  14000. vka[ offset_morphTarget + 3 ] = v2.x;
  14001. vka[ offset_morphTarget + 4 ] = v2.y;
  14002. vka[ offset_morphTarget + 5 ] = v2.z;
  14003. vka[ offset_morphTarget + 6 ] = v3.x;
  14004. vka[ offset_morphTarget + 7 ] = v3.y;
  14005. vka[ offset_morphTarget + 8 ] = v3.z;
  14006. vka[ offset_morphTarget + 9 ] = v4.x;
  14007. vka[ offset_morphTarget + 10 ] = v4.y;
  14008. vka[ offset_morphTarget + 11 ] = v4.z;
  14009. // morph normals
  14010. if ( material.morphNormals ) {
  14011. if ( needsSmoothNormals ) {
  14012. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  14013. n1 = faceVertexNormals.a;
  14014. n2 = faceVertexNormals.b;
  14015. n3 = faceVertexNormals.c;
  14016. n4 = faceVertexNormals.d;
  14017. } else {
  14018. n1 = morphNormals[ vk ].faceNormals[ chf ];
  14019. n2 = n1;
  14020. n3 = n1;
  14021. n4 = n1;
  14022. }
  14023. nka = morphNormalsArrays[ vk ];
  14024. nka[ offset_morphTarget ] = n1.x;
  14025. nka[ offset_morphTarget + 1 ] = n1.y;
  14026. nka[ offset_morphTarget + 2 ] = n1.z;
  14027. nka[ offset_morphTarget + 3 ] = n2.x;
  14028. nka[ offset_morphTarget + 4 ] = n2.y;
  14029. nka[ offset_morphTarget + 5 ] = n2.z;
  14030. nka[ offset_morphTarget + 6 ] = n3.x;
  14031. nka[ offset_morphTarget + 7 ] = n3.y;
  14032. nka[ offset_morphTarget + 8 ] = n3.z;
  14033. nka[ offset_morphTarget + 9 ] = n4.x;
  14034. nka[ offset_morphTarget + 10 ] = n4.y;
  14035. nka[ offset_morphTarget + 11 ] = n4.z;
  14036. }
  14037. //
  14038. offset_morphTarget += 12;
  14039. }
  14040. this.renderer.setDynamicArrayBuffer( geometryGroup.__webglMorphTargetsBuffers[ vk ], morphTargetsArrays[ vk ]);
  14041. if ( material.morphNormals ) {
  14042. this.renderer.setDynamicArrayBuffer( geometryGroup.__webglMorphNormalsBuffers[ vk ], morphNormalsArrays[ vk ]);
  14043. }
  14044. }
  14045. }
  14046. if ( obj_skinWeights.length ) {
  14047. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14048. face = obj_faces[ chunk_faces3[ f ] ];
  14049. // weights
  14050. sw1 = obj_skinWeights[ face.a ];
  14051. sw2 = obj_skinWeights[ face.b ];
  14052. sw3 = obj_skinWeights[ face.c ];
  14053. skinWeightArray[ offset_skin ] = sw1.x;
  14054. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  14055. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  14056. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  14057. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  14058. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  14059. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  14060. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  14061. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  14062. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  14063. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  14064. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  14065. // indices
  14066. si1 = obj_skinIndices[ face.a ];
  14067. si2 = obj_skinIndices[ face.b ];
  14068. si3 = obj_skinIndices[ face.c ];
  14069. skinIndexArray[ offset_skin ] = si1.x;
  14070. skinIndexArray[ offset_skin + 1 ] = si1.y;
  14071. skinIndexArray[ offset_skin + 2 ] = si1.z;
  14072. skinIndexArray[ offset_skin + 3 ] = si1.w;
  14073. skinIndexArray[ offset_skin + 4 ] = si2.x;
  14074. skinIndexArray[ offset_skin + 5 ] = si2.y;
  14075. skinIndexArray[ offset_skin + 6 ] = si2.z;
  14076. skinIndexArray[ offset_skin + 7 ] = si2.w;
  14077. skinIndexArray[ offset_skin + 8 ] = si3.x;
  14078. skinIndexArray[ offset_skin + 9 ] = si3.y;
  14079. skinIndexArray[ offset_skin + 10 ] = si3.z;
  14080. skinIndexArray[ offset_skin + 11 ] = si3.w;
  14081. offset_skin += 12;
  14082. }
  14083. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14084. face = obj_faces[ chunk_faces4[ f ] ];
  14085. // weights
  14086. sw1 = obj_skinWeights[ face.a ];
  14087. sw2 = obj_skinWeights[ face.b ];
  14088. sw3 = obj_skinWeights[ face.c ];
  14089. sw4 = obj_skinWeights[ face.d ];
  14090. skinWeightArray[ offset_skin ] = sw1.x;
  14091. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  14092. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  14093. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  14094. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  14095. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  14096. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  14097. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  14098. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  14099. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  14100. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  14101. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  14102. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  14103. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  14104. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  14105. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  14106. // indices
  14107. si1 = obj_skinIndices[ face.a ];
  14108. si2 = obj_skinIndices[ face.b ];
  14109. si3 = obj_skinIndices[ face.c ];
  14110. si4 = obj_skinIndices[ face.d ];
  14111. skinIndexArray[ offset_skin ] = si1.x;
  14112. skinIndexArray[ offset_skin + 1 ] = si1.y;
  14113. skinIndexArray[ offset_skin + 2 ] = si1.z;
  14114. skinIndexArray[ offset_skin + 3 ] = si1.w;
  14115. skinIndexArray[ offset_skin + 4 ] = si2.x;
  14116. skinIndexArray[ offset_skin + 5 ] = si2.y;
  14117. skinIndexArray[ offset_skin + 6 ] = si2.z;
  14118. skinIndexArray[ offset_skin + 7 ] = si2.w;
  14119. skinIndexArray[ offset_skin + 8 ] = si3.x;
  14120. skinIndexArray[ offset_skin + 9 ] = si3.y;
  14121. skinIndexArray[ offset_skin + 10 ] = si3.z;
  14122. skinIndexArray[ offset_skin + 11 ] = si3.w;
  14123. skinIndexArray[ offset_skin + 12 ] = si4.x;
  14124. skinIndexArray[ offset_skin + 13 ] = si4.y;
  14125. skinIndexArray[ offset_skin + 14 ] = si4.z;
  14126. skinIndexArray[ offset_skin + 15 ] = si4.w;
  14127. offset_skin += 16;
  14128. }
  14129. if ( offset_skin > 0 ) {
  14130. renderer.setDynamicArrayBuffer( geometryGroup.__webglSkinIndicesBuffer, skinIndexArray);
  14131. renderer.setDynamicArrayBuffer( geometryGroup.__webglSkinWeightsBuffer, skinWeightArray);
  14132. }
  14133. }
  14134. if ( dirtyColors && vertexColorType ) {
  14135. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14136. face = obj_faces[ chunk_faces3[ f ] ];
  14137. vertexColors = face.vertexColors;
  14138. faceColor = face.color;
  14139. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  14140. c1 = vertexColors[ 0 ];
  14141. c2 = vertexColors[ 1 ];
  14142. c3 = vertexColors[ 2 ];
  14143. } else {
  14144. c1 = faceColor;
  14145. c2 = faceColor;
  14146. c3 = faceColor;
  14147. }
  14148. colorArray[ offset_color ] = c1.r;
  14149. colorArray[ offset_color + 1 ] = c1.g;
  14150. colorArray[ offset_color + 2 ] = c1.b;
  14151. colorArray[ offset_color + 3 ] = c2.r;
  14152. colorArray[ offset_color + 4 ] = c2.g;
  14153. colorArray[ offset_color + 5 ] = c2.b;
  14154. colorArray[ offset_color + 6 ] = c3.r;
  14155. colorArray[ offset_color + 7 ] = c3.g;
  14156. colorArray[ offset_color + 8 ] = c3.b;
  14157. offset_color += 9;
  14158. }
  14159. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14160. face = obj_faces[ chunk_faces4[ f ] ];
  14161. vertexColors = face.vertexColors;
  14162. faceColor = face.color;
  14163. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  14164. c1 = vertexColors[ 0 ];
  14165. c2 = vertexColors[ 1 ];
  14166. c3 = vertexColors[ 2 ];
  14167. c4 = vertexColors[ 3 ];
  14168. } else {
  14169. c1 = faceColor;
  14170. c2 = faceColor;
  14171. c3 = faceColor;
  14172. c4 = faceColor;
  14173. }
  14174. colorArray[ offset_color ] = c1.r;
  14175. colorArray[ offset_color + 1 ] = c1.g;
  14176. colorArray[ offset_color + 2 ] = c1.b;
  14177. colorArray[ offset_color + 3 ] = c2.r;
  14178. colorArray[ offset_color + 4 ] = c2.g;
  14179. colorArray[ offset_color + 5 ] = c2.b;
  14180. colorArray[ offset_color + 6 ] = c3.r;
  14181. colorArray[ offset_color + 7 ] = c3.g;
  14182. colorArray[ offset_color + 8 ] = c3.b;
  14183. colorArray[ offset_color + 9 ] = c4.r;
  14184. colorArray[ offset_color + 10 ] = c4.g;
  14185. colorArray[ offset_color + 11 ] = c4.b;
  14186. offset_color += 12;
  14187. }
  14188. if ( offset_color > 0 ) {
  14189. renderer.setDynamicArrayBuffer( geometryGroup.__webglColorBuffer, colorArray);
  14190. }
  14191. }
  14192. if ( dirtyTangents && geometry.hasTangents ) {
  14193. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14194. face = obj_faces[ chunk_faces3[ f ] ];
  14195. vertexTangents = face.vertexTangents;
  14196. t1 = vertexTangents[ 0 ];
  14197. t2 = vertexTangents[ 1 ];
  14198. t3 = vertexTangents[ 2 ];
  14199. tangentArray[ offset_tangent ] = t1.x;
  14200. tangentArray[ offset_tangent + 1 ] = t1.y;
  14201. tangentArray[ offset_tangent + 2 ] = t1.z;
  14202. tangentArray[ offset_tangent + 3 ] = t1.w;
  14203. tangentArray[ offset_tangent + 4 ] = t2.x;
  14204. tangentArray[ offset_tangent + 5 ] = t2.y;
  14205. tangentArray[ offset_tangent + 6 ] = t2.z;
  14206. tangentArray[ offset_tangent + 7 ] = t2.w;
  14207. tangentArray[ offset_tangent + 8 ] = t3.x;
  14208. tangentArray[ offset_tangent + 9 ] = t3.y;
  14209. tangentArray[ offset_tangent + 10 ] = t3.z;
  14210. tangentArray[ offset_tangent + 11 ] = t3.w;
  14211. offset_tangent += 12;
  14212. }
  14213. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14214. face = obj_faces[ chunk_faces4[ f ] ];
  14215. vertexTangents = face.vertexTangents;
  14216. t1 = vertexTangents[ 0 ];
  14217. t2 = vertexTangents[ 1 ];
  14218. t3 = vertexTangents[ 2 ];
  14219. t4 = vertexTangents[ 3 ];
  14220. tangentArray[ offset_tangent ] = t1.x;
  14221. tangentArray[ offset_tangent + 1 ] = t1.y;
  14222. tangentArray[ offset_tangent + 2 ] = t1.z;
  14223. tangentArray[ offset_tangent + 3 ] = t1.w;
  14224. tangentArray[ offset_tangent + 4 ] = t2.x;
  14225. tangentArray[ offset_tangent + 5 ] = t2.y;
  14226. tangentArray[ offset_tangent + 6 ] = t2.z;
  14227. tangentArray[ offset_tangent + 7 ] = t2.w;
  14228. tangentArray[ offset_tangent + 8 ] = t3.x;
  14229. tangentArray[ offset_tangent + 9 ] = t3.y;
  14230. tangentArray[ offset_tangent + 10 ] = t3.z;
  14231. tangentArray[ offset_tangent + 11 ] = t3.w;
  14232. tangentArray[ offset_tangent + 12 ] = t4.x;
  14233. tangentArray[ offset_tangent + 13 ] = t4.y;
  14234. tangentArray[ offset_tangent + 14 ] = t4.z;
  14235. tangentArray[ offset_tangent + 15 ] = t4.w;
  14236. offset_tangent += 16;
  14237. }
  14238. renderer.setDynamicArrayBuffer( geometryGroup.__webglTangentBuffer, tangentArray);
  14239. }
  14240. if ( dirtyNormals && normalType ) {
  14241. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14242. face = obj_faces[ chunk_faces3[ f ] ];
  14243. vertexNormals = face.vertexNormals;
  14244. faceNormal = face.normal;
  14245. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  14246. for ( i = 0; i < 3; i ++ ) {
  14247. vn = vertexNormals[ i ];
  14248. normalArray[ offset_normal ] = vn.x;
  14249. normalArray[ offset_normal + 1 ] = vn.y;
  14250. normalArray[ offset_normal + 2 ] = vn.z;
  14251. offset_normal += 3;
  14252. }
  14253. } else {
  14254. for ( i = 0; i < 3; i ++ ) {
  14255. normalArray[ offset_normal ] = faceNormal.x;
  14256. normalArray[ offset_normal + 1 ] = faceNormal.y;
  14257. normalArray[ offset_normal + 2 ] = faceNormal.z;
  14258. offset_normal += 3;
  14259. }
  14260. }
  14261. }
  14262. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14263. face = obj_faces[ chunk_faces4[ f ] ];
  14264. vertexNormals = face.vertexNormals;
  14265. faceNormal = face.normal;
  14266. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  14267. for ( i = 0; i < 4; i ++ ) {
  14268. vn = vertexNormals[ i ];
  14269. normalArray[ offset_normal ] = vn.x;
  14270. normalArray[ offset_normal + 1 ] = vn.y;
  14271. normalArray[ offset_normal + 2 ] = vn.z;
  14272. offset_normal += 3;
  14273. }
  14274. } else {
  14275. for ( i = 0; i < 4; i ++ ) {
  14276. normalArray[ offset_normal ] = faceNormal.x;
  14277. normalArray[ offset_normal + 1 ] = faceNormal.y;
  14278. normalArray[ offset_normal + 2 ] = faceNormal.z;
  14279. offset_normal += 3;
  14280. }
  14281. }
  14282. }
  14283. renderer.setDynamicArrayBuffer( geometryGroup.__webglNormalBuffer, normalArray);
  14284. }
  14285. if ( dirtyUvs && obj_uvs && uvType ) {
  14286. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14287. fi = chunk_faces3[ f ];
  14288. uv = obj_uvs[ fi ];
  14289. if ( uv === undefined ) continue;
  14290. for ( i = 0; i < 3; i ++ ) {
  14291. uvi = uv[ i ];
  14292. uvArray[ offset_uv ] = uvi.x;
  14293. uvArray[ offset_uv + 1 ] = uvi.y;
  14294. offset_uv += 2;
  14295. }
  14296. }
  14297. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14298. fi = chunk_faces4[ f ];
  14299. uv = obj_uvs[ fi ];
  14300. if ( uv === undefined ) continue;
  14301. for ( i = 0; i < 4; i ++ ) {
  14302. uvi = uv[ i ];
  14303. uvArray[ offset_uv ] = uvi.x;
  14304. uvArray[ offset_uv + 1 ] = uvi.y;
  14305. offset_uv += 2;
  14306. }
  14307. }
  14308. if ( offset_uv > 0 ) {
  14309. renderer.setDynamicArrayBuffer( geometryGroup.__webglUVBuffer, uvArray);
  14310. }
  14311. }
  14312. if ( dirtyUvs && obj_uvs2 && uvType ) {
  14313. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14314. fi = chunk_faces3[ f ];
  14315. uv2 = obj_uvs2[ fi ];
  14316. if ( uv2 === undefined ) continue;
  14317. for ( i = 0; i < 3; i ++ ) {
  14318. uv2i = uv2[ i ];
  14319. uv2Array[ offset_uv2 ] = uv2i.x;
  14320. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  14321. offset_uv2 += 2;
  14322. }
  14323. }
  14324. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14325. fi = chunk_faces4[ f ];
  14326. uv2 = obj_uvs2[ fi ];
  14327. if ( uv2 === undefined ) continue;
  14328. for ( i = 0; i < 4; i ++ ) {
  14329. uv2i = uv2[ i ];
  14330. uv2Array[ offset_uv2 ] = uv2i.x;
  14331. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  14332. offset_uv2 += 2;
  14333. }
  14334. }
  14335. if ( offset_uv2 > 0 ) {
  14336. renderer.setDynamicArrayBuffer( geometryGroup.__webglUV2Buffer, uv2Array);
  14337. }
  14338. }
  14339. if ( dirtyElements ) {
  14340. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14341. faceArray[ offset_face ] = vertexIndex;
  14342. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  14343. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  14344. offset_face += 3;
  14345. lineArray[ offset_line ] = vertexIndex;
  14346. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  14347. lineArray[ offset_line + 2 ] = vertexIndex;
  14348. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  14349. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  14350. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  14351. offset_line += 6;
  14352. vertexIndex += 3;
  14353. }
  14354. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14355. faceArray[ offset_face ] = vertexIndex;
  14356. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  14357. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  14358. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  14359. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  14360. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  14361. offset_face += 6;
  14362. lineArray[ offset_line ] = vertexIndex;
  14363. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  14364. lineArray[ offset_line + 2 ] = vertexIndex;
  14365. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  14366. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  14367. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  14368. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  14369. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  14370. offset_line += 8;
  14371. vertexIndex += 4;
  14372. }
  14373. renderer.setDynamicIndexBuffer( geometryGroup.__webglFaceBuffer, faceArray);
  14374. renderer.setDynamicIndexBuffer( geometryGroup.__webglLineBuffer, lineArray);
  14375. }
  14376. if ( customAttributes ) {
  14377. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  14378. customAttribute = customAttributes[ i ];
  14379. if ( ! customAttribute.__original.needsUpdate ) continue;
  14380. offset_custom = 0;
  14381. offset_customSrc = 0;
  14382. if ( customAttribute.size === 1 ) {
  14383. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  14384. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14385. face = obj_faces[ chunk_faces3[ f ] ];
  14386. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  14387. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  14388. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  14389. offset_custom += 3;
  14390. }
  14391. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14392. face = obj_faces[ chunk_faces4[ f ] ];
  14393. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  14394. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  14395. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  14396. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  14397. offset_custom += 4;
  14398. }
  14399. } else if ( customAttribute.boundTo === "faces" ) {
  14400. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14401. value = customAttribute.value[ chunk_faces3[ f ] ];
  14402. customAttribute.array[ offset_custom ] = value;
  14403. customAttribute.array[ offset_custom + 1 ] = value;
  14404. customAttribute.array[ offset_custom + 2 ] = value;
  14405. offset_custom += 3;
  14406. }
  14407. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14408. value = customAttribute.value[ chunk_faces4[ f ] ];
  14409. customAttribute.array[ offset_custom ] = value;
  14410. customAttribute.array[ offset_custom + 1 ] = value;
  14411. customAttribute.array[ offset_custom + 2 ] = value;
  14412. customAttribute.array[ offset_custom + 3 ] = value;
  14413. offset_custom += 4;
  14414. }
  14415. }
  14416. } else if ( customAttribute.size === 2 ) {
  14417. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  14418. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14419. face = obj_faces[ chunk_faces3[ f ] ];
  14420. v1 = customAttribute.value[ face.a ];
  14421. v2 = customAttribute.value[ face.b ];
  14422. v3 = customAttribute.value[ face.c ];
  14423. customAttribute.array[ offset_custom ] = v1.x;
  14424. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14425. customAttribute.array[ offset_custom + 2 ] = v2.x;
  14426. customAttribute.array[ offset_custom + 3 ] = v2.y;
  14427. customAttribute.array[ offset_custom + 4 ] = v3.x;
  14428. customAttribute.array[ offset_custom + 5 ] = v3.y;
  14429. offset_custom += 6;
  14430. }
  14431. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14432. face = obj_faces[ chunk_faces4[ f ] ];
  14433. v1 = customAttribute.value[ face.a ];
  14434. v2 = customAttribute.value[ face.b ];
  14435. v3 = customAttribute.value[ face.c ];
  14436. v4 = customAttribute.value[ face.d ];
  14437. customAttribute.array[ offset_custom ] = v1.x;
  14438. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14439. customAttribute.array[ offset_custom + 2 ] = v2.x;
  14440. customAttribute.array[ offset_custom + 3 ] = v2.y;
  14441. customAttribute.array[ offset_custom + 4 ] = v3.x;
  14442. customAttribute.array[ offset_custom + 5 ] = v3.y;
  14443. customAttribute.array[ offset_custom + 6 ] = v4.x;
  14444. customAttribute.array[ offset_custom + 7 ] = v4.y;
  14445. offset_custom += 8;
  14446. }
  14447. } else if ( customAttribute.boundTo === "faces" ) {
  14448. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14449. value = customAttribute.value[ chunk_faces3[ f ] ];
  14450. v1 = value;
  14451. v2 = value;
  14452. v3 = value;
  14453. customAttribute.array[ offset_custom ] = v1.x;
  14454. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14455. customAttribute.array[ offset_custom + 2 ] = v2.x;
  14456. customAttribute.array[ offset_custom + 3 ] = v2.y;
  14457. customAttribute.array[ offset_custom + 4 ] = v3.x;
  14458. customAttribute.array[ offset_custom + 5 ] = v3.y;
  14459. offset_custom += 6;
  14460. }
  14461. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14462. value = customAttribute.value[ chunk_faces4[ f ] ];
  14463. v1 = value;
  14464. v2 = value;
  14465. v3 = value;
  14466. v4 = value;
  14467. customAttribute.array[ offset_custom ] = v1.x;
  14468. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14469. customAttribute.array[ offset_custom + 2 ] = v2.x;
  14470. customAttribute.array[ offset_custom + 3 ] = v2.y;
  14471. customAttribute.array[ offset_custom + 4 ] = v3.x;
  14472. customAttribute.array[ offset_custom + 5 ] = v3.y;
  14473. customAttribute.array[ offset_custom + 6 ] = v4.x;
  14474. customAttribute.array[ offset_custom + 7 ] = v4.y;
  14475. offset_custom += 8;
  14476. }
  14477. }
  14478. } else if ( customAttribute.size === 3 ) {
  14479. var pp;
  14480. if ( customAttribute.type === "c" ) {
  14481. pp = [ "r", "g", "b" ];
  14482. } else {
  14483. pp = [ "x", "y", "z" ];
  14484. }
  14485. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  14486. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14487. face = obj_faces[ chunk_faces3[ f ] ];
  14488. v1 = customAttribute.value[ face.a ];
  14489. v2 = customAttribute.value[ face.b ];
  14490. v3 = customAttribute.value[ face.c ];
  14491. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  14492. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  14493. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  14494. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  14495. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  14496. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  14497. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  14498. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  14499. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  14500. offset_custom += 9;
  14501. }
  14502. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14503. face = obj_faces[ chunk_faces4[ f ] ];
  14504. v1 = customAttribute.value[ face.a ];
  14505. v2 = customAttribute.value[ face.b ];
  14506. v3 = customAttribute.value[ face.c ];
  14507. v4 = customAttribute.value[ face.d ];
  14508. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  14509. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  14510. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  14511. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  14512. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  14513. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  14514. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  14515. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  14516. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  14517. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  14518. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  14519. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  14520. offset_custom += 12;
  14521. }
  14522. } else if ( customAttribute.boundTo === "faces" ) {
  14523. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14524. value = customAttribute.value[ chunk_faces3[ f ] ];
  14525. v1 = value;
  14526. v2 = value;
  14527. v3 = value;
  14528. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  14529. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  14530. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  14531. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  14532. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  14533. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  14534. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  14535. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  14536. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  14537. offset_custom += 9;
  14538. }
  14539. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14540. value = customAttribute.value[ chunk_faces4[ f ] ];
  14541. v1 = value;
  14542. v2 = value;
  14543. v3 = value;
  14544. v4 = value;
  14545. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  14546. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  14547. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  14548. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  14549. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  14550. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  14551. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  14552. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  14553. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  14554. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  14555. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  14556. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  14557. offset_custom += 12;
  14558. }
  14559. } else if ( customAttribute.boundTo === "faceVertices" ) {
  14560. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14561. value = customAttribute.value[ chunk_faces3[ f ] ];
  14562. v1 = value[ 0 ];
  14563. v2 = value[ 1 ];
  14564. v3 = value[ 2 ];
  14565. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  14566. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  14567. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  14568. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  14569. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  14570. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  14571. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  14572. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  14573. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  14574. offset_custom += 9;
  14575. }
  14576. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14577. value = customAttribute.value[ chunk_faces4[ f ] ];
  14578. v1 = value[ 0 ];
  14579. v2 = value[ 1 ];
  14580. v3 = value[ 2 ];
  14581. v4 = value[ 3 ];
  14582. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  14583. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  14584. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  14585. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  14586. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  14587. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  14588. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  14589. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  14590. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  14591. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  14592. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  14593. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  14594. offset_custom += 12;
  14595. }
  14596. }
  14597. } else if ( customAttribute.size === 4 ) {
  14598. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  14599. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14600. face = obj_faces[ chunk_faces3[ f ] ];
  14601. v1 = customAttribute.value[ face.a ];
  14602. v2 = customAttribute.value[ face.b ];
  14603. v3 = customAttribute.value[ face.c ];
  14604. customAttribute.array[ offset_custom ] = v1.x;
  14605. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14606. customAttribute.array[ offset_custom + 2 ] = v1.z;
  14607. customAttribute.array[ offset_custom + 3 ] = v1.w;
  14608. customAttribute.array[ offset_custom + 4 ] = v2.x;
  14609. customAttribute.array[ offset_custom + 5 ] = v2.y;
  14610. customAttribute.array[ offset_custom + 6 ] = v2.z;
  14611. customAttribute.array[ offset_custom + 7 ] = v2.w;
  14612. customAttribute.array[ offset_custom + 8 ] = v3.x;
  14613. customAttribute.array[ offset_custom + 9 ] = v3.y;
  14614. customAttribute.array[ offset_custom + 10 ] = v3.z;
  14615. customAttribute.array[ offset_custom + 11 ] = v3.w;
  14616. offset_custom += 12;
  14617. }
  14618. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14619. face = obj_faces[ chunk_faces4[ f ] ];
  14620. v1 = customAttribute.value[ face.a ];
  14621. v2 = customAttribute.value[ face.b ];
  14622. v3 = customAttribute.value[ face.c ];
  14623. v4 = customAttribute.value[ face.d ];
  14624. customAttribute.array[ offset_custom ] = v1.x;
  14625. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14626. customAttribute.array[ offset_custom + 2 ] = v1.z;
  14627. customAttribute.array[ offset_custom + 3 ] = v1.w;
  14628. customAttribute.array[ offset_custom + 4 ] = v2.x;
  14629. customAttribute.array[ offset_custom + 5 ] = v2.y;
  14630. customAttribute.array[ offset_custom + 6 ] = v2.z;
  14631. customAttribute.array[ offset_custom + 7 ] = v2.w;
  14632. customAttribute.array[ offset_custom + 8 ] = v3.x;
  14633. customAttribute.array[ offset_custom + 9 ] = v3.y;
  14634. customAttribute.array[ offset_custom + 10 ] = v3.z;
  14635. customAttribute.array[ offset_custom + 11 ] = v3.w;
  14636. customAttribute.array[ offset_custom + 12 ] = v4.x;
  14637. customAttribute.array[ offset_custom + 13 ] = v4.y;
  14638. customAttribute.array[ offset_custom + 14 ] = v4.z;
  14639. customAttribute.array[ offset_custom + 15 ] = v4.w;
  14640. offset_custom += 16;
  14641. }
  14642. } else if ( customAttribute.boundTo === "faces" ) {
  14643. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14644. value = customAttribute.value[ chunk_faces3[ f ] ];
  14645. v1 = value;
  14646. v2 = value;
  14647. v3 = value;
  14648. customAttribute.array[ offset_custom ] = v1.x;
  14649. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14650. customAttribute.array[ offset_custom + 2 ] = v1.z;
  14651. customAttribute.array[ offset_custom + 3 ] = v1.w;
  14652. customAttribute.array[ offset_custom + 4 ] = v2.x;
  14653. customAttribute.array[ offset_custom + 5 ] = v2.y;
  14654. customAttribute.array[ offset_custom + 6 ] = v2.z;
  14655. customAttribute.array[ offset_custom + 7 ] = v2.w;
  14656. customAttribute.array[ offset_custom + 8 ] = v3.x;
  14657. customAttribute.array[ offset_custom + 9 ] = v3.y;
  14658. customAttribute.array[ offset_custom + 10 ] = v3.z;
  14659. customAttribute.array[ offset_custom + 11 ] = v3.w;
  14660. offset_custom += 12;
  14661. }
  14662. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14663. value = customAttribute.value[ chunk_faces4[ f ] ];
  14664. v1 = value;
  14665. v2 = value;
  14666. v3 = value;
  14667. v4 = value;
  14668. customAttribute.array[ offset_custom ] = v1.x;
  14669. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14670. customAttribute.array[ offset_custom + 2 ] = v1.z;
  14671. customAttribute.array[ offset_custom + 3 ] = v1.w;
  14672. customAttribute.array[ offset_custom + 4 ] = v2.x;
  14673. customAttribute.array[ offset_custom + 5 ] = v2.y;
  14674. customAttribute.array[ offset_custom + 6 ] = v2.z;
  14675. customAttribute.array[ offset_custom + 7 ] = v2.w;
  14676. customAttribute.array[ offset_custom + 8 ] = v3.x;
  14677. customAttribute.array[ offset_custom + 9 ] = v3.y;
  14678. customAttribute.array[ offset_custom + 10 ] = v3.z;
  14679. customAttribute.array[ offset_custom + 11 ] = v3.w;
  14680. customAttribute.array[ offset_custom + 12 ] = v4.x;
  14681. customAttribute.array[ offset_custom + 13 ] = v4.y;
  14682. customAttribute.array[ offset_custom + 14 ] = v4.z;
  14683. customAttribute.array[ offset_custom + 15 ] = v4.w;
  14684. offset_custom += 16;
  14685. }
  14686. } else if ( customAttribute.boundTo === "faceVertices" ) {
  14687. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  14688. value = customAttribute.value[ chunk_faces3[ f ] ];
  14689. v1 = value[ 0 ];
  14690. v2 = value[ 1 ];
  14691. v3 = value[ 2 ];
  14692. customAttribute.array[ offset_custom ] = v1.x;
  14693. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14694. customAttribute.array[ offset_custom + 2 ] = v1.z;
  14695. customAttribute.array[ offset_custom + 3 ] = v1.w;
  14696. customAttribute.array[ offset_custom + 4 ] = v2.x;
  14697. customAttribute.array[ offset_custom + 5 ] = v2.y;
  14698. customAttribute.array[ offset_custom + 6 ] = v2.z;
  14699. customAttribute.array[ offset_custom + 7 ] = v2.w;
  14700. customAttribute.array[ offset_custom + 8 ] = v3.x;
  14701. customAttribute.array[ offset_custom + 9 ] = v3.y;
  14702. customAttribute.array[ offset_custom + 10 ] = v3.z;
  14703. customAttribute.array[ offset_custom + 11 ] = v3.w;
  14704. offset_custom += 12;
  14705. }
  14706. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  14707. value = customAttribute.value[ chunk_faces4[ f ] ];
  14708. v1 = value[ 0 ];
  14709. v2 = value[ 1 ];
  14710. v3 = value[ 2 ];
  14711. v4 = value[ 3 ];
  14712. customAttribute.array[ offset_custom ] = v1.x;
  14713. customAttribute.array[ offset_custom + 1 ] = v1.y;
  14714. customAttribute.array[ offset_custom + 2 ] = v1.z;
  14715. customAttribute.array[ offset_custom + 3 ] = v1.w;
  14716. customAttribute.array[ offset_custom + 4 ] = v2.x;
  14717. customAttribute.array[ offset_custom + 5 ] = v2.y;
  14718. customAttribute.array[ offset_custom + 6 ] = v2.z;
  14719. customAttribute.array[ offset_custom + 7 ] = v2.w;
  14720. customAttribute.array[ offset_custom + 8 ] = v3.x;
  14721. customAttribute.array[ offset_custom + 9 ] = v3.y;
  14722. customAttribute.array[ offset_custom + 10 ] = v3.z;
  14723. customAttribute.array[ offset_custom + 11 ] = v3.w;
  14724. customAttribute.array[ offset_custom + 12 ] = v4.x;
  14725. customAttribute.array[ offset_custom + 13 ] = v4.y;
  14726. customAttribute.array[ offset_custom + 14 ] = v4.z;
  14727. customAttribute.array[ offset_custom + 15 ] = v4.w;
  14728. offset_custom += 16;
  14729. }
  14730. }
  14731. }
  14732. renderer.setDynamicArrayBuffer( customAttribute.buffer, customAttribute.array);
  14733. }
  14734. }
  14735. if ( dispose ) {
  14736. delete geometryGroup.__inittedArrays;
  14737. delete geometryGroup.__colorArray;
  14738. delete geometryGroup.__normalArray;
  14739. delete geometryGroup.__tangentArray;
  14740. delete geometryGroup.__uvArray;
  14741. delete geometryGroup.__uv2Array;
  14742. delete geometryGroup.__faceArray;
  14743. delete geometryGroup.__vertexArray;
  14744. delete geometryGroup.__lineArray;
  14745. delete geometryGroup.__skinIndexArray;
  14746. delete geometryGroup.__skinWeightArray;
  14747. }
  14748. }
  14749. } );
  14750. THREE.WebGLRenderer.ParticleRenderer = function ( lowlevelrenderer, info ) {
  14751. THREE.WebGLRenderer.Object3DRenderer.call( this, lowlevelrenderer, info );
  14752. };
  14753. THREE.WebGLRenderer.ParticleRenderer.prototype = Object.create( THREE.WebGLRenderer.Object3DRenderer.prototype );
  14754. THREE.extend( THREE.WebGLRenderer.ParticleRenderer.prototype, {
  14755. createBuffers: function ( geometry ) {
  14756. var renderer = this.renderer;
  14757. geometry.__webglVertexBuffer = renderer.createBuffer();
  14758. geometry.__webglColorBuffer = renderer.createBuffer();
  14759. this.info.memory.geometries ++;
  14760. },
  14761. initBuffers: function ( geometry, object ) {
  14762. var nvertices = geometry.vertices.length;
  14763. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  14764. geometry.__colorArray = new Float32Array( nvertices * 3 );
  14765. geometry.__sortArray = [];
  14766. geometry.__webglParticleCount = nvertices;
  14767. this.initCustomAttributes ( geometry, object );
  14768. },
  14769. setBuffers: function ( geometry, object , projectionScreenMatrix ) {
  14770. var renderer = this.renderer;
  14771. var v, c, vertex, offset, index, color,
  14772. vertices = geometry.vertices,
  14773. vl = vertices.length,
  14774. colors = geometry.colors,
  14775. cl = colors.length,
  14776. vertexArray = geometry.__vertexArray,
  14777. colorArray = geometry.__colorArray,
  14778. sortArray = geometry.__sortArray,
  14779. dirtyVertices = geometry.verticesNeedUpdate,
  14780. dirtyElements = geometry.elementsNeedUpdate,
  14781. dirtyColors = geometry.colorsNeedUpdate,
  14782. customAttributes = geometry.__webglCustomAttributesList,
  14783. i, il,
  14784. a, ca, cal, value,
  14785. customAttribute;
  14786. var _projScreenMatrixPS = THREE.WebGLRenderer.ParticleRenderer._m1,
  14787. _vector3 = THREE.WebGLRenderer.ParticleRenderer._v1;
  14788. if ( object.sortParticles ) {
  14789. _projScreenMatrixPS.multiplyMatrices( projectionScreenMatrix, object.matrixWorld );
  14790. for ( v = 0; v < vl; v ++ ) {
  14791. vertex = vertices[ v ];
  14792. _vector3.copy( vertex );
  14793. _vector3.applyProjection(_projScreenMatrixPS);
  14794. sortArray[ v ] = [ _vector3.z, v ];
  14795. }
  14796. sortArray.sort( this.numericalSort );
  14797. for ( v = 0; v < vl; v ++ ) {
  14798. vertex = vertices[ sortArray[v][1] ];
  14799. offset = v * 3;
  14800. vertexArray[ offset ] = vertex.x;
  14801. vertexArray[ offset + 1 ] = vertex.y;
  14802. vertexArray[ offset + 2 ] = vertex.z;
  14803. }
  14804. for ( c = 0; c < cl; c ++ ) {
  14805. offset = c * 3;
  14806. color = colors[ sortArray[c][1] ];
  14807. colorArray[ offset ] = color.r;
  14808. colorArray[ offset + 1 ] = color.g;
  14809. colorArray[ offset + 2 ] = color.b;
  14810. }
  14811. if ( customAttributes ) {
  14812. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  14813. customAttribute = customAttributes[ i ];
  14814. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  14815. offset = 0;
  14816. cal = customAttribute.value.length;
  14817. if ( customAttribute.size === 1 ) {
  14818. for ( ca = 0; ca < cal; ca ++ ) {
  14819. index = sortArray[ ca ][ 1 ];
  14820. customAttribute.array[ ca ] = customAttribute.value[ index ];
  14821. }
  14822. } else if ( customAttribute.size === 2 ) {
  14823. for ( ca = 0; ca < cal; ca ++ ) {
  14824. index = sortArray[ ca ][ 1 ];
  14825. value = customAttribute.value[ index ];
  14826. customAttribute.array[ offset ] = value.x;
  14827. customAttribute.array[ offset + 1 ] = value.y;
  14828. offset += 2;
  14829. }
  14830. } else if ( customAttribute.size === 3 ) {
  14831. if ( customAttribute.type === "c" ) {
  14832. for ( ca = 0; ca < cal; ca ++ ) {
  14833. index = sortArray[ ca ][ 1 ];
  14834. value = customAttribute.value[ index ];
  14835. customAttribute.array[ offset ] = value.r;
  14836. customAttribute.array[ offset + 1 ] = value.g;
  14837. customAttribute.array[ offset + 2 ] = value.b;
  14838. offset += 3;
  14839. }
  14840. } else {
  14841. for ( ca = 0; ca < cal; ca ++ ) {
  14842. index = sortArray[ ca ][ 1 ];
  14843. value = customAttribute.value[ index ];
  14844. customAttribute.array[ offset ] = value.x;
  14845. customAttribute.array[ offset + 1 ] = value.y;
  14846. customAttribute.array[ offset + 2 ] = value.z;
  14847. offset += 3;
  14848. }
  14849. }
  14850. } else if ( customAttribute.size === 4 ) {
  14851. for ( ca = 0; ca < cal; ca ++ ) {
  14852. index = sortArray[ ca ][ 1 ];
  14853. value = customAttribute.value[ index ];
  14854. customAttribute.array[ offset ] = value.x;
  14855. customAttribute.array[ offset + 1 ] = value.y;
  14856. customAttribute.array[ offset + 2 ] = value.z;
  14857. customAttribute.array[ offset + 3 ] = value.w;
  14858. offset += 4;
  14859. }
  14860. }
  14861. }
  14862. }
  14863. } else {
  14864. if ( dirtyVertices ) {
  14865. for ( v = 0; v < vl; v ++ ) {
  14866. vertex = vertices[ v ];
  14867. offset = v * 3;
  14868. vertexArray[ offset ] = vertex.x;
  14869. vertexArray[ offset + 1 ] = vertex.y;
  14870. vertexArray[ offset + 2 ] = vertex.z;
  14871. }
  14872. }
  14873. if ( dirtyColors ) {
  14874. for ( c = 0; c < cl; c ++ ) {
  14875. color = colors[ c ];
  14876. offset = c * 3;
  14877. colorArray[ offset ] = color.r;
  14878. colorArray[ offset + 1 ] = color.g;
  14879. colorArray[ offset + 2 ] = color.b;
  14880. }
  14881. }
  14882. if ( customAttributes ) {
  14883. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  14884. customAttribute = customAttributes[ i ];
  14885. if ( customAttribute.needsUpdate &&
  14886. ( customAttribute.boundTo === undefined ||
  14887. customAttribute.boundTo === "vertices") ) {
  14888. cal = customAttribute.value.length;
  14889. offset = 0;
  14890. if ( customAttribute.size === 1 ) {
  14891. for ( ca = 0; ca < cal; ca ++ ) {
  14892. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  14893. }
  14894. } else if ( customAttribute.size === 2 ) {
  14895. for ( ca = 0; ca < cal; ca ++ ) {
  14896. value = customAttribute.value[ ca ];
  14897. customAttribute.array[ offset ] = value.x;
  14898. customAttribute.array[ offset + 1 ] = value.y;
  14899. offset += 2;
  14900. }
  14901. } else if ( customAttribute.size === 3 ) {
  14902. if ( customAttribute.type === "c" ) {
  14903. for ( ca = 0; ca < cal; ca ++ ) {
  14904. value = customAttribute.value[ ca ];
  14905. customAttribute.array[ offset ] = value.r;
  14906. customAttribute.array[ offset + 1 ] = value.g;
  14907. customAttribute.array[ offset + 2 ] = value.b;
  14908. offset += 3;
  14909. }
  14910. } else {
  14911. for ( ca = 0; ca < cal; ca ++ ) {
  14912. value = customAttribute.value[ ca ];
  14913. customAttribute.array[ offset ] = value.x;
  14914. customAttribute.array[ offset + 1 ] = value.y;
  14915. customAttribute.array[ offset + 2 ] = value.z;
  14916. offset += 3;
  14917. }
  14918. }
  14919. } else if ( customAttribute.size === 4 ) {
  14920. for ( ca = 0; ca < cal; ca ++ ) {
  14921. value = customAttribute.value[ ca ];
  14922. customAttribute.array[ offset ] = value.x;
  14923. customAttribute.array[ offset + 1 ] = value.y;
  14924. customAttribute.array[ offset + 2 ] = value.z;
  14925. customAttribute.array[ offset + 3 ] = value.w;
  14926. offset += 4;
  14927. }
  14928. }
  14929. }
  14930. }
  14931. }
  14932. }
  14933. if ( dirtyVertices || object.sortParticles ) {
  14934. renderer.setDynamicArrayBuffer(geometry.__webglVertexBuffer,vertexArray);
  14935. }
  14936. if ( dirtyColors || object.sortParticles ) {
  14937. renderer.setDynamicArrayBuffer(geometry.__webglColorBuffer,colorArray);
  14938. }
  14939. if ( customAttributes ) {
  14940. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  14941. customAttribute = customAttributes[ i ];
  14942. if ( customAttribute.needsUpdate || object.sortParticles ) {
  14943. renderer.setDynamicArrayBuffer(customAttribute.buffer,customAttribute.array);
  14944. }
  14945. }
  14946. }
  14947. }
  14948. } );
  14949. THREE.WebGLRenderer.ParticleRenderer._m1 = new THREE.Matrix4();
  14950. THREE.WebGLRenderer.ParticleRenderer._v1 = new THREE.Vector3();
  14951. THREE.WebGLRenderer.LineRenderer = function ( lowlevelrenderer, info ) {
  14952. THREE.WebGLRenderer.Object3DRenderer.call( this, lowlevelrenderer, info );
  14953. };
  14954. THREE.WebGLRenderer.LineRenderer.prototype = Object.create( THREE.WebGLRenderer.Object3DRenderer.prototype );
  14955. THREE.extend( THREE.WebGLRenderer.LineRenderer.prototype, {
  14956. createBuffers: function ( geometry ) {
  14957. var renderer = this.renderer;
  14958. geometry.__webglVertexBuffer = renderer.createBuffer();
  14959. geometry.__webglColorBuffer = renderer.createBuffer();
  14960. geometry.__webglLineDistanceBuffer = renderer.createBuffer();
  14961. this.info.memory.geometries ++;
  14962. },
  14963. initBuffers: function ( geometry, object ) {
  14964. var nvertices = geometry.vertices.length;
  14965. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  14966. geometry.__colorArray = new Float32Array( nvertices * 3 );
  14967. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  14968. geometry.__webglLineCount = nvertices;
  14969. this.initCustomAttributes ( geometry, object );
  14970. },
  14971. setBuffers: function ( geometry, object ) {
  14972. var renderer = this.renderer;
  14973. var v, c, d, vertex, offset, color,
  14974. vertices = geometry.vertices,
  14975. colors = geometry.colors,
  14976. lineDistances = geometry.lineDistances,
  14977. vl = vertices.length,
  14978. cl = colors.length,
  14979. dl = lineDistances.length,
  14980. vertexArray = geometry.__vertexArray,
  14981. colorArray = geometry.__colorArray,
  14982. lineDistanceArray = geometry.__lineDistanceArray,
  14983. dirtyVertices = geometry.verticesNeedUpdate,
  14984. dirtyColors = geometry.colorsNeedUpdate,
  14985. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  14986. customAttributes = geometry.__webglCustomAttributesList,
  14987. i, il,
  14988. a, ca, cal, value,
  14989. customAttribute;
  14990. if ( dirtyVertices ) {
  14991. for ( v = 0; v < vl; v ++ ) {
  14992. vertex = vertices[ v ];
  14993. offset = v * 3;
  14994. vertexArray[ offset ] = vertex.x;
  14995. vertexArray[ offset + 1 ] = vertex.y;
  14996. vertexArray[ offset + 2 ] = vertex.z;
  14997. }
  14998. renderer.setDynamicArrayBuffer(geometry.__webglVertexBuffer,vertexArray);
  14999. }
  15000. if ( dirtyColors ) {
  15001. for ( c = 0; c < cl; c ++ ) {
  15002. color = colors[ c ];
  15003. offset = c * 3;
  15004. colorArray[ offset ] = color.r;
  15005. colorArray[ offset + 1 ] = color.g;
  15006. colorArray[ offset + 2 ] = color.b;
  15007. }
  15008. renderer.setDynamicArrayBuffer(geometry.__webglColorBuffer,colorArray);
  15009. }
  15010. if ( dirtyLineDistances ) {
  15011. for ( d = 0; d < dl; d ++ ) {
  15012. lineDistanceArray[ d ] = lineDistances[ d ];
  15013. }
  15014. renderer.setDynamicArrayBuffer( geometry.__webglLineDistanceBuffer,lineDistanceArray);
  15015. }
  15016. if ( customAttributes ) {
  15017. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  15018. customAttribute = customAttributes[ i ];
  15019. if ( customAttribute.needsUpdate &&
  15020. ( customAttribute.boundTo === undefined ||
  15021. customAttribute.boundTo === "vertices" ) ) {
  15022. offset = 0;
  15023. cal = customAttribute.value.length;
  15024. if ( customAttribute.size === 1 ) {
  15025. for ( ca = 0; ca < cal; ca ++ ) {
  15026. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  15027. }
  15028. } else if ( customAttribute.size === 2 ) {
  15029. for ( ca = 0; ca < cal; ca ++ ) {
  15030. value = customAttribute.value[ ca ];
  15031. customAttribute.array[ offset ] = value.x;
  15032. customAttribute.array[ offset + 1 ] = value.y;
  15033. offset += 2;
  15034. }
  15035. } else if ( customAttribute.size === 3 ) {
  15036. if ( customAttribute.type === "c" ) {
  15037. for ( ca = 0; ca < cal; ca ++ ) {
  15038. value = customAttribute.value[ ca ];
  15039. customAttribute.array[ offset ] = value.r;
  15040. customAttribute.array[ offset + 1 ] = value.g;
  15041. customAttribute.array[ offset + 2 ] = value.b;
  15042. offset += 3;
  15043. }
  15044. } else {
  15045. for ( ca = 0; ca < cal; ca ++ ) {
  15046. value = customAttribute.value[ ca ];
  15047. customAttribute.array[ offset ] = value.x;
  15048. customAttribute.array[ offset + 1 ] = value.y;
  15049. customAttribute.array[ offset + 2 ] = value.z;
  15050. offset += 3;
  15051. }
  15052. }
  15053. } else if ( customAttribute.size === 4 ) {
  15054. for ( ca = 0; ca < cal; ca ++ ) {
  15055. value = customAttribute.value[ ca ];
  15056. customAttribute.array[ offset ] = value.x;
  15057. customAttribute.array[ offset + 1 ] = value.y;
  15058. customAttribute.array[ offset + 2 ] = value.z;
  15059. customAttribute.array[ offset + 3 ] = value.w;
  15060. offset += 4;
  15061. }
  15062. }
  15063. renderer.setDynamicArrayBuffer( customAttribute.buffer,customAttribute.array);
  15064. }
  15065. }
  15066. }
  15067. }
  15068. } );
  15069. THREE.WebGLRenderer.RibbonRenderer = function ( lowlevelrenderer, info ) {
  15070. THREE.WebGLRenderer.Object3DRenderer.call( this, lowlevelrenderer, info );
  15071. };
  15072. THREE.WebGLRenderer.RibbonRenderer.prototype = Object.create( THREE.WebGLRenderer.Object3DRenderer.prototype );
  15073. THREE.extend( THREE.WebGLRenderer.RibbonRenderer.prototype, {
  15074. createBuffers: function ( geometry ) {
  15075. var renderer = this.renderer;
  15076. geometry.__webglVertexBuffer = renderer.createBuffer();
  15077. geometry.__webglColorBuffer = renderer.createBuffer();
  15078. geometry.__webglNormalBuffer = renderer.createBuffer();
  15079. this.info.memory.geometries ++;
  15080. },
  15081. initBuffers: function ( geometry, object ) {
  15082. var nvertices = geometry.vertices.length;
  15083. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  15084. geometry.__colorArray = new Float32Array( nvertices * 3 );
  15085. geometry.__normalArray = new Float32Array( nvertices * 3 );
  15086. geometry.__webglVertexCount = nvertices;
  15087. this.initCustomAttributes ( geometry, object );
  15088. },
  15089. setBuffers: function ( geometry, object , projectionScreenMatrix ) {
  15090. var renderer = this.renderer;
  15091. var v, c, n, vertex, offset, color, normal,
  15092. i, il, ca, cal, customAttribute, value,
  15093. vertices = geometry.vertices,
  15094. colors = geometry.colors,
  15095. normals = geometry.normals,
  15096. vl = vertices.length,
  15097. cl = colors.length,
  15098. nl = normals.length,
  15099. vertexArray = geometry.__vertexArray,
  15100. colorArray = geometry.__colorArray,
  15101. normalArray = geometry.__normalArray,
  15102. dirtyVertices = geometry.verticesNeedUpdate,
  15103. dirtyColors = geometry.colorsNeedUpdate,
  15104. dirtyNormals = geometry.normalsNeedUpdate,
  15105. customAttributes = geometry.__webglCustomAttributesList;
  15106. if ( dirtyVertices ) {
  15107. for ( v = 0; v < vl; v ++ ) {
  15108. vertex = vertices[ v ];
  15109. offset = v * 3;
  15110. vertexArray[ offset ] = vertex.x;
  15111. vertexArray[ offset + 1 ] = vertex.y;
  15112. vertexArray[ offset + 2 ] = vertex.z;
  15113. }
  15114. renderer.setDynamicArrayBuffer( geometry.__webglVertexBuffer,vertexArray);
  15115. }
  15116. if ( dirtyColors ) {
  15117. for ( c = 0; c < cl; c ++ ) {
  15118. color = colors[ c ];
  15119. offset = c * 3;
  15120. colorArray[ offset ] = color.r;
  15121. colorArray[ offset + 1 ] = color.g;
  15122. colorArray[ offset + 2 ] = color.b;
  15123. }
  15124. renderer.setDynamicArrayBuffer( geometry.__webglColorBuffer, colorArray);
  15125. }
  15126. if ( dirtyNormals ) {
  15127. for ( n = 0; n < nl; n ++ ) {
  15128. normal = normals[ n ];
  15129. offset = n * 3;
  15130. normalArray[ offset ] = normal.x;
  15131. normalArray[ offset + 1 ] = normal.y;
  15132. normalArray[ offset + 2 ] = normal.z;
  15133. }
  15134. renderer.setDynamicArrayBuffer( geometry.__webglNormalBuffer, normalArray);
  15135. }
  15136. if ( customAttributes ) {
  15137. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  15138. customAttribute = customAttributes[ i ];
  15139. if ( customAttribute.needsUpdate &&
  15140. ( customAttribute.boundTo === undefined ||
  15141. customAttribute.boundTo === "vertices" ) ) {
  15142. offset = 0;
  15143. cal = customAttribute.value.length;
  15144. if ( customAttribute.size === 1 ) {
  15145. for ( ca = 0; ca < cal; ca ++ ) {
  15146. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  15147. }
  15148. } else if ( customAttribute.size === 2 ) {
  15149. for ( ca = 0; ca < cal; ca ++ ) {
  15150. value = customAttribute.value[ ca ];
  15151. customAttribute.array[ offset ] = value.x;
  15152. customAttribute.array[ offset + 1 ] = value.y;
  15153. offset += 2;
  15154. }
  15155. } else if ( customAttribute.size === 3 ) {
  15156. if ( customAttribute.type === "c" ) {
  15157. for ( ca = 0; ca < cal; ca ++ ) {
  15158. value = customAttribute.value[ ca ];
  15159. customAttribute.array[ offset ] = value.r;
  15160. customAttribute.array[ offset + 1 ] = value.g;
  15161. customAttribute.array[ offset + 2 ] = value.b;
  15162. offset += 3;
  15163. }
  15164. } else {
  15165. for ( ca = 0; ca < cal; ca ++ ) {
  15166. value = customAttribute.value[ ca ];
  15167. customAttribute.array[ offset ] = value.x;
  15168. customAttribute.array[ offset + 1 ] = value.y;
  15169. customAttribute.array[ offset + 2 ] = value.z;
  15170. offset += 3;
  15171. }
  15172. }
  15173. } else if ( customAttribute.size === 4 ) {
  15174. for ( ca = 0; ca < cal; ca ++ ) {
  15175. value = customAttribute.value[ ca ];
  15176. customAttribute.array[ offset ] = value.x;
  15177. customAttribute.array[ offset + 1 ] = value.y;
  15178. customAttribute.array[ offset + 2 ] = value.z;
  15179. customAttribute.array[ offset + 3 ] = value.w;
  15180. offset += 4;
  15181. }
  15182. }
  15183. renderer.setDynamicArrayBuffer( customAttribute.buffer, customAttribute.array);
  15184. }
  15185. }
  15186. }
  15187. }
  15188. } );
  15189. /**
  15190. * @author szimek / https://github.com/szimek/
  15191. * @author alteredq / http://alteredqualia.com/
  15192. */
  15193. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15194. THREE.EventDispatcher.call( this );
  15195. this.width = width;
  15196. this.height = height;
  15197. options = options || {};
  15198. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15199. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15200. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15201. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15202. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15203. this.offset = new THREE.Vector2( 0, 0 );
  15204. this.repeat = new THREE.Vector2( 1, 1 );
  15205. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15206. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15207. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15208. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15209. this.generateMipmaps = true;
  15210. this.shareDepthFrom = null;
  15211. };
  15212. THREE.WebGLRenderTarget.prototype.clone = function() {
  15213. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15214. tmp.wrapS = this.wrapS;
  15215. tmp.wrapT = this.wrapT;
  15216. tmp.magFilter = this.magFilter;
  15217. tmp.minFilter = this.minFilter;
  15218. tmp.anisotropy = this.anisotropy;
  15219. tmp.offset.copy( this.offset );
  15220. tmp.repeat.copy( this.repeat );
  15221. tmp.format = this.format;
  15222. tmp.type = this.type;
  15223. tmp.depthBuffer = this.depthBuffer;
  15224. tmp.stencilBuffer = this.stencilBuffer;
  15225. tmp.generateMipmaps = this.generateMipmaps;
  15226. tmp.shareDepthFrom = this.shareDepthFrom;
  15227. return tmp;
  15228. };
  15229. THREE.WebGLRenderTarget.prototype.dispose = function () {
  15230. this.dispatchEvent( { type: 'dispose' } );
  15231. };
  15232. /**
  15233. * @author alteredq / http://alteredqualia.com
  15234. */
  15235. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15236. THREE.WebGLRenderTarget.call( this, width, height, options );
  15237. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15238. };
  15239. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15240. /**
  15241. * @author mrdoob / http://mrdoob.com/
  15242. */
  15243. THREE.RenderableVertex = function () {
  15244. this.positionWorld = new THREE.Vector3();
  15245. this.positionScreen = new THREE.Vector4();
  15246. this.visible = true;
  15247. };
  15248. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15249. this.positionWorld.copy( vertex.positionWorld );
  15250. this.positionScreen.copy( vertex.positionScreen );
  15251. };
  15252. /**
  15253. * @author mrdoob / http://mrdoob.com/
  15254. */
  15255. THREE.RenderableFace3 = function () {
  15256. this.v1 = new THREE.RenderableVertex();
  15257. this.v2 = new THREE.RenderableVertex();
  15258. this.v3 = new THREE.RenderableVertex();
  15259. this.centroidModel = new THREE.Vector3();
  15260. this.normalModel = new THREE.Vector3();
  15261. this.normalModelView = new THREE.Vector3();
  15262. this.vertexNormalsLength = 0;
  15263. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15264. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15265. this.color = null;
  15266. this.material = null;
  15267. this.uvs = [[]];
  15268. this.z = null;
  15269. };
  15270. /**
  15271. * @author mrdoob / http://mrdoob.com/
  15272. */
  15273. THREE.RenderableFace4 = function () {
  15274. this.v1 = new THREE.RenderableVertex();
  15275. this.v2 = new THREE.RenderableVertex();
  15276. this.v3 = new THREE.RenderableVertex();
  15277. this.v4 = new THREE.RenderableVertex();
  15278. this.centroidModel = new THREE.Vector3();
  15279. this.normalModel = new THREE.Vector3();
  15280. this.normalModelView = new THREE.Vector3();
  15281. this.vertexNormalsLength = 0;
  15282. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15283. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15284. this.color = null;
  15285. this.material = null;
  15286. this.uvs = [[]];
  15287. this.z = null;
  15288. };
  15289. /**
  15290. * @author mrdoob / http://mrdoob.com/
  15291. */
  15292. THREE.RenderableObject = function () {
  15293. this.object = null;
  15294. this.z = null;
  15295. };
  15296. /**
  15297. * @author mrdoob / http://mrdoob.com/
  15298. */
  15299. THREE.RenderableParticle = function () {
  15300. this.object = null;
  15301. this.x = null;
  15302. this.y = null;
  15303. this.z = null;
  15304. this.rotation = null;
  15305. this.scale = new THREE.Vector2();
  15306. this.material = null;
  15307. };
  15308. /**
  15309. * @author mrdoob / http://mrdoob.com/
  15310. */
  15311. THREE.RenderableLine = function () {
  15312. this.z = null;
  15313. this.v1 = new THREE.RenderableVertex();
  15314. this.v2 = new THREE.RenderableVertex();
  15315. this.material = null;
  15316. };
  15317. /**
  15318. * @author mrdoob / http://mrdoob.com/
  15319. * @author alteredq / http://alteredqualia.com/
  15320. */
  15321. THREE.GeometryUtils = {
  15322. // Merge two geometries or geometry and geometry from object (using object's transform)
  15323. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  15324. var matrix, normalMatrix,
  15325. vertexOffset = geometry1.vertices.length,
  15326. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15327. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15328. vertices1 = geometry1.vertices,
  15329. vertices2 = geometry2.vertices,
  15330. faces1 = geometry1.faces,
  15331. faces2 = geometry2.faces,
  15332. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15333. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15334. if ( object2 instanceof THREE.Mesh ) {
  15335. object2.matrixAutoUpdate && object2.updateMatrix();
  15336. matrix = object2.matrix;
  15337. normalMatrix = new THREE.Matrix3();
  15338. normalMatrix.getInverse( matrix );
  15339. normalMatrix.transpose();
  15340. }
  15341. // vertices
  15342. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15343. var vertex = vertices2[ i ];
  15344. var vertexCopy = vertex.clone();
  15345. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15346. vertices1.push( vertexCopy );
  15347. }
  15348. // faces
  15349. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15350. var face = faces2[ i ], faceCopy, normal, color,
  15351. faceVertexNormals = face.vertexNormals,
  15352. faceVertexColors = face.vertexColors;
  15353. if ( face instanceof THREE.Face3 ) {
  15354. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15355. } else if ( face instanceof THREE.Face4 ) {
  15356. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  15357. }
  15358. faceCopy.normal.copy( face.normal );
  15359. if ( normalMatrix ) {
  15360. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15361. }
  15362. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15363. normal = faceVertexNormals[ j ].clone();
  15364. if ( normalMatrix ) {
  15365. normal.applyMatrix3( normalMatrix ).normalize();
  15366. }
  15367. faceCopy.vertexNormals.push( normal );
  15368. }
  15369. faceCopy.color.copy( face.color );
  15370. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15371. color = faceVertexColors[ j ];
  15372. faceCopy.vertexColors.push( color.clone() );
  15373. }
  15374. faceCopy.materialIndex = face.materialIndex;
  15375. faceCopy.centroid.copy( face.centroid );
  15376. if ( matrix ) {
  15377. faceCopy.centroid.applyMatrix4( matrix );
  15378. }
  15379. faces1.push( faceCopy );
  15380. }
  15381. // uvs
  15382. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15383. var uv = uvs2[ i ], uvCopy = [];
  15384. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15385. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15386. }
  15387. uvs1.push( uvCopy );
  15388. }
  15389. },
  15390. removeMaterials: function ( geometry, materialIndexArray ) {
  15391. var materialIndexMap = {};
  15392. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  15393. materialIndexMap[ materialIndexArray[i] ] = true;
  15394. }
  15395. var face, newFaces = [];
  15396. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15397. face = geometry.faces[ i ];
  15398. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  15399. }
  15400. geometry.faces = newFaces;
  15401. },
  15402. // Get random point in triangle (via barycentric coordinates)
  15403. // (uniform distribution)
  15404. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15405. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  15406. var a, b, c,
  15407. point = new THREE.Vector3(),
  15408. tmp = THREE.GeometryUtils.__v1;
  15409. a = THREE.GeometryUtils.random();
  15410. b = THREE.GeometryUtils.random();
  15411. if ( ( a + b ) > 1 ) {
  15412. a = 1 - a;
  15413. b = 1 - b;
  15414. }
  15415. c = 1 - a - b;
  15416. point.copy( vectorA );
  15417. point.multiplyScalar( a );
  15418. tmp.copy( vectorB );
  15419. tmp.multiplyScalar( b );
  15420. point.add( tmp );
  15421. tmp.copy( vectorC );
  15422. tmp.multiplyScalar( c );
  15423. point.add( tmp );
  15424. return point;
  15425. },
  15426. // Get random point in face (triangle / quad)
  15427. // (uniform distribution)
  15428. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15429. var vA, vB, vC, vD;
  15430. if ( face instanceof THREE.Face3 ) {
  15431. vA = geometry.vertices[ face.a ];
  15432. vB = geometry.vertices[ face.b ];
  15433. vC = geometry.vertices[ face.c ];
  15434. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15435. } else if ( face instanceof THREE.Face4 ) {
  15436. vA = geometry.vertices[ face.a ];
  15437. vB = geometry.vertices[ face.b ];
  15438. vC = geometry.vertices[ face.c ];
  15439. vD = geometry.vertices[ face.d ];
  15440. var area1, area2;
  15441. if ( useCachedAreas ) {
  15442. if ( face._area1 && face._area2 ) {
  15443. area1 = face._area1;
  15444. area2 = face._area2;
  15445. } else {
  15446. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15447. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15448. face._area1 = area1;
  15449. face._area2 = area2;
  15450. }
  15451. } else {
  15452. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  15453. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15454. }
  15455. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  15456. if ( r < area1 ) {
  15457. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  15458. } else {
  15459. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  15460. }
  15461. }
  15462. },
  15463. // Get uniformly distributed random points in mesh
  15464. // - create array with cumulative sums of face areas
  15465. // - pick random number from 0 to total area
  15466. // - find corresponding place in area array by binary search
  15467. // - get random point in face
  15468. randomPointsInGeometry: function ( geometry, n ) {
  15469. var face, i,
  15470. faces = geometry.faces,
  15471. vertices = geometry.vertices,
  15472. il = faces.length,
  15473. totalArea = 0,
  15474. cumulativeAreas = [],
  15475. vA, vB, vC, vD;
  15476. // precompute face areas
  15477. for ( i = 0; i < il; i ++ ) {
  15478. face = faces[ i ];
  15479. if ( face instanceof THREE.Face3 ) {
  15480. vA = vertices[ face.a ];
  15481. vB = vertices[ face.b ];
  15482. vC = vertices[ face.c ];
  15483. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  15484. } else if ( face instanceof THREE.Face4 ) {
  15485. vA = vertices[ face.a ];
  15486. vB = vertices[ face.b ];
  15487. vC = vertices[ face.c ];
  15488. vD = vertices[ face.d ];
  15489. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15490. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15491. face._area = face._area1 + face._area2;
  15492. }
  15493. totalArea += face._area;
  15494. cumulativeAreas[ i ] = totalArea;
  15495. }
  15496. // binary search cumulative areas array
  15497. function binarySearchIndices( value ) {
  15498. function binarySearch( start, end ) {
  15499. // return closest larger index
  15500. // if exact number is not found
  15501. if ( end < start )
  15502. return start;
  15503. var mid = start + Math.floor( ( end - start ) / 2 );
  15504. if ( cumulativeAreas[ mid ] > value ) {
  15505. return binarySearch( start, mid - 1 );
  15506. } else if ( cumulativeAreas[ mid ] < value ) {
  15507. return binarySearch( mid + 1, end );
  15508. } else {
  15509. return mid;
  15510. }
  15511. }
  15512. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  15513. return result;
  15514. }
  15515. // pick random face weighted by face area
  15516. var r, index,
  15517. result = [];
  15518. var stats = {};
  15519. for ( i = 0; i < n; i ++ ) {
  15520. r = THREE.GeometryUtils.random() * totalArea;
  15521. index = binarySearchIndices( r );
  15522. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  15523. if ( ! stats[ index ] ) {
  15524. stats[ index ] = 1;
  15525. } else {
  15526. stats[ index ] += 1;
  15527. }
  15528. }
  15529. return result;
  15530. },
  15531. // Get triangle area (half of parallelogram)
  15532. // http://mathworld.wolfram.com/TriangleArea.html
  15533. triangleArea: function ( vectorA, vectorB, vectorC ) {
  15534. var tmp1 = THREE.GeometryUtils.__v1,
  15535. tmp2 = THREE.GeometryUtils.__v2;
  15536. tmp1.subVectors( vectorB, vectorA );
  15537. tmp2.subVectors( vectorC, vectorA );
  15538. tmp1.cross( tmp2 );
  15539. return 0.5 * tmp1.length();
  15540. },
  15541. // Center geometry so that 0,0,0 is in center of bounding box
  15542. center: function ( geometry ) {
  15543. geometry.computeBoundingBox();
  15544. var bb = geometry.boundingBox;
  15545. var offset = new THREE.Vector3();
  15546. offset.addVectors( bb.min, bb.max );
  15547. offset.multiplyScalar( -0.5 );
  15548. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  15549. geometry.computeBoundingBox();
  15550. return offset;
  15551. },
  15552. // Normalize UVs to be from <0,1>
  15553. // (for now just the first set of UVs)
  15554. normalizeUVs: function ( geometry ) {
  15555. var uvSet = geometry.faceVertexUvs[ 0 ];
  15556. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  15557. var uvs = uvSet[ i ];
  15558. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  15559. // texture repeat
  15560. if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
  15561. if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
  15562. }
  15563. }
  15564. },
  15565. triangulateQuads: function ( geometry ) {
  15566. var i, il, j, jl;
  15567. var faces = [];
  15568. var faceUvs = [];
  15569. var faceVertexUvs = [];
  15570. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  15571. faceUvs[ i ] = [];
  15572. }
  15573. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15574. faceVertexUvs[ i ] = [];
  15575. }
  15576. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15577. var face = geometry.faces[ i ];
  15578. if ( face instanceof THREE.Face4 ) {
  15579. var a = face.a;
  15580. var b = face.b;
  15581. var c = face.c;
  15582. var d = face.d;
  15583. var triA = new THREE.Face3();
  15584. var triB = new THREE.Face3();
  15585. triA.color.copy( face.color );
  15586. triB.color.copy( face.color );
  15587. triA.materialIndex = face.materialIndex;
  15588. triB.materialIndex = face.materialIndex;
  15589. triA.a = a;
  15590. triA.b = b;
  15591. triA.c = d;
  15592. triB.a = b;
  15593. triB.b = c;
  15594. triB.c = d;
  15595. if ( face.vertexColors.length === 4 ) {
  15596. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  15597. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  15598. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  15599. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  15600. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  15601. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  15602. }
  15603. faces.push( triA, triB );
  15604. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15605. if ( geometry.faceVertexUvs[ j ].length ) {
  15606. var uvs = geometry.faceVertexUvs[ j ][ i ];
  15607. var uvA = uvs[ 0 ];
  15608. var uvB = uvs[ 1 ];
  15609. var uvC = uvs[ 2 ];
  15610. var uvD = uvs[ 3 ];
  15611. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  15612. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  15613. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  15614. }
  15615. }
  15616. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15617. if ( geometry.faceUvs[ j ].length ) {
  15618. var faceUv = geometry.faceUvs[ j ][ i ];
  15619. faceUvs[ j ].push( faceUv, faceUv );
  15620. }
  15621. }
  15622. } else {
  15623. faces.push( face );
  15624. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15625. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  15626. }
  15627. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15628. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15629. }
  15630. }
  15631. }
  15632. geometry.faces = faces;
  15633. geometry.faceUvs = faceUvs;
  15634. geometry.faceVertexUvs = faceVertexUvs;
  15635. geometry.computeCentroids();
  15636. geometry.computeFaceNormals();
  15637. geometry.computeVertexNormals();
  15638. if ( geometry.hasTangents ) geometry.computeTangents();
  15639. },
  15640. setMaterialIndex: function ( geometry, index, startFace, endFace ){
  15641. var faces = geometry.faces;
  15642. var start = startFace || 0;
  15643. var end = endFace || faces.length - 1;
  15644. for ( var i = start; i <= end; i ++ ) {
  15645. faces[i].materialIndex = index;
  15646. }
  15647. }
  15648. };
  15649. THREE.GeometryUtils.random = THREE.Math.random16;
  15650. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  15651. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  15652. /**
  15653. * @author alteredq / http://alteredqualia.com/
  15654. * @author mrdoob / http://mrdoob.com/
  15655. */
  15656. THREE.ImageUtils = {
  15657. crossOrigin: 'anonymous',
  15658. loadTexture: function ( url, mapping, onLoad, onError ) {
  15659. var image = new Image();
  15660. var texture = new THREE.Texture( image, mapping );
  15661. var loader = new THREE.ImageLoader();
  15662. loader.addEventListener( 'load', function ( event ) {
  15663. texture.image = event.content;
  15664. texture.needsUpdate = true;
  15665. if ( onLoad ) onLoad( texture );
  15666. } );
  15667. loader.addEventListener( 'error', function ( event ) {
  15668. if ( onError ) onError( event.message );
  15669. } );
  15670. loader.crossOrigin = this.crossOrigin;
  15671. loader.load( url, image );
  15672. texture.sourceFile = url;
  15673. return texture;
  15674. },
  15675. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15676. var texture = new THREE.CompressedTexture();
  15677. texture.mapping = mapping;
  15678. var request = new XMLHttpRequest();
  15679. request.onload = function () {
  15680. var buffer = request.response;
  15681. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15682. texture.format = dds.format;
  15683. texture.mipmaps = dds.mipmaps;
  15684. texture.image.width = dds.width;
  15685. texture.image.height = dds.height;
  15686. // gl.generateMipmap fails for compressed textures
  15687. // mipmaps must be embedded in the DDS file
  15688. // or texture filters must not use mipmapping
  15689. texture.generateMipmaps = false;
  15690. texture.needsUpdate = true;
  15691. if ( onLoad ) onLoad( texture );
  15692. }
  15693. request.onerror = onError;
  15694. request.open( 'GET', url, true );
  15695. request.responseType = "arraybuffer";
  15696. request.send( null );
  15697. return texture;
  15698. },
  15699. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15700. var images = [];
  15701. images.loadCount = 0;
  15702. var texture = new THREE.Texture();
  15703. texture.image = images;
  15704. if ( mapping !== undefined ) texture.mapping = mapping;
  15705. // no flipping needed for cube textures
  15706. texture.flipY = false;
  15707. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15708. var cubeImage = new Image();
  15709. images[ i ] = cubeImage;
  15710. cubeImage.onload = function () {
  15711. images.loadCount += 1;
  15712. if ( images.loadCount === 6 ) {
  15713. texture.needsUpdate = true;
  15714. if ( onLoad ) onLoad( texture );
  15715. }
  15716. };
  15717. cubeImage.onerror = onError;
  15718. cubeImage.crossOrigin = this.crossOrigin;
  15719. cubeImage.src = array[ i ];
  15720. }
  15721. return texture;
  15722. },
  15723. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15724. var images = [];
  15725. images.loadCount = 0;
  15726. var texture = new THREE.CompressedTexture();
  15727. texture.image = images;
  15728. if ( mapping !== undefined ) texture.mapping = mapping;
  15729. // no flipping for cube textures
  15730. // (also flipping doesn't work for compressed textures )
  15731. texture.flipY = false;
  15732. // can't generate mipmaps for compressed textures
  15733. // mips must be embedded in DDS files
  15734. texture.generateMipmaps = false;
  15735. var generateCubeFaceCallback = function ( rq, img ) {
  15736. return function () {
  15737. var buffer = rq.response;
  15738. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15739. img.format = dds.format;
  15740. img.mipmaps = dds.mipmaps;
  15741. img.width = dds.width;
  15742. img.height = dds.height;
  15743. images.loadCount += 1;
  15744. if ( images.loadCount === 6 ) {
  15745. texture.format = dds.format;
  15746. texture.needsUpdate = true;
  15747. if ( onLoad ) onLoad( texture );
  15748. }
  15749. }
  15750. }
  15751. // compressed cubemap textures as 6 separate DDS files
  15752. if ( array instanceof Array ) {
  15753. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15754. var cubeImage = {};
  15755. images[ i ] = cubeImage;
  15756. var request = new XMLHttpRequest();
  15757. request.onload = generateCubeFaceCallback( request, cubeImage );
  15758. request.onerror = onError;
  15759. var url = array[ i ];
  15760. request.open( 'GET', url, true );
  15761. request.responseType = "arraybuffer";
  15762. request.send( null );
  15763. }
  15764. // compressed cubemap texture stored in a single DDS file
  15765. } else {
  15766. var url = array;
  15767. var request = new XMLHttpRequest();
  15768. request.onload = function( ) {
  15769. var buffer = request.response;
  15770. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15771. if ( dds.isCubemap ) {
  15772. var faces = dds.mipmaps.length / dds.mipmapCount;
  15773. for ( var f = 0; f < faces; f ++ ) {
  15774. images[ f ] = { mipmaps : [] };
  15775. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15776. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15777. images[ f ].format = dds.format;
  15778. images[ f ].width = dds.width;
  15779. images[ f ].height = dds.height;
  15780. }
  15781. }
  15782. texture.format = dds.format;
  15783. texture.needsUpdate = true;
  15784. if ( onLoad ) onLoad( texture );
  15785. }
  15786. }
  15787. request.onerror = onError;
  15788. request.open( 'GET', url, true );
  15789. request.responseType = "arraybuffer";
  15790. request.send( null );
  15791. }
  15792. return texture;
  15793. },
  15794. parseDDS: function ( buffer, loadMipmaps ) {
  15795. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15796. // Adapted from @toji's DDS utils
  15797. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15798. // All values and structures referenced from:
  15799. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15800. var DDS_MAGIC = 0x20534444;
  15801. var DDSD_CAPS = 0x1,
  15802. DDSD_HEIGHT = 0x2,
  15803. DDSD_WIDTH = 0x4,
  15804. DDSD_PITCH = 0x8,
  15805. DDSD_PIXELFORMAT = 0x1000,
  15806. DDSD_MIPMAPCOUNT = 0x20000,
  15807. DDSD_LINEARSIZE = 0x80000,
  15808. DDSD_DEPTH = 0x800000;
  15809. var DDSCAPS_COMPLEX = 0x8,
  15810. DDSCAPS_MIPMAP = 0x400000,
  15811. DDSCAPS_TEXTURE = 0x1000;
  15812. var DDSCAPS2_CUBEMAP = 0x200,
  15813. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15814. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15815. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15816. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15817. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15818. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15819. DDSCAPS2_VOLUME = 0x200000;
  15820. var DDPF_ALPHAPIXELS = 0x1,
  15821. DDPF_ALPHA = 0x2,
  15822. DDPF_FOURCC = 0x4,
  15823. DDPF_RGB = 0x40,
  15824. DDPF_YUV = 0x200,
  15825. DDPF_LUMINANCE = 0x20000;
  15826. function fourCCToInt32( value ) {
  15827. return value.charCodeAt(0) +
  15828. (value.charCodeAt(1) << 8) +
  15829. (value.charCodeAt(2) << 16) +
  15830. (value.charCodeAt(3) << 24);
  15831. }
  15832. function int32ToFourCC( value ) {
  15833. return String.fromCharCode(
  15834. value & 0xff,
  15835. (value >> 8) & 0xff,
  15836. (value >> 16) & 0xff,
  15837. (value >> 24) & 0xff
  15838. );
  15839. }
  15840. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15841. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15842. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15843. var headerLengthInt = 31; // The header length in 32 bit ints
  15844. // Offsets into the header array
  15845. var off_magic = 0;
  15846. var off_size = 1;
  15847. var off_flags = 2;
  15848. var off_height = 3;
  15849. var off_width = 4;
  15850. var off_mipmapCount = 7;
  15851. var off_pfFlags = 20;
  15852. var off_pfFourCC = 21;
  15853. var off_caps = 27;
  15854. var off_caps2 = 28;
  15855. var off_caps3 = 29;
  15856. var off_caps4 = 30;
  15857. // Parse header
  15858. var header = new Int32Array( buffer, 0, headerLengthInt );
  15859. if ( header[ off_magic ] !== DDS_MAGIC ) {
  15860. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  15861. return dds;
  15862. }
  15863. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  15864. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  15865. return dds;
  15866. }
  15867. var blockBytes;
  15868. var fourCC = header[ off_pfFourCC ];
  15869. switch ( fourCC ) {
  15870. case FOURCC_DXT1:
  15871. blockBytes = 8;
  15872. dds.format = THREE.RGB_S3TC_DXT1_Format;
  15873. break;
  15874. case FOURCC_DXT3:
  15875. blockBytes = 16;
  15876. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  15877. break;
  15878. case FOURCC_DXT5:
  15879. blockBytes = 16;
  15880. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  15881. break;
  15882. default:
  15883. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  15884. return dds;
  15885. }
  15886. dds.mipmapCount = 1;
  15887. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  15888. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  15889. }
  15890. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  15891. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  15892. dds.width = header[ off_width ];
  15893. dds.height = header[ off_height ];
  15894. var dataOffset = header[ off_size ] + 4;
  15895. // Extract mipmaps buffers
  15896. var width = dds.width;
  15897. var height = dds.height;
  15898. var faces = dds.isCubemap ? 6 : 1;
  15899. for ( var face = 0; face < faces; face ++ ) {
  15900. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15901. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  15902. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  15903. var mipmap = { "data": byteArray, "width": width, "height": height };
  15904. dds.mipmaps.push( mipmap );
  15905. dataOffset += dataLength;
  15906. width = Math.max( width * 0.5, 1 );
  15907. height = Math.max( height * 0.5, 1 );
  15908. }
  15909. width = dds.width;
  15910. height = dds.height;
  15911. }
  15912. return dds;
  15913. },
  15914. getNormalMap: function ( image, depth ) {
  15915. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  15916. var cross = function ( a, b ) {
  15917. 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 ] ];
  15918. }
  15919. var subtract = function ( a, b ) {
  15920. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  15921. }
  15922. var normalize = function ( a ) {
  15923. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  15924. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  15925. }
  15926. depth = depth | 1;
  15927. var width = image.width;
  15928. var height = image.height;
  15929. var canvas = document.createElement( 'canvas' );
  15930. canvas.width = width;
  15931. canvas.height = height;
  15932. var context = canvas.getContext( '2d' );
  15933. context.drawImage( image, 0, 0 );
  15934. var data = context.getImageData( 0, 0, width, height ).data;
  15935. var imageData = context.createImageData( width, height );
  15936. var output = imageData.data;
  15937. for ( var x = 0; x < width; x ++ ) {
  15938. for ( var y = 0; y < height; y ++ ) {
  15939. var ly = y - 1 < 0 ? 0 : y - 1;
  15940. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  15941. var lx = x - 1 < 0 ? 0 : x - 1;
  15942. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  15943. var points = [];
  15944. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  15945. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  15946. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  15947. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  15948. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  15949. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  15950. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  15951. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  15952. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  15953. var normals = [];
  15954. var num_points = points.length;
  15955. for ( var i = 0; i < num_points; i ++ ) {
  15956. var v1 = points[ i ];
  15957. var v2 = points[ ( i + 1 ) % num_points ];
  15958. v1 = subtract( v1, origin );
  15959. v2 = subtract( v2, origin );
  15960. normals.push( normalize( cross( v1, v2 ) ) );
  15961. }
  15962. var normal = [ 0, 0, 0 ];
  15963. for ( var i = 0; i < normals.length; i ++ ) {
  15964. normal[ 0 ] += normals[ i ][ 0 ];
  15965. normal[ 1 ] += normals[ i ][ 1 ];
  15966. normal[ 2 ] += normals[ i ][ 2 ];
  15967. }
  15968. normal[ 0 ] /= normals.length;
  15969. normal[ 1 ] /= normals.length;
  15970. normal[ 2 ] /= normals.length;
  15971. var idx = ( y * width + x ) * 4;
  15972. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15973. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15974. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  15975. output[ idx + 3 ] = 255;
  15976. }
  15977. }
  15978. context.putImageData( imageData, 0, 0 );
  15979. return canvas;
  15980. },
  15981. generateDataTexture: function ( width, height, color ) {
  15982. var size = width * height;
  15983. var data = new Uint8Array( 3 * size );
  15984. var r = Math.floor( color.r * 255 );
  15985. var g = Math.floor( color.g * 255 );
  15986. var b = Math.floor( color.b * 255 );
  15987. for ( var i = 0; i < size; i ++ ) {
  15988. data[ i * 3 ] = r;
  15989. data[ i * 3 + 1 ] = g;
  15990. data[ i * 3 + 2 ] = b;
  15991. }
  15992. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  15993. texture.needsUpdate = true;
  15994. return texture;
  15995. }
  15996. };
  15997. /**
  15998. * @author alteredq / http://alteredqualia.com/
  15999. */
  16000. THREE.SceneUtils = {
  16001. createMultiMaterialObject: function ( geometry, materials ) {
  16002. var group = new THREE.Object3D();
  16003. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16004. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16005. }
  16006. return group;
  16007. },
  16008. detach : function ( child, parent, scene ) {
  16009. child.applyMatrix( parent.matrixWorld );
  16010. parent.remove( child );
  16011. scene.add( child );
  16012. },
  16013. attach: function ( child, scene, parent ) {
  16014. var matrixWorldInverse = new THREE.Matrix4();
  16015. matrixWorldInverse.getInverse( parent.matrixWorld );
  16016. child.applyMatrix( matrixWorldInverse );
  16017. scene.remove( child );
  16018. parent.add( child );
  16019. }
  16020. };
  16021. /**
  16022. * @author zz85 / http://www.lab4games.net/zz85/blog
  16023. * @author alteredq / http://alteredqualia.com/
  16024. *
  16025. * For Text operations in three.js (See TextGeometry)
  16026. *
  16027. * It uses techniques used in:
  16028. *
  16029. * typeface.js and canvastext
  16030. * For converting fonts and rendering with javascript
  16031. * http://typeface.neocracy.org
  16032. *
  16033. * Triangulation ported from AS3
  16034. * Simple Polygon Triangulation
  16035. * http://actionsnippet.com/?p=1462
  16036. *
  16037. * A Method to triangulate shapes with holes
  16038. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16039. *
  16040. */
  16041. THREE.FontUtils = {
  16042. faces : {},
  16043. // Just for now. face[weight][style]
  16044. face : "helvetiker",
  16045. weight: "normal",
  16046. style : "normal",
  16047. size : 150,
  16048. divisions : 10,
  16049. getFace : function() {
  16050. return this.faces[ this.face ][ this.weight ][ this.style ];
  16051. },
  16052. loadFace : function( data ) {
  16053. var family = data.familyName.toLowerCase();
  16054. var ThreeFont = this;
  16055. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16056. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16057. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16058. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16059. return data;
  16060. },
  16061. drawText : function( text ) {
  16062. var characterPts = [], allPts = [];
  16063. // RenderText
  16064. var i, p,
  16065. face = this.getFace(),
  16066. scale = this.size / face.resolution,
  16067. offset = 0,
  16068. chars = String( text ).split( '' ),
  16069. length = chars.length;
  16070. var fontPaths = [];
  16071. for ( i = 0; i < length; i ++ ) {
  16072. var path = new THREE.Path();
  16073. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16074. offset += ret.offset;
  16075. fontPaths.push( ret.path );
  16076. }
  16077. // get the width
  16078. var width = offset / 2;
  16079. //
  16080. // for ( p = 0; p < allPts.length; p++ ) {
  16081. //
  16082. // allPts[ p ].x -= width;
  16083. //
  16084. // }
  16085. //var extract = this.extractPoints( allPts, characterPts );
  16086. //extract.contour = allPts;
  16087. //extract.paths = fontPaths;
  16088. //extract.offset = width;
  16089. return { paths : fontPaths, offset : width };
  16090. },
  16091. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16092. var pts = [];
  16093. var i, i2, divisions,
  16094. outline, action, length,
  16095. scaleX, scaleY,
  16096. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16097. laste,
  16098. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16099. if ( !glyph ) return;
  16100. if ( glyph.o ) {
  16101. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16102. length = outline.length;
  16103. scaleX = scale;
  16104. scaleY = scale;
  16105. for ( i = 0; i < length; ) {
  16106. action = outline[ i ++ ];
  16107. //console.log( action );
  16108. switch( action ) {
  16109. case 'm':
  16110. // Move To
  16111. x = outline[ i++ ] * scaleX + offset;
  16112. y = outline[ i++ ] * scaleY;
  16113. path.moveTo( x, y );
  16114. break;
  16115. case 'l':
  16116. // Line To
  16117. x = outline[ i++ ] * scaleX + offset;
  16118. y = outline[ i++ ] * scaleY;
  16119. path.lineTo(x,y);
  16120. break;
  16121. case 'q':
  16122. // QuadraticCurveTo
  16123. cpx = outline[ i++ ] * scaleX + offset;
  16124. cpy = outline[ i++ ] * scaleY;
  16125. cpx1 = outline[ i++ ] * scaleX + offset;
  16126. cpy1 = outline[ i++ ] * scaleY;
  16127. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16128. laste = pts[ pts.length - 1 ];
  16129. if ( laste ) {
  16130. cpx0 = laste.x;
  16131. cpy0 = laste.y;
  16132. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16133. var t = i2 / divisions;
  16134. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16135. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16136. }
  16137. }
  16138. break;
  16139. case 'b':
  16140. // Cubic Bezier Curve
  16141. cpx = outline[ i++ ] * scaleX + offset;
  16142. cpy = outline[ i++ ] * scaleY;
  16143. cpx1 = outline[ i++ ] * scaleX + offset;
  16144. cpy1 = outline[ i++ ] * -scaleY;
  16145. cpx2 = outline[ i++ ] * scaleX + offset;
  16146. cpy2 = outline[ i++ ] * -scaleY;
  16147. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16148. laste = pts[ pts.length - 1 ];
  16149. if ( laste ) {
  16150. cpx0 = laste.x;
  16151. cpy0 = laste.y;
  16152. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16153. var t = i2 / divisions;
  16154. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16155. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16156. }
  16157. }
  16158. break;
  16159. }
  16160. }
  16161. }
  16162. return { offset: glyph.ha*scale, path:path};
  16163. }
  16164. };
  16165. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16166. // Parameters
  16167. parameters = parameters || {};
  16168. var size = parameters.size !== undefined ? parameters.size : 100;
  16169. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16170. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16171. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16172. var style = parameters.style !== undefined ? parameters.style : "normal";
  16173. THREE.FontUtils.size = size;
  16174. THREE.FontUtils.divisions = curveSegments;
  16175. THREE.FontUtils.face = font;
  16176. THREE.FontUtils.weight = weight;
  16177. THREE.FontUtils.style = style;
  16178. // Get a Font data json object
  16179. var data = THREE.FontUtils.drawText( text );
  16180. var paths = data.paths;
  16181. var shapes = [];
  16182. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16183. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16184. }
  16185. return shapes;
  16186. };
  16187. /**
  16188. * This code is a quick port of code written in C++ which was submitted to
  16189. * flipcode.com by John W. Ratcliff // July 22, 2000
  16190. * See original code and more information here:
  16191. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16192. *
  16193. * ported to actionscript by Zevan Rosser
  16194. * www.actionsnippet.com
  16195. *
  16196. * ported to javascript by Joshua Koo
  16197. * http://www.lab4games.net/zz85/blog
  16198. *
  16199. */
  16200. ( function( namespace ) {
  16201. var EPSILON = 0.0000000001;
  16202. // takes in an contour array and returns
  16203. var process = function( contour, indices ) {
  16204. var n = contour.length;
  16205. if ( n < 3 ) return null;
  16206. var result = [],
  16207. verts = [],
  16208. vertIndices = [];
  16209. /* we want a counter-clockwise polygon in verts */
  16210. var u, v, w;
  16211. if ( area( contour ) > 0.0 ) {
  16212. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16213. } else {
  16214. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16215. }
  16216. var nv = n;
  16217. /* remove nv - 2 vertices, creating 1 triangle every time */
  16218. var count = 2 * nv; /* error detection */
  16219. for( v = nv - 1; nv > 2; ) {
  16220. /* if we loop, it is probably a non-simple polygon */
  16221. if ( ( count-- ) <= 0 ) {
  16222. //** Triangulate: ERROR - probable bad polygon!
  16223. //throw ( "Warning, unable to triangulate polygon!" );
  16224. //return null;
  16225. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16226. console.log( "Warning, unable to triangulate polygon!" );
  16227. if ( indices ) return vertIndices;
  16228. return result;
  16229. }
  16230. /* three consecutive vertices in current polygon, <u,v,w> */
  16231. u = v; if ( nv <= u ) u = 0; /* previous */
  16232. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16233. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16234. if ( snip( contour, u, v, w, nv, verts ) ) {
  16235. var a, b, c, s, t;
  16236. /* true names of the vertices */
  16237. a = verts[ u ];
  16238. b = verts[ v ];
  16239. c = verts[ w ];
  16240. /* output Triangle */
  16241. result.push( [ contour[ a ],
  16242. contour[ b ],
  16243. contour[ c ] ] );
  16244. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16245. /* remove v from the remaining polygon */
  16246. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16247. verts[ s ] = verts[ t ];
  16248. }
  16249. nv--;
  16250. /* reset error detection counter */
  16251. count = 2 * nv;
  16252. }
  16253. }
  16254. if ( indices ) return vertIndices;
  16255. return result;
  16256. };
  16257. // calculate area of the contour polygon
  16258. var area = function ( contour ) {
  16259. var n = contour.length;
  16260. var a = 0.0;
  16261. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16262. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16263. }
  16264. return a * 0.5;
  16265. };
  16266. var snip = function ( contour, u, v, w, n, verts ) {
  16267. var p;
  16268. var ax, ay, bx, by;
  16269. var cx, cy, px, py;
  16270. ax = contour[ verts[ u ] ].x;
  16271. ay = contour[ verts[ u ] ].y;
  16272. bx = contour[ verts[ v ] ].x;
  16273. by = contour[ verts[ v ] ].y;
  16274. cx = contour[ verts[ w ] ].x;
  16275. cy = contour[ verts[ w ] ].y;
  16276. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16277. var aX, aY, bX, bY, cX, cY;
  16278. var apx, apy, bpx, bpy, cpx, cpy;
  16279. var cCROSSap, bCROSScp, aCROSSbp;
  16280. aX = cx - bx; aY = cy - by;
  16281. bX = ax - cx; bY = ay - cy;
  16282. cX = bx - ax; cY = by - ay;
  16283. for ( p = 0; p < n; p++ ) {
  16284. if( (p === u) || (p === v) || (p === w) ) continue;
  16285. px = contour[ verts[ p ] ].x
  16286. py = contour[ verts[ p ] ].y
  16287. apx = px - ax; apy = py - ay;
  16288. bpx = px - bx; bpy = py - by;
  16289. cpx = px - cx; cpy = py - cy;
  16290. // see if p is inside triangle abc
  16291. aCROSSbp = aX*bpy - aY*bpx;
  16292. cCROSSap = cX*apy - cY*apx;
  16293. bCROSScp = bX*cpy - bY*cpx;
  16294. if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
  16295. }
  16296. return true;
  16297. };
  16298. namespace.Triangulate = process;
  16299. namespace.Triangulate.area = area;
  16300. return namespace;
  16301. })(THREE.FontUtils);
  16302. // To use the typeface.js face files, hook up the API
  16303. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  16304. * @author zz85 / http://www.lab4games.net/zz85/blog
  16305. * Extensible curve object
  16306. *
  16307. * Some common of Curve methods
  16308. * .getPoint(t), getTangent(t)
  16309. * .getPointAt(u), getTagentAt(u)
  16310. * .getPoints(), .getSpacedPoints()
  16311. * .getLength()
  16312. * .updateArcLengths()
  16313. *
  16314. * This file contains following classes:
  16315. *
  16316. * -- 2d classes --
  16317. * THREE.Curve
  16318. * THREE.LineCurve
  16319. * THREE.QuadraticBezierCurve
  16320. * THREE.CubicBezierCurve
  16321. * THREE.SplineCurve
  16322. * THREE.ArcCurve
  16323. * THREE.EllipseCurve
  16324. *
  16325. * -- 3d classes --
  16326. * THREE.LineCurve3
  16327. * THREE.QuadraticBezierCurve3
  16328. * THREE.CubicBezierCurve3
  16329. * THREE.SplineCurve3
  16330. * THREE.ClosedSplineCurve3
  16331. *
  16332. * A series of curves can be represented as a THREE.CurvePath
  16333. *
  16334. **/
  16335. /**************************************************************
  16336. * Abstract Curve base class
  16337. **************************************************************/
  16338. THREE.Curve = function () {
  16339. };
  16340. // Virtual base class method to overwrite and implement in subclasses
  16341. // - t [0 .. 1]
  16342. THREE.Curve.prototype.getPoint = function ( t ) {
  16343. console.log( "Warning, getPoint() not implemented!" );
  16344. return null;
  16345. };
  16346. // Get point at relative position in curve according to arc length
  16347. // - u [0 .. 1]
  16348. THREE.Curve.prototype.getPointAt = function ( u ) {
  16349. var t = this.getUtoTmapping( u );
  16350. return this.getPoint( t );
  16351. };
  16352. // Get sequence of points using getPoint( t )
  16353. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16354. if ( !divisions ) divisions = 5;
  16355. var d, pts = [];
  16356. for ( d = 0; d <= divisions; d ++ ) {
  16357. pts.push( this.getPoint( d / divisions ) );
  16358. }
  16359. return pts;
  16360. };
  16361. // Get sequence of points using getPointAt( u )
  16362. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16363. if ( !divisions ) divisions = 5;
  16364. var d, pts = [];
  16365. for ( d = 0; d <= divisions; d ++ ) {
  16366. pts.push( this.getPointAt( d / divisions ) );
  16367. }
  16368. return pts;
  16369. };
  16370. // Get total curve arc length
  16371. THREE.Curve.prototype.getLength = function () {
  16372. var lengths = this.getLengths();
  16373. return lengths[ lengths.length - 1 ];
  16374. };
  16375. // Get list of cumulative segment lengths
  16376. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16377. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16378. if ( this.cacheArcLengths
  16379. && ( this.cacheArcLengths.length == divisions + 1 )
  16380. && !this.needsUpdate) {
  16381. //console.log( "cached", this.cacheArcLengths );
  16382. return this.cacheArcLengths;
  16383. }
  16384. this.needsUpdate = false;
  16385. var cache = [];
  16386. var current, last = this.getPoint( 0 );
  16387. var p, sum = 0;
  16388. cache.push( 0 );
  16389. for ( p = 1; p <= divisions; p ++ ) {
  16390. current = this.getPoint ( p / divisions );
  16391. sum += current.distanceTo( last );
  16392. cache.push( sum );
  16393. last = current;
  16394. }
  16395. this.cacheArcLengths = cache;
  16396. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16397. };
  16398. THREE.Curve.prototype.updateArcLengths = function() {
  16399. this.needsUpdate = true;
  16400. this.getLengths();
  16401. };
  16402. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16403. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16404. var arcLengths = this.getLengths();
  16405. var i = 0, il = arcLengths.length;
  16406. var targetArcLength; // The targeted u distance value to get
  16407. if ( distance ) {
  16408. targetArcLength = distance;
  16409. } else {
  16410. targetArcLength = u * arcLengths[ il - 1 ];
  16411. }
  16412. //var time = Date.now();
  16413. // binary search for the index with largest value smaller than target u distance
  16414. var low = 0, high = il - 1, comparison;
  16415. while ( low <= high ) {
  16416. 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
  16417. comparison = arcLengths[ i ] - targetArcLength;
  16418. if ( comparison < 0 ) {
  16419. low = i + 1;
  16420. continue;
  16421. } else if ( comparison > 0 ) {
  16422. high = i - 1;
  16423. continue;
  16424. } else {
  16425. high = i;
  16426. break;
  16427. // DONE
  16428. }
  16429. }
  16430. i = high;
  16431. //console.log('b' , i, low, high, Date.now()- time);
  16432. if ( arcLengths[ i ] == targetArcLength ) {
  16433. var t = i / ( il - 1 );
  16434. return t;
  16435. }
  16436. // we could get finer grain at lengths, or use simple interpolatation between two points
  16437. var lengthBefore = arcLengths[ i ];
  16438. var lengthAfter = arcLengths[ i + 1 ];
  16439. var segmentLength = lengthAfter - lengthBefore;
  16440. // determine where we are between the 'before' and 'after' points
  16441. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16442. // add that fractional amount to t
  16443. var t = ( i + segmentFraction ) / ( il -1 );
  16444. return t;
  16445. };
  16446. // Returns a unit vector tangent at t
  16447. // In case any sub curve does not implement its tangent derivation,
  16448. // 2 points a small delta apart will be used to find its gradient
  16449. // which seems to give a reasonable approximation
  16450. THREE.Curve.prototype.getTangent = function( t ) {
  16451. var delta = 0.0001;
  16452. var t1 = t - delta;
  16453. var t2 = t + delta;
  16454. // Capping in case of danger
  16455. if ( t1 < 0 ) t1 = 0;
  16456. if ( t2 > 1 ) t2 = 1;
  16457. var pt1 = this.getPoint( t1 );
  16458. var pt2 = this.getPoint( t2 );
  16459. var vec = pt2.clone().sub(pt1);
  16460. return vec.normalize();
  16461. };
  16462. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16463. var t = this.getUtoTmapping( u );
  16464. return this.getTangent( t );
  16465. };
  16466. /**************************************************************
  16467. * Line
  16468. **************************************************************/
  16469. THREE.LineCurve = function ( v1, v2 ) {
  16470. this.v1 = v1;
  16471. this.v2 = v2;
  16472. };
  16473. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  16474. THREE.LineCurve.prototype.getPoint = function ( t ) {
  16475. var point = this.v2.clone().sub(this.v1);
  16476. point.multiplyScalar( t ).add( this.v1 );
  16477. return point;
  16478. };
  16479. // Line curve is linear, so we can overwrite default getPointAt
  16480. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  16481. return this.getPoint( u );
  16482. };
  16483. THREE.LineCurve.prototype.getTangent = function( t ) {
  16484. var tangent = this.v2.clone().sub(this.v1);
  16485. return tangent.normalize();
  16486. };
  16487. /**************************************************************
  16488. * Quadratic Bezier curve
  16489. **************************************************************/
  16490. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  16491. this.v0 = v0;
  16492. this.v1 = v1;
  16493. this.v2 = v2;
  16494. };
  16495. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16496. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  16497. var tx, ty;
  16498. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16499. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16500. return new THREE.Vector2( tx, ty );
  16501. };
  16502. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  16503. var tx, ty;
  16504. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  16505. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  16506. // returns unit vector
  16507. var tangent = new THREE.Vector2( tx, ty );
  16508. tangent.normalize();
  16509. return tangent;
  16510. };
  16511. /**************************************************************
  16512. * Cubic Bezier curve
  16513. **************************************************************/
  16514. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  16515. this.v0 = v0;
  16516. this.v1 = v1;
  16517. this.v2 = v2;
  16518. this.v3 = v3;
  16519. };
  16520. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16521. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  16522. var tx, ty;
  16523. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16524. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16525. return new THREE.Vector2( tx, ty );
  16526. };
  16527. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  16528. var tx, ty;
  16529. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16530. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16531. var tangent = new THREE.Vector2( tx, ty );
  16532. tangent.normalize();
  16533. return tangent;
  16534. };
  16535. /**************************************************************
  16536. * Spline curve
  16537. **************************************************************/
  16538. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  16539. this.points = (points == undefined) ? [] : points;
  16540. };
  16541. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  16542. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  16543. var v = new THREE.Vector2();
  16544. var c = [];
  16545. var points = this.points, point, intPoint, weight;
  16546. point = ( points.length - 1 ) * t;
  16547. intPoint = Math.floor( point );
  16548. weight = point - intPoint;
  16549. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16550. c[ 1 ] = intPoint;
  16551. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  16552. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  16553. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16554. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16555. return v;
  16556. };
  16557. /**************************************************************
  16558. * Ellipse curve
  16559. **************************************************************/
  16560. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  16561. aStartAngle, aEndAngle,
  16562. aClockwise ) {
  16563. this.aX = aX;
  16564. this.aY = aY;
  16565. this.xRadius = xRadius;
  16566. this.yRadius = yRadius;
  16567. this.aStartAngle = aStartAngle;
  16568. this.aEndAngle = aEndAngle;
  16569. this.aClockwise = aClockwise;
  16570. };
  16571. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  16572. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  16573. var deltaAngle = this.aEndAngle - this.aStartAngle;
  16574. if ( !this.aClockwise ) {
  16575. t = 1 - t;
  16576. }
  16577. var angle = this.aStartAngle + t * deltaAngle;
  16578. var tx = this.aX + this.xRadius * Math.cos( angle );
  16579. var ty = this.aY + this.yRadius * Math.sin( angle );
  16580. return new THREE.Vector2( tx, ty );
  16581. };
  16582. /**************************************************************
  16583. * Arc curve
  16584. **************************************************************/
  16585. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  16586. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  16587. };
  16588. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  16589. /**************************************************************
  16590. * Utils
  16591. **************************************************************/
  16592. THREE.Curve.Utils = {
  16593. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16594. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16595. },
  16596. // Puay Bing, thanks for helping with this derivative!
  16597. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16598. return -3 * p0 * (1 - t) * (1 - t) +
  16599. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16600. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16601. 3 * t * t * p3;
  16602. },
  16603. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16604. // To check if my formulas are correct
  16605. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16606. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16607. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16608. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16609. return h00 + h10 + h01 + h11;
  16610. },
  16611. // Catmull-Rom
  16612. interpolate: function( p0, p1, p2, p3, t ) {
  16613. var v0 = ( p2 - p0 ) * 0.5;
  16614. var v1 = ( p3 - p1 ) * 0.5;
  16615. var t2 = t * t;
  16616. var t3 = t * t2;
  16617. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16618. }
  16619. };
  16620. // TODO: Transformation for Curves?
  16621. /**************************************************************
  16622. * 3D Curves
  16623. **************************************************************/
  16624. // A Factory method for creating new curve subclasses
  16625. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16626. constructor.prototype = Object.create( THREE.Curve.prototype );
  16627. constructor.prototype.getPoint = getPointFunc;
  16628. return constructor;
  16629. };
  16630. /**************************************************************
  16631. * Line3D
  16632. **************************************************************/
  16633. THREE.LineCurve3 = THREE.Curve.create(
  16634. function ( v1, v2 ) {
  16635. this.v1 = v1;
  16636. this.v2 = v2;
  16637. },
  16638. function ( t ) {
  16639. var r = new THREE.Vector3();
  16640. r.subVectors( this.v2, this.v1 ); // diff
  16641. r.multiplyScalar( t );
  16642. r.add( this.v1 );
  16643. return r;
  16644. }
  16645. );
  16646. /**************************************************************
  16647. * Quadratic Bezier 3D curve
  16648. **************************************************************/
  16649. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  16650. function ( v0, v1, v2 ) {
  16651. this.v0 = v0;
  16652. this.v1 = v1;
  16653. this.v2 = v2;
  16654. },
  16655. function ( t ) {
  16656. var tx, ty, tz;
  16657. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16658. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16659. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  16660. return new THREE.Vector3( tx, ty, tz );
  16661. }
  16662. );
  16663. /**************************************************************
  16664. * Cubic Bezier 3D curve
  16665. **************************************************************/
  16666. THREE.CubicBezierCurve3 = THREE.Curve.create(
  16667. function ( v0, v1, v2, v3 ) {
  16668. this.v0 = v0;
  16669. this.v1 = v1;
  16670. this.v2 = v2;
  16671. this.v3 = v3;
  16672. },
  16673. function ( t ) {
  16674. var tx, ty, tz;
  16675. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16676. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16677. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  16678. return new THREE.Vector3( tx, ty, tz );
  16679. }
  16680. );
  16681. /**************************************************************
  16682. * Spline 3D curve
  16683. **************************************************************/
  16684. THREE.SplineCurve3 = THREE.Curve.create(
  16685. function ( points /* array of Vector3 */) {
  16686. this.points = (points == undefined) ? [] : points;
  16687. },
  16688. function ( t ) {
  16689. var v = new THREE.Vector3();
  16690. var c = [];
  16691. var points = this.points, point, intPoint, weight;
  16692. point = ( points.length - 1 ) * t;
  16693. intPoint = Math.floor( point );
  16694. weight = point - intPoint;
  16695. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16696. c[ 1 ] = intPoint;
  16697. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16698. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16699. var pt0 = points[ c[0] ],
  16700. pt1 = points[ c[1] ],
  16701. pt2 = points[ c[2] ],
  16702. pt3 = points[ c[3] ];
  16703. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  16704. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  16705. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  16706. return v;
  16707. }
  16708. );
  16709. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  16710. // var v = new THREE.Vector3();
  16711. // var c = [];
  16712. // var points = this.points, point, intPoint, weight;
  16713. // point = ( points.length - 1 ) * t;
  16714. // intPoint = Math.floor( point );
  16715. // weight = point - intPoint;
  16716. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16717. // c[ 1 ] = intPoint;
  16718. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16719. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16720. // var pt0 = points[ c[0] ],
  16721. // pt1 = points[ c[1] ],
  16722. // pt2 = points[ c[2] ],
  16723. // pt3 = points[ c[3] ];
  16724. // // t = weight;
  16725. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  16726. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  16727. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  16728. // return v;
  16729. // }
  16730. /**************************************************************
  16731. * Closed Spline 3D curve
  16732. **************************************************************/
  16733. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  16734. function ( points /* array of Vector3 */) {
  16735. this.points = (points == undefined) ? [] : points;
  16736. },
  16737. function ( t ) {
  16738. var v = new THREE.Vector3();
  16739. var c = [];
  16740. var points = this.points, point, intPoint, weight;
  16741. point = ( points.length - 0 ) * t;
  16742. // This needs to be from 0-length +1
  16743. intPoint = Math.floor( point );
  16744. weight = point - intPoint;
  16745. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  16746. c[ 0 ] = ( intPoint - 1 ) % points.length;
  16747. c[ 1 ] = ( intPoint ) % points.length;
  16748. c[ 2 ] = ( intPoint + 1 ) % points.length;
  16749. c[ 3 ] = ( intPoint + 2 ) % points.length;
  16750. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16751. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16752. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  16753. return v;
  16754. }
  16755. );
  16756. /**
  16757. * @author zz85 / http://www.lab4games.net/zz85/blog
  16758. *
  16759. **/
  16760. /**************************************************************
  16761. * Curved Path - a curve path is simply a array of connected
  16762. * curves, but retains the api of a curve
  16763. **************************************************************/
  16764. THREE.CurvePath = function () {
  16765. this.curves = [];
  16766. this.bends = [];
  16767. this.autoClose = false; // Automatically closes the path
  16768. };
  16769. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16770. THREE.CurvePath.prototype.add = function ( curve ) {
  16771. this.curves.push( curve );
  16772. };
  16773. THREE.CurvePath.prototype.checkConnection = function() {
  16774. // TODO
  16775. // If the ending of curve is not connected to the starting
  16776. // or the next curve, then, this is not a real path
  16777. };
  16778. THREE.CurvePath.prototype.closePath = function() {
  16779. // TODO Test
  16780. // and verify for vector3 (needs to implement equals)
  16781. // Add a line curve if start and end of lines are not connected
  16782. var startPoint = this.curves[0].getPoint(0);
  16783. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16784. if (!startPoint.equals(endPoint)) {
  16785. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16786. }
  16787. };
  16788. // To get accurate point with reference to
  16789. // entire path distance at time t,
  16790. // following has to be done:
  16791. // 1. Length of each sub path have to be known
  16792. // 2. Locate and identify type of curve
  16793. // 3. Get t for the curve
  16794. // 4. Return curve.getPointAt(t')
  16795. THREE.CurvePath.prototype.getPoint = function( t ) {
  16796. var d = t * this.getLength();
  16797. var curveLengths = this.getCurveLengths();
  16798. var i = 0, diff, curve;
  16799. // To think about boundaries points.
  16800. while ( i < curveLengths.length ) {
  16801. if ( curveLengths[ i ] >= d ) {
  16802. diff = curveLengths[ i ] - d;
  16803. curve = this.curves[ i ];
  16804. var u = 1 - diff / curve.getLength();
  16805. return curve.getPointAt( u );
  16806. break;
  16807. }
  16808. i ++;
  16809. }
  16810. return null;
  16811. // loop where sum != 0, sum > d , sum+1 <d
  16812. };
  16813. /*
  16814. THREE.CurvePath.prototype.getTangent = function( t ) {
  16815. };*/
  16816. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16817. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16818. // getPoint() depends on getLength
  16819. THREE.CurvePath.prototype.getLength = function() {
  16820. var lens = this.getCurveLengths();
  16821. return lens[ lens.length - 1 ];
  16822. };
  16823. // Compute lengths and cache them
  16824. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16825. THREE.CurvePath.prototype.getCurveLengths = function() {
  16826. // We use cache values if curves and cache array are same length
  16827. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16828. return this.cacheLengths;
  16829. };
  16830. // Get length of subsurve
  16831. // Push sums into cached array
  16832. var lengths = [], sums = 0;
  16833. var i, il = this.curves.length;
  16834. for ( i = 0; i < il; i ++ ) {
  16835. sums += this.curves[ i ].getLength();
  16836. lengths.push( sums );
  16837. }
  16838. this.cacheLengths = lengths;
  16839. return lengths;
  16840. };
  16841. // Returns min and max coordinates, as well as centroid
  16842. THREE.CurvePath.prototype.getBoundingBox = function () {
  16843. var points = this.getPoints();
  16844. var maxX, maxY, maxZ;
  16845. var minX, minY, minZ;
  16846. maxX = maxY = Number.NEGATIVE_INFINITY;
  16847. minX = minY = Number.POSITIVE_INFINITY;
  16848. var p, i, il, sum;
  16849. var v3 = points[0] instanceof THREE.Vector3;
  16850. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16851. for ( i = 0, il = points.length; i < il; i ++ ) {
  16852. p = points[ i ];
  16853. if ( p.x > maxX ) maxX = p.x;
  16854. else if ( p.x < minX ) minX = p.x;
  16855. if ( p.y > maxY ) maxY = p.y;
  16856. else if ( p.y < minY ) minY = p.y;
  16857. if ( v3 ) {
  16858. if ( p.z > maxZ ) maxZ = p.z;
  16859. else if ( p.z < minZ ) minZ = p.z;
  16860. }
  16861. sum.add( p );
  16862. }
  16863. var ret = {
  16864. minX: minX,
  16865. minY: minY,
  16866. maxX: maxX,
  16867. maxY: maxY,
  16868. centroid: sum.divideScalar( il )
  16869. };
  16870. if ( v3 ) {
  16871. ret.maxZ = maxZ;
  16872. ret.minZ = minZ;
  16873. }
  16874. return ret;
  16875. };
  16876. /**************************************************************
  16877. * Create Geometries Helpers
  16878. **************************************************************/
  16879. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16880. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16881. var pts = this.getPoints( divisions, true );
  16882. return this.createGeometry( pts );
  16883. };
  16884. // Generate geometry from equidistance sampling along the path
  16885. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16886. var pts = this.getSpacedPoints( divisions, true );
  16887. return this.createGeometry( pts );
  16888. };
  16889. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16890. var geometry = new THREE.Geometry();
  16891. for ( var i = 0; i < points.length; i ++ ) {
  16892. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16893. }
  16894. return geometry;
  16895. };
  16896. /**************************************************************
  16897. * Bend / Wrap Helper Methods
  16898. **************************************************************/
  16899. // Wrap path / Bend modifiers?
  16900. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16901. this.bends.push( bendpath );
  16902. };
  16903. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16904. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16905. var i, il;
  16906. if ( !bends ) {
  16907. bends = this.bends;
  16908. }
  16909. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16910. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16911. }
  16912. return oldPts;
  16913. };
  16914. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16915. var oldPts = this.getSpacedPoints( segments );
  16916. var i, il;
  16917. if ( !bends ) {
  16918. bends = this.bends;
  16919. }
  16920. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16921. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16922. }
  16923. return oldPts;
  16924. };
  16925. // This returns getPoints() bend/wrapped around the contour of a path.
  16926. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16927. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16928. var bounds = this.getBoundingBox();
  16929. var i, il, p, oldX, oldY, xNorm;
  16930. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16931. p = oldPts[ i ];
  16932. oldX = p.x;
  16933. oldY = p.y;
  16934. xNorm = oldX / bounds.maxX;
  16935. // If using actual distance, for length > path, requires line extrusions
  16936. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16937. xNorm = path.getUtoTmapping( xNorm, oldX );
  16938. // check for out of bounds?
  16939. var pathPt = path.getPoint( xNorm );
  16940. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  16941. p.x = pathPt.x + normal.x;
  16942. p.y = pathPt.y + normal.y;
  16943. }
  16944. return oldPts;
  16945. };
  16946. /**
  16947. * @author alteredq / http://alteredqualia.com/
  16948. */
  16949. THREE.Gyroscope = function () {
  16950. THREE.Object3D.call( this );
  16951. };
  16952. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16953. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16954. this.matrixAutoUpdate && this.updateMatrix();
  16955. // update matrixWorld
  16956. if ( this.matrixWorldNeedsUpdate || force ) {
  16957. if ( this.parent ) {
  16958. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16959. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  16960. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  16961. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  16962. } else {
  16963. this.matrixWorld.copy( this.matrix );
  16964. }
  16965. this.matrixWorldNeedsUpdate = false;
  16966. force = true;
  16967. }
  16968. // update children
  16969. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16970. this.children[ i ].updateMatrixWorld( force );
  16971. }
  16972. };
  16973. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16974. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16975. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  16976. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  16977. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16978. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16979. /**
  16980. * @author zz85 / http://www.lab4games.net/zz85/blog
  16981. * Creates free form 2d path using series of points, lines or curves.
  16982. *
  16983. **/
  16984. THREE.Path = function ( points ) {
  16985. THREE.CurvePath.call(this);
  16986. this.actions = [];
  16987. if ( points ) {
  16988. this.fromPoints( points );
  16989. }
  16990. };
  16991. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16992. THREE.PathActions = {
  16993. MOVE_TO: 'moveTo',
  16994. LINE_TO: 'lineTo',
  16995. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16996. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16997. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16998. ARC: 'arc', // Circle
  16999. ELLIPSE: 'ellipse'
  17000. };
  17001. // TODO Clean up PATH API
  17002. // Create path using straight lines to connect all points
  17003. // - vectors: array of Vector2
  17004. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17005. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17006. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17007. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17008. };
  17009. };
  17010. // startPath() endPath()?
  17011. THREE.Path.prototype.moveTo = function ( x, y ) {
  17012. var args = Array.prototype.slice.call( arguments );
  17013. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17014. };
  17015. THREE.Path.prototype.lineTo = function ( x, y ) {
  17016. var args = Array.prototype.slice.call( arguments );
  17017. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17018. var x0 = lastargs[ lastargs.length - 2 ];
  17019. var y0 = lastargs[ lastargs.length - 1 ];
  17020. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17021. this.curves.push( curve );
  17022. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17023. };
  17024. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17025. var args = Array.prototype.slice.call( arguments );
  17026. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17027. var x0 = lastargs[ lastargs.length - 2 ];
  17028. var y0 = lastargs[ lastargs.length - 1 ];
  17029. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17030. new THREE.Vector2( aCPx, aCPy ),
  17031. new THREE.Vector2( aX, aY ) );
  17032. this.curves.push( curve );
  17033. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17034. };
  17035. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17036. aCP2x, aCP2y,
  17037. aX, aY ) {
  17038. var args = Array.prototype.slice.call( arguments );
  17039. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17040. var x0 = lastargs[ lastargs.length - 2 ];
  17041. var y0 = lastargs[ lastargs.length - 1 ];
  17042. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17043. new THREE.Vector2( aCP1x, aCP1y ),
  17044. new THREE.Vector2( aCP2x, aCP2y ),
  17045. new THREE.Vector2( aX, aY ) );
  17046. this.curves.push( curve );
  17047. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17048. };
  17049. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17050. var args = Array.prototype.slice.call( arguments );
  17051. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17052. var x0 = lastargs[ lastargs.length - 2 ];
  17053. var y0 = lastargs[ lastargs.length - 1 ];
  17054. //---
  17055. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17056. Array.prototype.push.apply( npts, pts );
  17057. var curve = new THREE.SplineCurve( npts );
  17058. this.curves.push( curve );
  17059. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17060. };
  17061. // FUTURE: Change the API or follow canvas API?
  17062. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17063. aStartAngle, aEndAngle, aClockwise ) {
  17064. var lastargs = this.actions[ this.actions.length - 1].args;
  17065. var x0 = lastargs[ lastargs.length - 2 ];
  17066. var y0 = lastargs[ lastargs.length - 1 ];
  17067. this.absarc(aX + x0, aY + y0, aRadius,
  17068. aStartAngle, aEndAngle, aClockwise );
  17069. };
  17070. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17071. aStartAngle, aEndAngle, aClockwise ) {
  17072. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17073. };
  17074. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17075. aStartAngle, aEndAngle, aClockwise ) {
  17076. var lastargs = this.actions[ this.actions.length - 1].args;
  17077. var x0 = lastargs[ lastargs.length - 2 ];
  17078. var y0 = lastargs[ lastargs.length - 1 ];
  17079. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17080. aStartAngle, aEndAngle, aClockwise );
  17081. };
  17082. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17083. aStartAngle, aEndAngle, aClockwise ) {
  17084. var args = Array.prototype.slice.call( arguments );
  17085. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17086. aStartAngle, aEndAngle, aClockwise );
  17087. this.curves.push( curve );
  17088. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  17089. args.push(lastPoint.x);
  17090. args.push(lastPoint.y);
  17091. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17092. };
  17093. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17094. if ( ! divisions ) divisions = 40;
  17095. var points = [];
  17096. for ( var i = 0; i < divisions; i ++ ) {
  17097. points.push( this.getPoint( i / divisions ) );
  17098. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17099. }
  17100. // if ( closedPath ) {
  17101. //
  17102. // points.push( points[ 0 ] );
  17103. //
  17104. // }
  17105. return points;
  17106. };
  17107. /* Return an array of vectors based on contour of the path */
  17108. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17109. if (this.useSpacedPoints) {
  17110. console.log('tata');
  17111. return this.getSpacedPoints( divisions, closedPath );
  17112. }
  17113. divisions = divisions || 12;
  17114. var points = [];
  17115. var i, il, item, action, args;
  17116. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17117. laste, j,
  17118. t, tx, ty;
  17119. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17120. item = this.actions[ i ];
  17121. action = item.action;
  17122. args = item.args;
  17123. switch( action ) {
  17124. case THREE.PathActions.MOVE_TO:
  17125. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17126. break;
  17127. case THREE.PathActions.LINE_TO:
  17128. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17129. break;
  17130. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17131. cpx = args[ 2 ];
  17132. cpy = args[ 3 ];
  17133. cpx1 = args[ 0 ];
  17134. cpy1 = args[ 1 ];
  17135. if ( points.length > 0 ) {
  17136. laste = points[ points.length - 1 ];
  17137. cpx0 = laste.x;
  17138. cpy0 = laste.y;
  17139. } else {
  17140. laste = this.actions[ i - 1 ].args;
  17141. cpx0 = laste[ laste.length - 2 ];
  17142. cpy0 = laste[ laste.length - 1 ];
  17143. }
  17144. for ( j = 1; j <= divisions; j ++ ) {
  17145. t = j / divisions;
  17146. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17147. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17148. points.push( new THREE.Vector2( tx, ty ) );
  17149. }
  17150. break;
  17151. case THREE.PathActions.BEZIER_CURVE_TO:
  17152. cpx = args[ 4 ];
  17153. cpy = args[ 5 ];
  17154. cpx1 = args[ 0 ];
  17155. cpy1 = args[ 1 ];
  17156. cpx2 = args[ 2 ];
  17157. cpy2 = args[ 3 ];
  17158. if ( points.length > 0 ) {
  17159. laste = points[ points.length - 1 ];
  17160. cpx0 = laste.x;
  17161. cpy0 = laste.y;
  17162. } else {
  17163. laste = this.actions[ i - 1 ].args;
  17164. cpx0 = laste[ laste.length - 2 ];
  17165. cpy0 = laste[ laste.length - 1 ];
  17166. }
  17167. for ( j = 1; j <= divisions; j ++ ) {
  17168. t = j / divisions;
  17169. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17170. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17171. points.push( new THREE.Vector2( tx, ty ) );
  17172. }
  17173. break;
  17174. case THREE.PathActions.CSPLINE_THRU:
  17175. laste = this.actions[ i - 1 ].args;
  17176. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17177. var spts = [ last ];
  17178. var n = divisions * args[ 0 ].length;
  17179. spts = spts.concat( args[ 0 ] );
  17180. var spline = new THREE.SplineCurve( spts );
  17181. for ( j = 1; j <= n; j ++ ) {
  17182. points.push( spline.getPointAt( j / n ) ) ;
  17183. }
  17184. break;
  17185. case THREE.PathActions.ARC:
  17186. var aX = args[ 0 ], aY = args[ 1 ],
  17187. aRadius = args[ 2 ],
  17188. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17189. aClockwise = !!args[ 5 ];
  17190. var deltaAngle = aEndAngle - aStartAngle;
  17191. var angle;
  17192. var tdivisions = divisions * 2;
  17193. for ( j = 1; j <= tdivisions; j ++ ) {
  17194. t = j / tdivisions;
  17195. if ( ! aClockwise ) {
  17196. t = 1 - t;
  17197. }
  17198. angle = aStartAngle + t * deltaAngle;
  17199. tx = aX + aRadius * Math.cos( angle );
  17200. ty = aY + aRadius * Math.sin( angle );
  17201. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17202. points.push( new THREE.Vector2( tx, ty ) );
  17203. }
  17204. //console.log(points);
  17205. break;
  17206. case THREE.PathActions.ELLIPSE:
  17207. var aX = args[ 0 ], aY = args[ 1 ],
  17208. xRadius = args[ 2 ],
  17209. yRadius = args[ 3 ],
  17210. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17211. aClockwise = !!args[ 6 ];
  17212. var deltaAngle = aEndAngle - aStartAngle;
  17213. var angle;
  17214. var tdivisions = divisions * 2;
  17215. for ( j = 1; j <= tdivisions; j ++ ) {
  17216. t = j / tdivisions;
  17217. if ( ! aClockwise ) {
  17218. t = 1 - t;
  17219. }
  17220. angle = aStartAngle + t * deltaAngle;
  17221. tx = aX + xRadius * Math.cos( angle );
  17222. ty = aY + yRadius * Math.sin( angle );
  17223. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17224. points.push( new THREE.Vector2( tx, ty ) );
  17225. }
  17226. //console.log(points);
  17227. break;
  17228. } // end switch
  17229. }
  17230. // Normalize to remove the closing point by default.
  17231. var lastPoint = points[ points.length - 1];
  17232. var EPSILON = 0.0000000001;
  17233. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17234. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17235. points.splice( points.length - 1, 1);
  17236. if ( closedPath ) {
  17237. points.push( points[ 0 ] );
  17238. }
  17239. return points;
  17240. };
  17241. // Breaks path into shapes
  17242. THREE.Path.prototype.toShapes = function() {
  17243. var i, il, item, action, args;
  17244. var subPaths = [], lastPath = new THREE.Path();
  17245. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17246. item = this.actions[ i ];
  17247. args = item.args;
  17248. action = item.action;
  17249. if ( action == THREE.PathActions.MOVE_TO ) {
  17250. if ( lastPath.actions.length != 0 ) {
  17251. subPaths.push( lastPath );
  17252. lastPath = new THREE.Path();
  17253. }
  17254. }
  17255. lastPath[ action ].apply( lastPath, args );
  17256. }
  17257. if ( lastPath.actions.length != 0 ) {
  17258. subPaths.push( lastPath );
  17259. }
  17260. // console.log(subPaths);
  17261. if ( subPaths.length == 0 ) return [];
  17262. var tmpPath, tmpShape, shapes = [];
  17263. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17264. // console.log("Holes first", holesFirst);
  17265. if ( subPaths.length == 1) {
  17266. tmpPath = subPaths[0];
  17267. tmpShape = new THREE.Shape();
  17268. tmpShape.actions = tmpPath.actions;
  17269. tmpShape.curves = tmpPath.curves;
  17270. shapes.push( tmpShape );
  17271. return shapes;
  17272. };
  17273. if ( holesFirst ) {
  17274. tmpShape = new THREE.Shape();
  17275. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17276. tmpPath = subPaths[ i ];
  17277. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17278. tmpShape.actions = tmpPath.actions;
  17279. tmpShape.curves = tmpPath.curves;
  17280. shapes.push( tmpShape );
  17281. tmpShape = new THREE.Shape();
  17282. //console.log('cw', i);
  17283. } else {
  17284. tmpShape.holes.push( tmpPath );
  17285. //console.log('ccw', i);
  17286. }
  17287. }
  17288. } else {
  17289. // Shapes first
  17290. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17291. tmpPath = subPaths[ i ];
  17292. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17293. if ( tmpShape ) shapes.push( tmpShape );
  17294. tmpShape = new THREE.Shape();
  17295. tmpShape.actions = tmpPath.actions;
  17296. tmpShape.curves = tmpPath.curves;
  17297. } else {
  17298. tmpShape.holes.push( tmpPath );
  17299. }
  17300. }
  17301. shapes.push( tmpShape );
  17302. }
  17303. //console.log("shape", shapes);
  17304. return shapes;
  17305. };
  17306. /**
  17307. * @author zz85 / http://www.lab4games.net/zz85/blog
  17308. * Defines a 2d shape plane using paths.
  17309. **/
  17310. // STEP 1 Create a path.
  17311. // STEP 2 Turn path into shape.
  17312. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17313. // STEP 3a - Extract points from each shape, turn to vertices
  17314. // STEP 3b - Triangulate each shape, add faces.
  17315. THREE.Shape = function () {
  17316. THREE.Path.apply( this, arguments );
  17317. this.holes = [];
  17318. };
  17319. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17320. // Convenience method to return ExtrudeGeometry
  17321. THREE.Shape.prototype.extrude = function ( options ) {
  17322. var extruded = new THREE.ExtrudeGeometry( this, options );
  17323. return extruded;
  17324. };
  17325. // Convenience method to return ShapeGeometry
  17326. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17327. var geometry = new THREE.ShapeGeometry( this, options );
  17328. return geometry;
  17329. };
  17330. // Get points of holes
  17331. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17332. var i, il = this.holes.length, holesPts = [];
  17333. for ( i = 0; i < il; i ++ ) {
  17334. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17335. }
  17336. return holesPts;
  17337. };
  17338. // Get points of holes (spaced by regular distance)
  17339. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17340. var i, il = this.holes.length, holesPts = [];
  17341. for ( i = 0; i < il; i ++ ) {
  17342. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17343. }
  17344. return holesPts;
  17345. };
  17346. // Get points of shape and holes (keypoints based on segments parameter)
  17347. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17348. return {
  17349. shape: this.getTransformedPoints( divisions ),
  17350. holes: this.getPointsHoles( divisions )
  17351. };
  17352. };
  17353. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17354. if (this.useSpacedPoints) {
  17355. return this.extractAllSpacedPoints(divisions);
  17356. }
  17357. return this.extractAllPoints(divisions);
  17358. };
  17359. //
  17360. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17361. //
  17362. // return {
  17363. //
  17364. // shape: this.transform( bend, divisions ),
  17365. // holes: this.getPointsHoles( divisions, bend )
  17366. //
  17367. // };
  17368. //
  17369. // };
  17370. // Get points of shape and holes (spaced by regular distance)
  17371. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17372. return {
  17373. shape: this.getTransformedSpacedPoints( divisions ),
  17374. holes: this.getSpacedPointsHoles( divisions )
  17375. };
  17376. };
  17377. /**************************************************************
  17378. * Utils
  17379. **************************************************************/
  17380. THREE.Shape.Utils = {
  17381. /*
  17382. contour - array of vector2 for contour
  17383. holes - array of array of vector2
  17384. */
  17385. removeHoles: function ( contour, holes ) {
  17386. var shape = contour.concat(); // work on this shape
  17387. var allpoints = shape.concat();
  17388. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17389. var prevShapeVert, nextShapeVert,
  17390. prevHoleVert, nextHoleVert,
  17391. holeIndex, shapeIndex,
  17392. shapeId, shapeGroup,
  17393. h, h2,
  17394. hole, shortest, d,
  17395. p, pts1, pts2,
  17396. tmpShape1, tmpShape2,
  17397. tmpHole1, tmpHole2,
  17398. verts = [];
  17399. for ( h = 0; h < holes.length; h ++ ) {
  17400. hole = holes[ h ];
  17401. /*
  17402. shapeholes[ h ].concat(); // preserves original
  17403. holes.push( hole );
  17404. */
  17405. Array.prototype.push.apply( allpoints, hole );
  17406. shortest = Number.POSITIVE_INFINITY;
  17407. // Find the shortest pair of pts between shape and hole
  17408. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17409. // Using distanceToSquared() intead of distanceTo() should speed a little
  17410. // since running square roots operations are reduced.
  17411. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17412. pts1 = hole[ h2 ];
  17413. var dist = [];
  17414. for ( p = 0; p < shape.length; p++ ) {
  17415. pts2 = shape[ p ];
  17416. d = pts1.distanceToSquared( pts2 );
  17417. dist.push( d );
  17418. if ( d < shortest ) {
  17419. shortest = d;
  17420. holeIndex = h2;
  17421. shapeIndex = p;
  17422. }
  17423. }
  17424. }
  17425. //console.log("shortest", shortest, dist);
  17426. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17427. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17428. var areaapts = [
  17429. hole[ holeIndex ],
  17430. shape[ shapeIndex ],
  17431. shape[ prevShapeVert ]
  17432. ];
  17433. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17434. var areabpts = [
  17435. hole[ holeIndex ],
  17436. hole[ prevHoleVert ],
  17437. shape[ shapeIndex ]
  17438. ];
  17439. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17440. var shapeOffset = 1;
  17441. var holeOffset = -1;
  17442. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17443. shapeIndex += shapeOffset;
  17444. holeIndex += holeOffset;
  17445. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17446. shapeIndex %= shape.length;
  17447. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17448. holeIndex %= hole.length;
  17449. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17450. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17451. areaapts = [
  17452. hole[ holeIndex ],
  17453. shape[ shapeIndex ],
  17454. shape[ prevShapeVert ]
  17455. ];
  17456. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17457. areabpts = [
  17458. hole[ holeIndex ],
  17459. hole[ prevHoleVert ],
  17460. shape[ shapeIndex ]
  17461. ];
  17462. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17463. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17464. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17465. // In case areas are not correct.
  17466. //console.log("USE THIS");
  17467. shapeIndex = oldShapeIndex;
  17468. holeIndex = oldHoleIndex ;
  17469. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17470. shapeIndex %= shape.length;
  17471. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17472. holeIndex %= hole.length;
  17473. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17474. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17475. } else {
  17476. //console.log("USE THAT ")
  17477. }
  17478. tmpShape1 = shape.slice( 0, shapeIndex );
  17479. tmpShape2 = shape.slice( shapeIndex );
  17480. tmpHole1 = hole.slice( holeIndex );
  17481. tmpHole2 = hole.slice( 0, holeIndex );
  17482. // Should check orders here again?
  17483. var trianglea = [
  17484. hole[ holeIndex ],
  17485. shape[ shapeIndex ],
  17486. shape[ prevShapeVert ]
  17487. ];
  17488. var triangleb = [
  17489. hole[ holeIndex ] ,
  17490. hole[ prevHoleVert ],
  17491. shape[ shapeIndex ]
  17492. ];
  17493. verts.push( trianglea );
  17494. verts.push( triangleb );
  17495. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17496. }
  17497. return {
  17498. shape:shape, /* shape with no holes */
  17499. isolatedPts: verts, /* isolated faces */
  17500. allpoints: allpoints
  17501. }
  17502. },
  17503. triangulateShape: function ( contour, holes ) {
  17504. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17505. var shape = shapeWithoutHoles.shape,
  17506. allpoints = shapeWithoutHoles.allpoints,
  17507. isolatedPts = shapeWithoutHoles.isolatedPts;
  17508. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17509. // 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.
  17510. //console.log( "triangles",triangles, triangles.length );
  17511. //console.log( "allpoints",allpoints, allpoints.length );
  17512. var i, il, f, face,
  17513. key, index,
  17514. allPointsMap = {},
  17515. isolatedPointsMap = {};
  17516. // prepare all points map
  17517. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17518. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17519. if ( allPointsMap[ key ] !== undefined ) {
  17520. console.log( "Duplicate point", key );
  17521. }
  17522. allPointsMap[ key ] = i;
  17523. }
  17524. // check all face vertices against all points map
  17525. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17526. face = triangles[ i ];
  17527. for ( f = 0; f < 3; f ++ ) {
  17528. key = face[ f ].x + ":" + face[ f ].y;
  17529. index = allPointsMap[ key ];
  17530. if ( index !== undefined ) {
  17531. face[ f ] = index;
  17532. }
  17533. }
  17534. }
  17535. // check isolated points vertices against all points map
  17536. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17537. face = isolatedPts[ i ];
  17538. for ( f = 0; f < 3; f ++ ) {
  17539. key = face[ f ].x + ":" + face[ f ].y;
  17540. index = allPointsMap[ key ];
  17541. if ( index !== undefined ) {
  17542. face[ f ] = index;
  17543. }
  17544. }
  17545. }
  17546. return triangles.concat( isolatedPts );
  17547. }, // end triangulate shapes
  17548. /*
  17549. triangulate2 : function( pts, holes ) {
  17550. // For use with Poly2Tri.js
  17551. var allpts = pts.concat();
  17552. var shape = [];
  17553. for (var p in pts) {
  17554. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17555. }
  17556. var swctx = new js.poly2tri.SweepContext(shape);
  17557. for (var h in holes) {
  17558. var aHole = holes[h];
  17559. var newHole = []
  17560. for (i in aHole) {
  17561. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17562. allpts.push(aHole[i]);
  17563. }
  17564. swctx.AddHole(newHole);
  17565. }
  17566. var find;
  17567. var findIndexForPt = function (pt) {
  17568. find = new THREE.Vector2(pt.x, pt.y);
  17569. var p;
  17570. for (p=0, pl = allpts.length; p<pl; p++) {
  17571. if (allpts[p].equals(find)) return p;
  17572. }
  17573. return -1;
  17574. };
  17575. // triangulate
  17576. js.poly2tri.sweep.Triangulate(swctx);
  17577. var triangles = swctx.GetTriangles();
  17578. var tr ;
  17579. var facesPts = [];
  17580. for (var t in triangles) {
  17581. tr = triangles[t];
  17582. facesPts.push([
  17583. findIndexForPt(tr.GetPoint(0)),
  17584. findIndexForPt(tr.GetPoint(1)),
  17585. findIndexForPt(tr.GetPoint(2))
  17586. ]);
  17587. }
  17588. // console.log(facesPts);
  17589. // console.log("triangles", triangles.length, triangles);
  17590. // Returns array of faces with 3 element each
  17591. return facesPts;
  17592. },
  17593. */
  17594. isClockWise: function ( pts ) {
  17595. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17596. },
  17597. // Bezier Curves formulas obtained from
  17598. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17599. // Quad Bezier Functions
  17600. b2p0: function ( t, p ) {
  17601. var k = 1 - t;
  17602. return k * k * p;
  17603. },
  17604. b2p1: function ( t, p ) {
  17605. return 2 * ( 1 - t ) * t * p;
  17606. },
  17607. b2p2: function ( t, p ) {
  17608. return t * t * p;
  17609. },
  17610. b2: function ( t, p0, p1, p2 ) {
  17611. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17612. },
  17613. // Cubic Bezier Functions
  17614. b3p0: function ( t, p ) {
  17615. var k = 1 - t;
  17616. return k * k * k * p;
  17617. },
  17618. b3p1: function ( t, p ) {
  17619. var k = 1 - t;
  17620. return 3 * k * k * t * p;
  17621. },
  17622. b3p2: function ( t, p ) {
  17623. var k = 1 - t;
  17624. return 3 * k * t * t * p;
  17625. },
  17626. b3p3: function ( t, p ) {
  17627. return t * t * t * p;
  17628. },
  17629. b3: function ( t, p0, p1, p2, p3 ) {
  17630. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17631. }
  17632. };
  17633. /**
  17634. * @author mikael emtinger / http://gomo.se/
  17635. */
  17636. THREE.AnimationHandler = (function() {
  17637. var playing = [];
  17638. var library = {};
  17639. var that = {};
  17640. //--- update ---
  17641. that.update = function( deltaTimeMS ) {
  17642. for( var i = 0; i < playing.length; i ++ )
  17643. playing[ i ].update( deltaTimeMS );
  17644. };
  17645. //--- add ---
  17646. that.addToUpdate = function( animation ) {
  17647. if ( playing.indexOf( animation ) === -1 )
  17648. playing.push( animation );
  17649. };
  17650. //--- remove ---
  17651. that.removeFromUpdate = function( animation ) {
  17652. var index = playing.indexOf( animation );
  17653. if( index !== -1 )
  17654. playing.splice( index, 1 );
  17655. };
  17656. //--- add ---
  17657. that.add = function( data ) {
  17658. if ( library[ data.name ] !== undefined )
  17659. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17660. library[ data.name ] = data;
  17661. initData( data );
  17662. };
  17663. //--- get ---
  17664. that.get = function( name ) {
  17665. if ( typeof name === "string" ) {
  17666. if ( library[ name ] ) {
  17667. return library[ name ];
  17668. } else {
  17669. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17670. return null;
  17671. }
  17672. } else {
  17673. // todo: add simple tween library
  17674. }
  17675. };
  17676. //--- parse ---
  17677. that.parse = function( root ) {
  17678. // setup hierarchy
  17679. var hierarchy = [];
  17680. if ( root instanceof THREE.SkinnedMesh ) {
  17681. for( var b = 0; b < root.bones.length; b++ ) {
  17682. hierarchy.push( root.bones[ b ] );
  17683. }
  17684. } else {
  17685. parseRecurseHierarchy( root, hierarchy );
  17686. }
  17687. return hierarchy;
  17688. };
  17689. var parseRecurseHierarchy = function( root, hierarchy ) {
  17690. hierarchy.push( root );
  17691. for( var c = 0; c < root.children.length; c++ )
  17692. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17693. }
  17694. //--- init data ---
  17695. var initData = function( data ) {
  17696. if( data.initialized === true )
  17697. return;
  17698. // loop through all keys
  17699. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17700. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17701. // remove minus times
  17702. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17703. data.hierarchy[ h ].keys[ k ].time = 0;
  17704. // create quaternions
  17705. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17706. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17707. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17708. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17709. }
  17710. }
  17711. // prepare morph target keys
  17712. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17713. // get all used
  17714. var usedMorphTargets = {};
  17715. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17716. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17717. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17718. usedMorphTargets[ morphTargetName ] = -1;
  17719. }
  17720. }
  17721. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17722. // set all used on all frames
  17723. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17724. var influences = {};
  17725. for ( var morphTargetName in usedMorphTargets ) {
  17726. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17727. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17728. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17729. break;
  17730. }
  17731. }
  17732. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17733. influences[ morphTargetName ] = 0;
  17734. }
  17735. }
  17736. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17737. }
  17738. }
  17739. // remove all keys that are on the same time
  17740. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17741. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17742. data.hierarchy[ h ].keys.splice( k, 1 );
  17743. k --;
  17744. }
  17745. }
  17746. // set index
  17747. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17748. data.hierarchy[ h ].keys[ k ].index = k;
  17749. }
  17750. }
  17751. // JIT
  17752. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17753. data.JIT = {};
  17754. data.JIT.hierarchy = [];
  17755. for( var h = 0; h < data.hierarchy.length; h ++ )
  17756. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17757. // done
  17758. data.initialized = true;
  17759. };
  17760. // interpolation types
  17761. that.LINEAR = 0;
  17762. that.CATMULLROM = 1;
  17763. that.CATMULLROM_FORWARD = 2;
  17764. return that;
  17765. }());
  17766. /**
  17767. * @author mikael emtinger / http://gomo.se/
  17768. * @author mrdoob / http://mrdoob.com/
  17769. * @author alteredq / http://alteredqualia.com/
  17770. */
  17771. THREE.Animation = function ( root, name, interpolationType ) {
  17772. this.root = root;
  17773. this.data = THREE.AnimationHandler.get( name );
  17774. this.hierarchy = THREE.AnimationHandler.parse( root );
  17775. this.currentTime = 0;
  17776. this.timeScale = 1;
  17777. this.isPlaying = false;
  17778. this.isPaused = true;
  17779. this.loop = true;
  17780. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17781. this.points = [];
  17782. this.target = new THREE.Vector3();
  17783. };
  17784. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17785. if ( this.isPlaying === false ) {
  17786. this.isPlaying = true;
  17787. this.loop = loop !== undefined ? loop : true;
  17788. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17789. // reset key cache
  17790. var h, hl = this.hierarchy.length,
  17791. object;
  17792. for ( h = 0; h < hl; h ++ ) {
  17793. object = this.hierarchy[ h ];
  17794. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17795. object.useQuaternion = true;
  17796. }
  17797. object.matrixAutoUpdate = true;
  17798. if ( object.animationCache === undefined ) {
  17799. object.animationCache = {};
  17800. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17801. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17802. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17803. }
  17804. var prevKey = object.animationCache.prevKey;
  17805. var nextKey = object.animationCache.nextKey;
  17806. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17807. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17808. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17809. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17810. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17811. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17812. }
  17813. this.update( 0 );
  17814. }
  17815. this.isPaused = false;
  17816. THREE.AnimationHandler.addToUpdate( this );
  17817. };
  17818. THREE.Animation.prototype.pause = function() {
  17819. if ( this.isPaused === true ) {
  17820. THREE.AnimationHandler.addToUpdate( this );
  17821. } else {
  17822. THREE.AnimationHandler.removeFromUpdate( this );
  17823. }
  17824. this.isPaused = !this.isPaused;
  17825. };
  17826. THREE.Animation.prototype.stop = function() {
  17827. this.isPlaying = false;
  17828. this.isPaused = false;
  17829. THREE.AnimationHandler.removeFromUpdate( this );
  17830. };
  17831. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17832. // early out
  17833. if ( this.isPlaying === false ) return;
  17834. // vars
  17835. var types = [ "pos", "rot", "scl" ];
  17836. var type;
  17837. var scale;
  17838. var vector;
  17839. var prevXYZ, nextXYZ;
  17840. var prevKey, nextKey;
  17841. var object;
  17842. var animationCache;
  17843. var frame;
  17844. var JIThierarchy = this.data.JIT.hierarchy;
  17845. var currentTime, unloopedCurrentTime;
  17846. var currentPoint, forwardPoint, angle;
  17847. this.currentTime += deltaTimeMS * this.timeScale;
  17848. unloopedCurrentTime = this.currentTime;
  17849. currentTime = this.currentTime = this.currentTime % this.data.length;
  17850. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17851. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17852. object = this.hierarchy[ h ];
  17853. animationCache = object.animationCache;
  17854. // loop through pos/rot/scl
  17855. for ( var t = 0; t < 3; t ++ ) {
  17856. // get keys
  17857. type = types[ t ];
  17858. prevKey = animationCache.prevKey[ type ];
  17859. nextKey = animationCache.nextKey[ type ];
  17860. // switch keys?
  17861. if ( nextKey.time <= unloopedCurrentTime ) {
  17862. // did we loop?
  17863. if ( currentTime < unloopedCurrentTime ) {
  17864. if ( this.loop ) {
  17865. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17866. nextKey = this.getNextKeyWith( type, h, 1 );
  17867. while( nextKey.time < currentTime ) {
  17868. prevKey = nextKey;
  17869. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17870. }
  17871. } else {
  17872. this.stop();
  17873. return;
  17874. }
  17875. } else {
  17876. do {
  17877. prevKey = nextKey;
  17878. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17879. } while( nextKey.time < currentTime )
  17880. }
  17881. animationCache.prevKey[ type ] = prevKey;
  17882. animationCache.nextKey[ type ] = nextKey;
  17883. }
  17884. object.matrixAutoUpdate = true;
  17885. object.matrixWorldNeedsUpdate = true;
  17886. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  17887. prevXYZ = prevKey[ type ];
  17888. nextXYZ = nextKey[ type ];
  17889. // check scale error
  17890. if ( scale < 0 || scale > 1 ) {
  17891. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  17892. scale = scale < 0 ? 0 : 1;
  17893. }
  17894. // interpolate
  17895. if ( type === "pos" ) {
  17896. vector = object.position;
  17897. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  17898. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17899. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17900. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17901. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17902. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17903. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  17904. this.points[ 1 ] = prevXYZ;
  17905. this.points[ 2 ] = nextXYZ;
  17906. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  17907. scale = scale * 0.33 + 0.33;
  17908. currentPoint = this.interpolateCatmullRom( this.points, scale );
  17909. vector.x = currentPoint[ 0 ];
  17910. vector.y = currentPoint[ 1 ];
  17911. vector.z = currentPoint[ 2 ];
  17912. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17913. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  17914. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  17915. this.target.sub( vector );
  17916. this.target.y = 0;
  17917. this.target.normalize();
  17918. angle = Math.atan2( this.target.x, this.target.z );
  17919. object.rotation.set( 0, angle, 0 );
  17920. }
  17921. }
  17922. } else if ( type === "rot" ) {
  17923. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  17924. } else if ( type === "scl" ) {
  17925. vector = object.scale;
  17926. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17927. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17928. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17929. }
  17930. }
  17931. }
  17932. };
  17933. // Catmull-Rom spline
  17934. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  17935. var c = [], v3 = [],
  17936. point, intPoint, weight, w2, w3,
  17937. pa, pb, pc, pd;
  17938. point = ( points.length - 1 ) * scale;
  17939. intPoint = Math.floor( point );
  17940. weight = point - intPoint;
  17941. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  17942. c[ 1 ] = intPoint;
  17943. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  17944. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  17945. pa = points[ c[ 0 ] ];
  17946. pb = points[ c[ 1 ] ];
  17947. pc = points[ c[ 2 ] ];
  17948. pd = points[ c[ 3 ] ];
  17949. w2 = weight * weight;
  17950. w3 = weight * w2;
  17951. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  17952. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  17953. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  17954. return v3;
  17955. };
  17956. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  17957. var v0 = ( p2 - p0 ) * 0.5,
  17958. v1 = ( p3 - p1 ) * 0.5;
  17959. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17960. };
  17961. // Get next key with
  17962. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  17963. var keys = this.data.hierarchy[ h ].keys;
  17964. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17965. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17966. key = key < keys.length - 1 ? key : keys.length - 1;
  17967. } else {
  17968. key = key % keys.length;
  17969. }
  17970. for ( ; key < keys.length; key++ ) {
  17971. if ( keys[ key ][ type ] !== undefined ) {
  17972. return keys[ key ];
  17973. }
  17974. }
  17975. return this.data.hierarchy[ h ].keys[ 0 ];
  17976. };
  17977. // Get previous key with
  17978. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  17979. var keys = this.data.hierarchy[ h ].keys;
  17980. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17981. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17982. key = key > 0 ? key : 0;
  17983. } else {
  17984. key = key >= 0 ? key : key + keys.length;
  17985. }
  17986. for ( ; key >= 0; key -- ) {
  17987. if ( keys[ key ][ type ] !== undefined ) {
  17988. return keys[ key ];
  17989. }
  17990. }
  17991. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  17992. };
  17993. /**
  17994. * @author mikael emtinger / http://gomo.se/
  17995. * @author mrdoob / http://mrdoob.com/
  17996. * @author alteredq / http://alteredqualia.com/
  17997. * @author khang duong
  17998. * @author erik kitson
  17999. */
  18000. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  18001. this.root = root;
  18002. this.data = THREE.AnimationHandler.get( data );
  18003. this.hierarchy = THREE.AnimationHandler.parse( root );
  18004. this.currentTime = 0;
  18005. this.timeScale = 0.001;
  18006. this.isPlaying = false;
  18007. this.isPaused = true;
  18008. this.loop = true;
  18009. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  18010. // initialize to first keyframes
  18011. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18012. var keys = this.data.hierarchy[h].keys,
  18013. sids = this.data.hierarchy[h].sids,
  18014. obj = this.hierarchy[h];
  18015. if ( keys.length && sids ) {
  18016. for ( var s = 0; s < sids.length; s++ ) {
  18017. var sid = sids[ s ],
  18018. next = this.getNextKeyWith( sid, h, 0 );
  18019. if ( next ) {
  18020. next.apply( sid );
  18021. }
  18022. }
  18023. obj.matrixAutoUpdate = false;
  18024. this.data.hierarchy[h].node.updateMatrix();
  18025. obj.matrixWorldNeedsUpdate = true;
  18026. }
  18027. }
  18028. };
  18029. // Play
  18030. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18031. if( !this.isPlaying ) {
  18032. this.isPlaying = true;
  18033. this.loop = loop !== undefined ? loop : true;
  18034. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18035. this.startTimeMs = startTimeMS;
  18036. this.startTime = 10000000;
  18037. this.endTime = -this.startTime;
  18038. // reset key cache
  18039. var h, hl = this.hierarchy.length,
  18040. object,
  18041. node;
  18042. for ( h = 0; h < hl; h++ ) {
  18043. object = this.hierarchy[ h ];
  18044. node = this.data.hierarchy[ h ];
  18045. object.useQuaternion = true;
  18046. if ( node.animationCache === undefined ) {
  18047. node.animationCache = {};
  18048. node.animationCache.prevKey = null;
  18049. node.animationCache.nextKey = null;
  18050. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18051. }
  18052. var keys = this.data.hierarchy[h].keys;
  18053. if (keys.length) {
  18054. node.animationCache.prevKey = keys[ 0 ];
  18055. node.animationCache.nextKey = keys[ 1 ];
  18056. this.startTime = Math.min( keys[0].time, this.startTime );
  18057. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18058. }
  18059. }
  18060. this.update( 0 );
  18061. }
  18062. this.isPaused = false;
  18063. THREE.AnimationHandler.addToUpdate( this );
  18064. };
  18065. // Pause
  18066. THREE.KeyFrameAnimation.prototype.pause = function() {
  18067. if( this.isPaused ) {
  18068. THREE.AnimationHandler.addToUpdate( this );
  18069. } else {
  18070. THREE.AnimationHandler.removeFromUpdate( this );
  18071. }
  18072. this.isPaused = !this.isPaused;
  18073. };
  18074. // Stop
  18075. THREE.KeyFrameAnimation.prototype.stop = function() {
  18076. this.isPlaying = false;
  18077. this.isPaused = false;
  18078. THREE.AnimationHandler.removeFromUpdate( this );
  18079. // reset JIT matrix and remove cache
  18080. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18081. var obj = this.hierarchy[ h ];
  18082. var node = this.data.hierarchy[ h ];
  18083. if ( node.animationCache !== undefined ) {
  18084. var original = node.animationCache.originalMatrix;
  18085. if( obj instanceof THREE.Bone ) {
  18086. original.copy( obj.skinMatrix );
  18087. obj.skinMatrix = original;
  18088. } else {
  18089. original.copy( obj.matrix );
  18090. obj.matrix = original;
  18091. }
  18092. delete node.animationCache;
  18093. }
  18094. }
  18095. };
  18096. // Update
  18097. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18098. // early out
  18099. if( !this.isPlaying ) return;
  18100. // vars
  18101. var prevKey, nextKey;
  18102. var object;
  18103. var node;
  18104. var frame;
  18105. var JIThierarchy = this.data.JIT.hierarchy;
  18106. var currentTime, unloopedCurrentTime;
  18107. var looped;
  18108. // update
  18109. this.currentTime += deltaTimeMS * this.timeScale;
  18110. unloopedCurrentTime = this.currentTime;
  18111. currentTime = this.currentTime = this.currentTime % this.data.length;
  18112. // if looped around, the current time should be based on the startTime
  18113. if ( currentTime < this.startTimeMs ) {
  18114. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18115. }
  18116. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18117. looped = currentTime < unloopedCurrentTime;
  18118. if ( looped && !this.loop ) {
  18119. // Set the animation to the last keyframes and stop
  18120. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18121. var keys = this.data.hierarchy[h].keys,
  18122. sids = this.data.hierarchy[h].sids,
  18123. end = keys.length-1,
  18124. obj = this.hierarchy[h];
  18125. if ( keys.length ) {
  18126. for ( var s = 0; s < sids.length; s++ ) {
  18127. var sid = sids[ s ],
  18128. prev = this.getPrevKeyWith( sid, h, end );
  18129. if ( prev ) {
  18130. prev.apply( sid );
  18131. }
  18132. }
  18133. this.data.hierarchy[h].node.updateMatrix();
  18134. obj.matrixWorldNeedsUpdate = true;
  18135. }
  18136. }
  18137. this.stop();
  18138. return;
  18139. }
  18140. // check pre-infinity
  18141. if ( currentTime < this.startTime ) {
  18142. return;
  18143. }
  18144. // update
  18145. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18146. object = this.hierarchy[ h ];
  18147. node = this.data.hierarchy[ h ];
  18148. var keys = node.keys,
  18149. animationCache = node.animationCache;
  18150. // use JIT?
  18151. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18152. if( object instanceof THREE.Bone ) {
  18153. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18154. object.matrixWorldNeedsUpdate = false;
  18155. } else {
  18156. object.matrix = JIThierarchy[ h ][ frame ];
  18157. object.matrixWorldNeedsUpdate = true;
  18158. }
  18159. // use interpolation
  18160. } else if ( keys.length ) {
  18161. // make sure so original matrix and not JIT matrix is set
  18162. if ( this.JITCompile && animationCache ) {
  18163. if( object instanceof THREE.Bone ) {
  18164. object.skinMatrix = animationCache.originalMatrix;
  18165. } else {
  18166. object.matrix = animationCache.originalMatrix;
  18167. }
  18168. }
  18169. prevKey = animationCache.prevKey;
  18170. nextKey = animationCache.nextKey;
  18171. if ( prevKey && nextKey ) {
  18172. // switch keys?
  18173. if ( nextKey.time <= unloopedCurrentTime ) {
  18174. // did we loop?
  18175. if ( looped && this.loop ) {
  18176. prevKey = keys[ 0 ];
  18177. nextKey = keys[ 1 ];
  18178. while ( nextKey.time < currentTime ) {
  18179. prevKey = nextKey;
  18180. nextKey = keys[ prevKey.index + 1 ];
  18181. }
  18182. } else if ( !looped ) {
  18183. var lastIndex = keys.length - 1;
  18184. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18185. prevKey = nextKey;
  18186. nextKey = keys[ prevKey.index + 1 ];
  18187. }
  18188. }
  18189. animationCache.prevKey = prevKey;
  18190. animationCache.nextKey = nextKey;
  18191. }
  18192. if(nextKey.time >= currentTime)
  18193. prevKey.interpolate( nextKey, currentTime );
  18194. else
  18195. prevKey.interpolate( nextKey, nextKey.time);
  18196. }
  18197. this.data.hierarchy[h].node.updateMatrix();
  18198. object.matrixWorldNeedsUpdate = true;
  18199. }
  18200. }
  18201. // update JIT?
  18202. if ( this.JITCompile ) {
  18203. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18204. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18205. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18206. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18207. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18208. } else {
  18209. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18210. }
  18211. }
  18212. }
  18213. }
  18214. };
  18215. // Get next key with
  18216. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18217. var keys = this.data.hierarchy[ h ].keys;
  18218. key = key % keys.length;
  18219. for ( ; key < keys.length; key++ ) {
  18220. if ( keys[ key ].hasTarget( sid ) ) {
  18221. return keys[ key ];
  18222. }
  18223. }
  18224. return keys[ 0 ];
  18225. };
  18226. // Get previous key with
  18227. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18228. var keys = this.data.hierarchy[ h ].keys;
  18229. key = key >= 0 ? key : key + keys.length;
  18230. for ( ; key >= 0; key-- ) {
  18231. if ( keys[ key ].hasTarget( sid ) ) {
  18232. return keys[ key ];
  18233. }
  18234. }
  18235. return keys[ keys.length - 1 ];
  18236. };
  18237. /**
  18238. * Camera for rendering cube maps
  18239. * - renders scene into axis-aligned cube
  18240. *
  18241. * @author alteredq / http://alteredqualia.com/
  18242. */
  18243. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18244. THREE.Object3D.call( this );
  18245. var fov = 90, aspect = 1;
  18246. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18247. cameraPX.up.set( 0, -1, 0 );
  18248. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18249. this.add( cameraPX );
  18250. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18251. cameraNX.up.set( 0, -1, 0 );
  18252. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18253. this.add( cameraNX );
  18254. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18255. cameraPY.up.set( 0, 0, 1 );
  18256. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18257. this.add( cameraPY );
  18258. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18259. cameraNY.up.set( 0, 0, -1 );
  18260. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18261. this.add( cameraNY );
  18262. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18263. cameraPZ.up.set( 0, -1, 0 );
  18264. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18265. this.add( cameraPZ );
  18266. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18267. cameraNZ.up.set( 0, -1, 0 );
  18268. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18269. this.add( cameraNZ );
  18270. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18271. this.updateCubeMap = function ( renderer, scene ) {
  18272. var renderTarget = this.renderTarget;
  18273. var generateMipmaps = renderTarget.generateMipmaps;
  18274. renderTarget.generateMipmaps = false;
  18275. renderTarget.activeCubeFace = 0;
  18276. renderer.render( scene, cameraPX, renderTarget );
  18277. renderTarget.activeCubeFace = 1;
  18278. renderer.render( scene, cameraNX, renderTarget );
  18279. renderTarget.activeCubeFace = 2;
  18280. renderer.render( scene, cameraPY, renderTarget );
  18281. renderTarget.activeCubeFace = 3;
  18282. renderer.render( scene, cameraNY, renderTarget );
  18283. renderTarget.activeCubeFace = 4;
  18284. renderer.render( scene, cameraPZ, renderTarget );
  18285. renderTarget.generateMipmaps = generateMipmaps;
  18286. renderTarget.activeCubeFace = 5;
  18287. renderer.render( scene, cameraNZ, renderTarget );
  18288. };
  18289. };
  18290. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18291. /*
  18292. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18293. *
  18294. * A general perpose camera, for setting FOV, Lens Focal Length,
  18295. * and switching between perspective and orthographic views easily.
  18296. * Use this only if you do not wish to manage
  18297. * both a Orthographic and Perspective Camera
  18298. *
  18299. */
  18300. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18301. THREE.Camera.call( this );
  18302. this.fov = fov;
  18303. this.left = -width / 2;
  18304. this.right = width / 2
  18305. this.top = height / 2;
  18306. this.bottom = -height / 2;
  18307. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18308. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18309. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18310. this.zoom = 1;
  18311. this.toPerspective();
  18312. var aspect = width/height;
  18313. };
  18314. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18315. THREE.CombinedCamera.prototype.toPerspective = function () {
  18316. // Switches to the Perspective Camera
  18317. this.near = this.cameraP.near;
  18318. this.far = this.cameraP.far;
  18319. this.cameraP.fov = this.fov / this.zoom ;
  18320. this.cameraP.updateProjectionMatrix();
  18321. this.projectionMatrix = this.cameraP.projectionMatrix;
  18322. this.inPerspectiveMode = true;
  18323. this.inOrthographicMode = false;
  18324. };
  18325. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18326. // Switches to the Orthographic camera estimating viewport from Perspective
  18327. var fov = this.fov;
  18328. var aspect = this.cameraP.aspect;
  18329. var near = this.cameraP.near;
  18330. var far = this.cameraP.far;
  18331. // The size that we set is the mid plane of the viewing frustum
  18332. var hyperfocus = ( near + far ) / 2;
  18333. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18334. var planeHeight = 2 * halfHeight;
  18335. var planeWidth = planeHeight * aspect;
  18336. var halfWidth = planeWidth / 2;
  18337. halfHeight /= this.zoom;
  18338. halfWidth /= this.zoom;
  18339. this.cameraO.left = -halfWidth;
  18340. this.cameraO.right = halfWidth;
  18341. this.cameraO.top = halfHeight;
  18342. this.cameraO.bottom = -halfHeight;
  18343. // this.cameraO.left = -farHalfWidth;
  18344. // this.cameraO.right = farHalfWidth;
  18345. // this.cameraO.top = farHalfHeight;
  18346. // this.cameraO.bottom = -farHalfHeight;
  18347. // this.cameraO.left = this.left / this.zoom;
  18348. // this.cameraO.right = this.right / this.zoom;
  18349. // this.cameraO.top = this.top / this.zoom;
  18350. // this.cameraO.bottom = this.bottom / this.zoom;
  18351. this.cameraO.updateProjectionMatrix();
  18352. this.near = this.cameraO.near;
  18353. this.far = this.cameraO.far;
  18354. this.projectionMatrix = this.cameraO.projectionMatrix;
  18355. this.inPerspectiveMode = false;
  18356. this.inOrthographicMode = true;
  18357. };
  18358. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18359. this.cameraP.aspect = width / height;
  18360. this.left = -width / 2;
  18361. this.right = width / 2
  18362. this.top = height / 2;
  18363. this.bottom = -height / 2;
  18364. };
  18365. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18366. this.fov = fov;
  18367. if ( this.inPerspectiveMode ) {
  18368. this.toPerspective();
  18369. } else {
  18370. this.toOrthographic();
  18371. }
  18372. };
  18373. // For mantaining similar API with PerspectiveCamera
  18374. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18375. if ( this.inPerspectiveMode ) {
  18376. this.toPerspective();
  18377. } else {
  18378. this.toPerspective();
  18379. this.toOrthographic();
  18380. }
  18381. };
  18382. /*
  18383. * Uses Focal Length (in mm) to estimate and set FOV
  18384. * 35mm (fullframe) camera is used if frame size is not specified;
  18385. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18386. */
  18387. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18388. if ( frameHeight === undefined ) frameHeight = 24;
  18389. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18390. this.setFov( fov );
  18391. return fov;
  18392. };
  18393. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18394. this.zoom = zoom;
  18395. if ( this.inPerspectiveMode ) {
  18396. this.toPerspective();
  18397. } else {
  18398. this.toOrthographic();
  18399. }
  18400. };
  18401. THREE.CombinedCamera.prototype.toFrontView = function() {
  18402. this.rotation.x = 0;
  18403. this.rotation.y = 0;
  18404. this.rotation.z = 0;
  18405. // should we be modifing the matrix instead?
  18406. this.rotationAutoUpdate = false;
  18407. };
  18408. THREE.CombinedCamera.prototype.toBackView = function() {
  18409. this.rotation.x = 0;
  18410. this.rotation.y = Math.PI;
  18411. this.rotation.z = 0;
  18412. this.rotationAutoUpdate = false;
  18413. };
  18414. THREE.CombinedCamera.prototype.toLeftView = function() {
  18415. this.rotation.x = 0;
  18416. this.rotation.y = - Math.PI / 2;
  18417. this.rotation.z = 0;
  18418. this.rotationAutoUpdate = false;
  18419. };
  18420. THREE.CombinedCamera.prototype.toRightView = function() {
  18421. this.rotation.x = 0;
  18422. this.rotation.y = Math.PI / 2;
  18423. this.rotation.z = 0;
  18424. this.rotationAutoUpdate = false;
  18425. };
  18426. THREE.CombinedCamera.prototype.toTopView = function() {
  18427. this.rotation.x = - Math.PI / 2;
  18428. this.rotation.y = 0;
  18429. this.rotation.z = 0;
  18430. this.rotationAutoUpdate = false;
  18431. };
  18432. THREE.CombinedCamera.prototype.toBottomView = function() {
  18433. this.rotation.x = Math.PI / 2;
  18434. this.rotation.y = 0;
  18435. this.rotation.z = 0;
  18436. this.rotationAutoUpdate = false;
  18437. };
  18438. /**
  18439. * @author alteredq / http://alteredqualia.com/
  18440. *
  18441. * - 3d asterisk shape (for line pieces THREE.Line)
  18442. */
  18443. THREE.AsteriskGeometry = function ( innerRadius, outerRadius ) {
  18444. THREE.Geometry.call( this );
  18445. var sd = innerRadius;
  18446. var ed = outerRadius;
  18447. var sd2 = 0.707 * sd;
  18448. var ed2 = 0.707 * ed;
  18449. var rays = [ [ sd, 0, 0 ], [ ed, 0, 0 ], [ -sd, 0, 0 ], [ -ed, 0, 0 ],
  18450. [ 0, sd, 0 ], [ 0, ed, 0 ], [ 0, -sd, 0 ], [ 0, -ed, 0 ],
  18451. [ 0, 0, sd ], [ 0, 0, ed ], [ 0, 0, -sd ], [ 0, 0, -ed ],
  18452. [ sd2, sd2, 0 ], [ ed2, ed2, 0 ], [ -sd2, -sd2, 0 ], [ -ed2, -ed2, 0 ],
  18453. [ sd2, -sd2, 0 ], [ ed2, -ed2, 0 ], [ -sd2, sd2, 0 ], [ -ed2, ed2, 0 ],
  18454. [ sd2, 0, sd2 ], [ ed2, 0, ed2 ], [ -sd2, 0, -sd2 ], [ -ed2, 0, -ed2 ],
  18455. [ sd2, 0, -sd2 ], [ ed2, 0, -ed2 ], [ -sd2, 0, sd2 ], [ -ed2, 0, ed2 ],
  18456. [ 0, sd2, sd2 ], [ 0, ed2, ed2 ], [ 0, -sd2, -sd2 ], [ 0, -ed2, -ed2 ],
  18457. [ 0, sd2, -sd2 ], [ 0, ed2, -ed2 ], [ 0, -sd2, sd2 ], [ 0, -ed2, ed2 ]
  18458. ];
  18459. for ( var i = 0, il = rays.length; i < il; i ++ ) {
  18460. var x = rays[ i ][ 0 ];
  18461. var y = rays[ i ][ 1 ];
  18462. var z = rays[ i ][ 2 ];
  18463. this.vertices.push( new THREE.Vector3( x, y, z ) );
  18464. }
  18465. };
  18466. THREE.AsteriskGeometry.prototype = Object.create( THREE.Geometry.prototype );/**
  18467. * @author hughes
  18468. */
  18469. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18470. THREE.Geometry.call( this );
  18471. radius = radius || 50;
  18472. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18473. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18474. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18475. var i, uvs = [],
  18476. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18477. this.vertices.push(center);
  18478. uvs.push( centerUV );
  18479. for ( i = 0; i <= segments; i ++ ) {
  18480. var vertex = new THREE.Vector3();
  18481. var segment = thetaStart + i / segments * thetaLength;
  18482. vertex.x = radius * Math.cos( segment );
  18483. vertex.y = radius * Math.sin( segment );
  18484. this.vertices.push( vertex );
  18485. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  18486. }
  18487. var n = new THREE.Vector3( 0, 0, -1 );
  18488. for ( i = 1; i <= segments; i ++ ) {
  18489. var v1 = i;
  18490. var v2 = i + 1 ;
  18491. var v3 = 0;
  18492. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  18493. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  18494. }
  18495. this.computeCentroids();
  18496. this.computeFaceNormals();
  18497. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18498. };
  18499. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18500. /**
  18501. * @author mrdoob / http://mrdoob.com/
  18502. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18503. */
  18504. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18505. THREE.Geometry.call( this );
  18506. var scope = this;
  18507. this.width = width;
  18508. this.height = height;
  18509. this.depth = depth;
  18510. this.widthSegments = widthSegments || 1;
  18511. this.heightSegments = heightSegments || 1;
  18512. this.depthSegments = depthSegments || 1;
  18513. var width_half = this.width / 2;
  18514. var height_half = this.height / 2;
  18515. var depth_half = this.depth / 2;
  18516. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18517. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18518. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18519. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18520. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18521. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18522. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18523. var w, ix, iy,
  18524. gridX = scope.widthSegments,
  18525. gridY = scope.heightSegments,
  18526. width_half = width / 2,
  18527. height_half = height / 2,
  18528. offset = scope.vertices.length;
  18529. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18530. w = 'z';
  18531. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18532. w = 'y';
  18533. gridY = scope.depthSegments;
  18534. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18535. w = 'x';
  18536. gridX = scope.depthSegments;
  18537. }
  18538. var gridX1 = gridX + 1,
  18539. gridY1 = gridY + 1,
  18540. segment_width = width / gridX,
  18541. segment_height = height / gridY,
  18542. normal = new THREE.Vector3();
  18543. normal[ w ] = depth > 0 ? 1 : - 1;
  18544. for ( iy = 0; iy < gridY1; iy ++ ) {
  18545. for ( ix = 0; ix < gridX1; ix ++ ) {
  18546. var vector = new THREE.Vector3();
  18547. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18548. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18549. vector[ w ] = depth;
  18550. scope.vertices.push( vector );
  18551. }
  18552. }
  18553. for ( iy = 0; iy < gridY; iy++ ) {
  18554. for ( ix = 0; ix < gridX; ix++ ) {
  18555. var a = ix + gridX1 * iy;
  18556. var b = ix + gridX1 * ( iy + 1 );
  18557. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18558. var d = ( ix + 1 ) + gridX1 * iy;
  18559. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  18560. face.normal.copy( normal );
  18561. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18562. face.materialIndex = materialIndex;
  18563. scope.faces.push( face );
  18564. scope.faceVertexUvs[ 0 ].push( [
  18565. new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
  18566. new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  18567. new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  18568. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
  18569. ] );
  18570. }
  18571. }
  18572. }
  18573. this.computeCentroids();
  18574. this.mergeVertices();
  18575. };
  18576. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18577. /**
  18578. * @author mrdoob / http://mrdoob.com/
  18579. */
  18580. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  18581. THREE.Geometry.call( this );
  18582. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18583. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18584. height = height !== undefined ? height : 100;
  18585. var heightHalf = height / 2;
  18586. var segmentsX = radiusSegments || 8;
  18587. var segmentsY = heightSegments || 1;
  18588. var x, y, vertices = [], uvs = [];
  18589. for ( y = 0; y <= segmentsY; y ++ ) {
  18590. var verticesRow = [];
  18591. var uvsRow = [];
  18592. var v = y / segmentsY;
  18593. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18594. for ( x = 0; x <= segmentsX; x ++ ) {
  18595. var u = x / segmentsX;
  18596. var vertex = new THREE.Vector3();
  18597. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18598. vertex.y = - v * height + heightHalf;
  18599. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18600. this.vertices.push( vertex );
  18601. verticesRow.push( this.vertices.length - 1 );
  18602. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18603. }
  18604. vertices.push( verticesRow );
  18605. uvs.push( uvsRow );
  18606. }
  18607. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18608. var na, nb;
  18609. for ( x = 0; x < segmentsX; x ++ ) {
  18610. if ( radiusTop !== 0 ) {
  18611. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18612. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18613. } else {
  18614. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18615. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18616. }
  18617. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18618. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18619. for ( y = 0; y < segmentsY; y ++ ) {
  18620. var v1 = vertices[ y ][ x ];
  18621. var v2 = vertices[ y + 1 ][ x ];
  18622. var v3 = vertices[ y + 1 ][ x + 1 ];
  18623. var v4 = vertices[ y ][ x + 1 ];
  18624. var n1 = na.clone();
  18625. var n2 = na.clone();
  18626. var n3 = nb.clone();
  18627. var n4 = nb.clone();
  18628. var uv1 = uvs[ y ][ x ].clone();
  18629. var uv2 = uvs[ y + 1 ][ x ].clone();
  18630. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18631. var uv4 = uvs[ y ][ x + 1 ].clone();
  18632. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18633. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18634. }
  18635. }
  18636. // top cap
  18637. if ( !openEnded && radiusTop > 0 ) {
  18638. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18639. for ( x = 0; x < segmentsX; x ++ ) {
  18640. var v1 = vertices[ 0 ][ x ];
  18641. var v2 = vertices[ 0 ][ x + 1 ];
  18642. var v3 = this.vertices.length - 1;
  18643. var n1 = new THREE.Vector3( 0, 1, 0 );
  18644. var n2 = new THREE.Vector3( 0, 1, 0 );
  18645. var n3 = new THREE.Vector3( 0, 1, 0 );
  18646. var uv1 = uvs[ 0 ][ x ].clone();
  18647. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18648. var uv3 = new THREE.Vector2( uv2.u, 0 );
  18649. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18650. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18651. }
  18652. }
  18653. // bottom cap
  18654. if ( !openEnded && radiusBottom > 0 ) {
  18655. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18656. for ( x = 0; x < segmentsX; x ++ ) {
  18657. var v1 = vertices[ y ][ x + 1 ];
  18658. var v2 = vertices[ y ][ x ];
  18659. var v3 = this.vertices.length - 1;
  18660. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18661. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18662. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18663. var uv1 = uvs[ y ][ x + 1 ].clone();
  18664. var uv2 = uvs[ y ][ x ].clone();
  18665. var uv3 = new THREE.Vector2( uv2.u, 1 );
  18666. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18667. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18668. }
  18669. }
  18670. this.computeCentroids();
  18671. this.computeFaceNormals();
  18672. }
  18673. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18674. /**
  18675. * @author zz85 / http://www.lab4games.net/zz85/blog
  18676. *
  18677. * Creates extruded geometry from a path shape.
  18678. *
  18679. * parameters = {
  18680. *
  18681. * size: <float>, // size of the text
  18682. * height: <float>, // thickness to extrude text
  18683. * curveSegments: <int>, // number of points on the curves
  18684. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18685. * amount: <int>, // Amount
  18686. *
  18687. * bevelEnabled: <bool>, // turn on bevel
  18688. * bevelThickness: <float>, // how deep into text bevel goes
  18689. * bevelSize: <float>, // how far from text outline is bevel
  18690. * bevelSegments: <int>, // number of bevel layers
  18691. *
  18692. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18693. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18694. *
  18695. * material: <int> // material index for front and back faces
  18696. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18697. * uvGenerator: <Object> // object that provides UV generator functions
  18698. *
  18699. * }
  18700. **/
  18701. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18702. if ( typeof( shapes ) === "undefined" ) {
  18703. shapes = [];
  18704. return;
  18705. }
  18706. THREE.Geometry.call( this );
  18707. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18708. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18709. this.addShapeList( shapes, options );
  18710. this.computeCentroids();
  18711. this.computeFaceNormals();
  18712. // can't really use automatic vertex normals
  18713. // as then front and back sides get smoothed too
  18714. // should do separate smoothing just for sides
  18715. //this.computeVertexNormals();
  18716. //console.log( "took", ( Date.now() - startTime ) );
  18717. };
  18718. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18719. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18720. var sl = shapes.length;
  18721. for ( var s = 0; s < sl; s ++ ) {
  18722. var shape = shapes[ s ];
  18723. this.addShape( shape, options );
  18724. }
  18725. };
  18726. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18727. var amount = options.amount !== undefined ? options.amount : 100;
  18728. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18729. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18730. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18731. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18732. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18733. var steps = options.steps !== undefined ? options.steps : 1;
  18734. var extrudePath = options.extrudePath;
  18735. var extrudePts, extrudeByPath = false;
  18736. var material = options.material;
  18737. var extrudeMaterial = options.extrudeMaterial;
  18738. // Use default WorldUVGenerator if no UV generators are specified.
  18739. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18740. var shapebb = this.shapebb;
  18741. //shapebb = shape.getBoundingBox();
  18742. var splineTube, binormal, normal, position2;
  18743. if ( extrudePath ) {
  18744. extrudePts = extrudePath.getSpacedPoints( steps );
  18745. extrudeByPath = true;
  18746. bevelEnabled = false; // bevels not supported for path extrusion
  18747. // SETUP TNB variables
  18748. // Reuse TNB from TubeGeomtry for now.
  18749. // TODO1 - have a .isClosed in spline?
  18750. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18751. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18752. binormal = new THREE.Vector3();
  18753. normal = new THREE.Vector3();
  18754. position2 = new THREE.Vector3();
  18755. }
  18756. // Safeguards if bevels are not enabled
  18757. if ( ! bevelEnabled ) {
  18758. bevelSegments = 0;
  18759. bevelThickness = 0;
  18760. bevelSize = 0;
  18761. }
  18762. // Variables initalization
  18763. var ahole, h, hl; // looping of holes
  18764. var scope = this;
  18765. var bevelPoints = [];
  18766. var shapesOffset = this.vertices.length;
  18767. var shapePoints = shape.extractPoints( curveSegments );
  18768. var vertices = shapePoints.shape;
  18769. var holes = shapePoints.holes;
  18770. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18771. if ( reverse ) {
  18772. vertices = vertices.reverse();
  18773. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18774. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18775. ahole = holes[ h ];
  18776. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18777. holes[ h ] = ahole.reverse();
  18778. }
  18779. }
  18780. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18781. }
  18782. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18783. /* Vertices */
  18784. var contour = vertices; // vertices has all points but contour has only points of circumference
  18785. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18786. ahole = holes[ h ];
  18787. vertices = vertices.concat( ahole );
  18788. }
  18789. function scalePt2 ( pt, vec, size ) {
  18790. if ( !vec ) console.log( "die" );
  18791. return vec.clone().multiplyScalar( size ).add( pt );
  18792. }
  18793. var b, bs, t, z,
  18794. vert, vlen = vertices.length,
  18795. face, flen = faces.length,
  18796. cont, clen = contour.length;
  18797. // Find directions for point movement
  18798. var RAD_TO_DEGREES = 180 / Math.PI;
  18799. function getBevelVec( pt_i, pt_j, pt_k ) {
  18800. // Algorithm 2
  18801. return getBevelVec2( pt_i, pt_j, pt_k );
  18802. }
  18803. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18804. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18805. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18806. if ( anglea > angleb ) {
  18807. angleb += Math.PI * 2;
  18808. }
  18809. var anglec = ( anglea + angleb ) / 2;
  18810. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18811. var x = - Math.cos( anglec );
  18812. var y = - Math.sin( anglec );
  18813. var vec = new THREE.Vector2( x, y ); //.normalize();
  18814. return vec;
  18815. }
  18816. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18817. var a = THREE.ExtrudeGeometry.__v1,
  18818. b = THREE.ExtrudeGeometry.__v2,
  18819. v_hat = THREE.ExtrudeGeometry.__v3,
  18820. w_hat = THREE.ExtrudeGeometry.__v4,
  18821. p = THREE.ExtrudeGeometry.__v5,
  18822. q = THREE.ExtrudeGeometry.__v6,
  18823. v, w,
  18824. v_dot_w_hat, q_sub_p_dot_w_hat,
  18825. s, intersection;
  18826. // good reading for line-line intersection
  18827. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18828. // define a as vector j->i
  18829. // define b as vectot k->i
  18830. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18831. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18832. // get unit vectors
  18833. v = a.normalize();
  18834. w = b.normalize();
  18835. // normals from pt i
  18836. v_hat.set( -v.y, v.x );
  18837. w_hat.set( w.y, -w.x );
  18838. // pts from i
  18839. p.copy( pt_i ).add( v_hat );
  18840. q.copy( pt_i ).add( w_hat );
  18841. if ( p.equals( q ) ) {
  18842. //console.log("Warning: lines are straight");
  18843. return w_hat.clone();
  18844. }
  18845. // Points from j, k. helps prevents points cross overover most of the time
  18846. p.copy( pt_j ).add( v_hat );
  18847. q.copy( pt_k ).add( w_hat );
  18848. v_dot_w_hat = v.dot( w_hat );
  18849. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  18850. // We should not reach these conditions
  18851. if ( v_dot_w_hat === 0 ) {
  18852. console.log( "Either infinite or no solutions!" );
  18853. if ( q_sub_p_dot_w_hat === 0 ) {
  18854. console.log( "Its finite solutions." );
  18855. } else {
  18856. console.log( "Too bad, no solutions." );
  18857. }
  18858. }
  18859. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18860. if ( s < 0 ) {
  18861. // in case of emergecy, revert to algorithm 1.
  18862. return getBevelVec1( pt_i, pt_j, pt_k );
  18863. }
  18864. intersection = v.multiplyScalar( s ).add( p );
  18865. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18866. }
  18867. var contourMovements = [];
  18868. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18869. if ( j === il ) j = 0;
  18870. if ( k === il ) k = 0;
  18871. // (j)---(i)---(k)
  18872. // console.log('i,j,k', i, j , k)
  18873. var pt_i = contour[ i ];
  18874. var pt_j = contour[ j ];
  18875. var pt_k = contour[ k ];
  18876. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18877. }
  18878. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18879. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18880. ahole = holes[ h ];
  18881. oneHoleMovements = [];
  18882. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18883. if ( j === il ) j = 0;
  18884. if ( k === il ) k = 0;
  18885. // (j)---(i)---(k)
  18886. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18887. }
  18888. holesMovements.push( oneHoleMovements );
  18889. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18890. }
  18891. // Loop bevelSegments, 1 for the front, 1 for the back
  18892. for ( b = 0; b < bevelSegments; b ++ ) {
  18893. //for ( b = bevelSegments; b > 0; b -- ) {
  18894. t = b / bevelSegments;
  18895. z = bevelThickness * ( 1 - t );
  18896. //z = bevelThickness * t;
  18897. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18898. //bs = bevelSize * t ; // linear
  18899. // contract shape
  18900. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18901. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18902. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18903. v( vert.x, vert.y, - z );
  18904. }
  18905. // expand holes
  18906. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18907. ahole = holes[ h ];
  18908. oneHoleMovements = holesMovements[ h ];
  18909. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18910. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18911. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18912. v( vert.x, vert.y, -z );
  18913. }
  18914. }
  18915. }
  18916. bs = bevelSize;
  18917. // Back facing vertices
  18918. for ( i = 0; i < vlen; i ++ ) {
  18919. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18920. if ( !extrudeByPath ) {
  18921. v( vert.x, vert.y, 0 );
  18922. } else {
  18923. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18924. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18925. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18926. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  18927. v( position2.x, position2.y, position2.z );
  18928. }
  18929. }
  18930. // Add stepped vertices...
  18931. // Including front facing vertices
  18932. var s;
  18933. for ( s = 1; s <= steps; s ++ ) {
  18934. for ( i = 0; i < vlen; i ++ ) {
  18935. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18936. if ( !extrudeByPath ) {
  18937. v( vert.x, vert.y, amount / steps * s );
  18938. } else {
  18939. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18940. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18941. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18942. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  18943. v( position2.x, position2.y, position2.z );
  18944. }
  18945. }
  18946. }
  18947. // Add bevel segments planes
  18948. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18949. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18950. t = b / bevelSegments;
  18951. z = bevelThickness * ( 1 - t );
  18952. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18953. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18954. // contract shape
  18955. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18956. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18957. v( vert.x, vert.y, amount + z );
  18958. }
  18959. // expand holes
  18960. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18961. ahole = holes[ h ];
  18962. oneHoleMovements = holesMovements[ h ];
  18963. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18964. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18965. if ( !extrudeByPath ) {
  18966. v( vert.x, vert.y, amount + z );
  18967. } else {
  18968. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18969. }
  18970. }
  18971. }
  18972. }
  18973. /* Faces */
  18974. // Top and bottom faces
  18975. buildLidFaces();
  18976. // Sides faces
  18977. buildSideFaces();
  18978. ///// Internal functions
  18979. function buildLidFaces() {
  18980. if ( bevelEnabled ) {
  18981. var layer = 0 ; // steps + 1
  18982. var offset = vlen * layer;
  18983. // Bottom faces
  18984. for ( i = 0; i < flen; i ++ ) {
  18985. face = faces[ i ];
  18986. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  18987. }
  18988. layer = steps + bevelSegments * 2;
  18989. offset = vlen * layer;
  18990. // Top faces
  18991. for ( i = 0; i < flen; i ++ ) {
  18992. face = faces[ i ];
  18993. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  18994. }
  18995. } else {
  18996. // Bottom faces
  18997. for ( i = 0; i < flen; i++ ) {
  18998. face = faces[ i ];
  18999. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19000. }
  19001. // Top faces
  19002. for ( i = 0; i < flen; i ++ ) {
  19003. face = faces[ i ];
  19004. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19005. }
  19006. }
  19007. }
  19008. // Create faces for the z-sides of the shape
  19009. function buildSideFaces() {
  19010. var layeroffset = 0;
  19011. sidewalls( contour, layeroffset );
  19012. layeroffset += contour.length;
  19013. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19014. ahole = holes[ h ];
  19015. sidewalls( ahole, layeroffset );
  19016. //, true
  19017. layeroffset += ahole.length;
  19018. }
  19019. }
  19020. function sidewalls( contour, layeroffset ) {
  19021. var j, k;
  19022. i = contour.length;
  19023. while ( --i >= 0 ) {
  19024. j = i;
  19025. k = i - 1;
  19026. if ( k < 0 ) k = contour.length - 1;
  19027. //console.log('b', i,j, i-1, k,vertices.length);
  19028. var s = 0, sl = steps + bevelSegments * 2;
  19029. for ( s = 0; s < sl; s ++ ) {
  19030. var slen1 = vlen * s;
  19031. var slen2 = vlen * ( s + 1 );
  19032. var a = layeroffset + j + slen1,
  19033. b = layeroffset + k + slen1,
  19034. c = layeroffset + k + slen2,
  19035. d = layeroffset + j + slen2;
  19036. f4( a, b, c, d, contour, s, sl, j, k );
  19037. }
  19038. }
  19039. }
  19040. function v( x, y, z ) {
  19041. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19042. }
  19043. function f3( a, b, c, isBottom ) {
  19044. a += shapesOffset;
  19045. b += shapesOffset;
  19046. c += shapesOffset;
  19047. // normal, color, material
  19048. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19049. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19050. scope.faceVertexUvs[ 0 ].push( uvs );
  19051. }
  19052. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19053. a += shapesOffset;
  19054. b += shapesOffset;
  19055. c += shapesOffset;
  19056. d += shapesOffset;
  19057. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  19058. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19059. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19060. scope.faceVertexUvs[ 0 ].push( uvs );
  19061. }
  19062. };
  19063. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19064. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19065. var ax = geometry.vertices[ indexA ].x,
  19066. ay = geometry.vertices[ indexA ].y,
  19067. bx = geometry.vertices[ indexB ].x,
  19068. by = geometry.vertices[ indexB ].y,
  19069. cx = geometry.vertices[ indexC ].x,
  19070. cy = geometry.vertices[ indexC ].y;
  19071. return [
  19072. new THREE.Vector2( ax, ay ),
  19073. new THREE.Vector2( bx, by ),
  19074. new THREE.Vector2( cx, cy )
  19075. ];
  19076. },
  19077. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19078. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19079. },
  19080. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19081. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19082. contourIndex1, contourIndex2 ) {
  19083. var ax = geometry.vertices[ indexA ].x,
  19084. ay = geometry.vertices[ indexA ].y,
  19085. az = geometry.vertices[ indexA ].z,
  19086. bx = geometry.vertices[ indexB ].x,
  19087. by = geometry.vertices[ indexB ].y,
  19088. bz = geometry.vertices[ indexB ].z,
  19089. cx = geometry.vertices[ indexC ].x,
  19090. cy = geometry.vertices[ indexC ].y,
  19091. cz = geometry.vertices[ indexC ].z,
  19092. dx = geometry.vertices[ indexD ].x,
  19093. dy = geometry.vertices[ indexD ].y,
  19094. dz = geometry.vertices[ indexD ].z;
  19095. if ( Math.abs( ay - by ) < 0.01 ) {
  19096. return [
  19097. new THREE.Vector2( ax, 1 - az ),
  19098. new THREE.Vector2( bx, 1 - bz ),
  19099. new THREE.Vector2( cx, 1 - cz ),
  19100. new THREE.Vector2( dx, 1 - dz )
  19101. ];
  19102. } else {
  19103. return [
  19104. new THREE.Vector2( ay, 1 - az ),
  19105. new THREE.Vector2( by, 1 - bz ),
  19106. new THREE.Vector2( cy, 1 - cz ),
  19107. new THREE.Vector2( dy, 1 - dz )
  19108. ];
  19109. }
  19110. }
  19111. };
  19112. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19113. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19114. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19115. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19116. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19117. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19118. /**
  19119. * @author jonobr1 / http://jonobr1.com
  19120. *
  19121. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19122. * ExtrudeGeometry.
  19123. *
  19124. * parameters = {
  19125. *
  19126. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19127. *
  19128. * material: <int> // material index for front and back faces
  19129. * uvGenerator: <Object> // object that provides UV generator functions
  19130. *
  19131. * }
  19132. **/
  19133. THREE.ShapeGeometry = function ( shapes, options ) {
  19134. THREE.Geometry.call( this );
  19135. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19136. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19137. this.addShapeList( shapes, options );
  19138. this.computeCentroids();
  19139. this.computeFaceNormals();
  19140. };
  19141. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19142. /**
  19143. * Add an array of shapes to THREE.ShapeGeometry.
  19144. */
  19145. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19146. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19147. this.addShape( shapes[ i ], options );
  19148. }
  19149. return this;
  19150. };
  19151. /**
  19152. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19153. */
  19154. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19155. if ( options === undefined ) options = {};
  19156. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19157. var material = options.material;
  19158. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19159. var shapebb = this.shapebb;
  19160. //
  19161. var i, l, hole, s;
  19162. var shapesOffset = this.vertices.length;
  19163. var shapePoints = shape.extractPoints( curveSegments );
  19164. var vertices = shapePoints.shape;
  19165. var holes = shapePoints.holes;
  19166. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19167. if ( reverse ) {
  19168. vertices = vertices.reverse();
  19169. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19170. for ( i = 0, l = holes.length; i < l; i++ ) {
  19171. hole = holes[ i ];
  19172. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19173. holes[ i ] = hole.reverse();
  19174. }
  19175. }
  19176. reverse = false;
  19177. }
  19178. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19179. // Vertices
  19180. var contour = vertices;
  19181. for ( i = 0, l = holes.length; i < l; i++ ) {
  19182. hole = holes[ i ];
  19183. vertices = vertices.concat( hole );
  19184. }
  19185. //
  19186. var vert, vlen = vertices.length;
  19187. var face, flen = faces.length;
  19188. var cont, clen = contour.length;
  19189. for ( i = 0; i < vlen; i++ ) {
  19190. vert = vertices[ i ];
  19191. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19192. }
  19193. for ( i = 0; i < flen; i++ ) {
  19194. face = faces[ i ];
  19195. var a = face[ 0 ] + shapesOffset;
  19196. var b = face[ 1 ] + shapesOffset;
  19197. var c = face[ 2 ] + shapesOffset;
  19198. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19199. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19200. }
  19201. };
  19202. /**
  19203. * @author astrodud / http://astrodud.isgreat.org/
  19204. * @author zz85 / https://github.com/zz85
  19205. * @author bhouston / http://exocortex.com
  19206. */
  19207. // points - to create a closed torus, one must use a set of points
  19208. // like so: [ a, b, c, d, a ], see first is the same as last.
  19209. // segments - the number of circumference segments to create
  19210. // phiStart - the starting radian
  19211. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19212. // 2*pi is a closed lathe, less than 2PI is a portion.
  19213. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19214. THREE.Geometry.call( this );
  19215. segments = segments || 12;
  19216. phiStart = phiStart || 0;
  19217. phiLength = phiLength || 2 * Math.PI;
  19218. var inversePointLength = 1.0 / ( points.length - 1 );
  19219. var inverseSegments = 1.0 / segments;
  19220. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19221. var phi = phiStart + i * inverseSegments * phiLength;
  19222. var c = Math.cos( phi ),
  19223. s = Math.sin( phi );
  19224. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19225. var pt = points[ j ];
  19226. var vertex = new THREE.Vector3();
  19227. vertex.x = c * pt.x - s * pt.y;
  19228. vertex.y = s * pt.x + c * pt.y;
  19229. vertex.z = pt.z;
  19230. this.vertices.push( vertex );
  19231. }
  19232. }
  19233. var np = points.length;
  19234. for ( var i = 0, il = segments; i < il; i ++ ) {
  19235. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19236. var base = j + np * i;
  19237. var a = base;
  19238. var b = base + np;
  19239. var c = base + 1 + np;
  19240. var d = base + 1;
  19241. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19242. var u0 = i * inverseSegments;
  19243. var v0 = j * inversePointLength;
  19244. var u1 = u0 + inverseSegments;
  19245. var v1 = v0 + inversePointLength;
  19246. this.faceVertexUvs[ 0 ].push( [
  19247. new THREE.Vector2( u0, v0 ),
  19248. new THREE.Vector2( u1, v0 ),
  19249. new THREE.Vector2( u1, v1 ),
  19250. new THREE.Vector2( u0, v1 )
  19251. ] );
  19252. }
  19253. }
  19254. this.mergeVertices();
  19255. this.computeCentroids();
  19256. this.computeFaceNormals();
  19257. this.computeVertexNormals();
  19258. };
  19259. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19260. /**
  19261. * @author mrdoob / http://mrdoob.com/
  19262. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19263. */
  19264. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19265. THREE.Geometry.call( this );
  19266. this.width = width;
  19267. this.height = height;
  19268. this.widthSegments = widthSegments || 1;
  19269. this.heightSegments = heightSegments || 1;
  19270. var ix, iz;
  19271. var width_half = width / 2;
  19272. var height_half = height / 2;
  19273. var gridX = this.widthSegments;
  19274. var gridZ = this.heightSegments;
  19275. var gridX1 = gridX + 1;
  19276. var gridZ1 = gridZ + 1;
  19277. var segment_width = this.width / gridX;
  19278. var segment_height = this.height / gridZ;
  19279. var normal = new THREE.Vector3( 0, 0, 1 );
  19280. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19281. for ( ix = 0; ix < gridX1; ix ++ ) {
  19282. var x = ix * segment_width - width_half;
  19283. var y = iz * segment_height - height_half;
  19284. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19285. }
  19286. }
  19287. for ( iz = 0; iz < gridZ; iz ++ ) {
  19288. for ( ix = 0; ix < gridX; ix ++ ) {
  19289. var a = ix + gridX1 * iz;
  19290. var b = ix + gridX1 * ( iz + 1 );
  19291. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19292. var d = ( ix + 1 ) + gridX1 * iz;
  19293. var face = new THREE.Face4( a, b, c, d );
  19294. face.normal.copy( normal );
  19295. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19296. this.faces.push( face );
  19297. this.faceVertexUvs[ 0 ].push( [
  19298. new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
  19299. new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19300. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19301. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19302. ] );
  19303. }
  19304. }
  19305. this.computeCentroids();
  19306. };
  19307. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19308. /**
  19309. * @author Kaleb Murphy
  19310. */
  19311. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19312. THREE.Geometry.call( this );
  19313. innerRadius = innerRadius || 0;
  19314. outerRadius = outerRadius || 50;
  19315. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19316. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19317. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19318. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19319. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19320. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19321. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19322. var vertex = new THREE.Vector3();
  19323. var segment = thetaStart + o / thetaSegments * thetaLength;
  19324. vertex.x = radius * Math.cos( segment );
  19325. vertex.y = radius * Math.sin( segment );
  19326. this.vertices.push( vertex );
  19327. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  19328. }
  19329. radius += radiusStep;
  19330. }
  19331. var n = new THREE.Vector3( 0, 0, 1 );
  19332. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19333. var thetaSegment = i * thetaSegments;
  19334. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19335. var segment = o + thetaSegment;
  19336. var v1 = segment + i;
  19337. var v2 = segment + thetaSegments + i;
  19338. var v3 = segment + thetaSegments + 1 + i;
  19339. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19340. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19341. v1 = segment + i;
  19342. v2 = segment + thetaSegments + 1 + i;
  19343. v3 = segment + 1 + i;
  19344. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19345. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19346. }
  19347. }
  19348. this.computeCentroids();
  19349. this.computeFaceNormals();
  19350. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19351. };
  19352. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19353. /**
  19354. * @author mrdoob / http://mrdoob.com/
  19355. */
  19356. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19357. THREE.Geometry.call( this );
  19358. this.radius = radius || 50;
  19359. this.widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19360. this.heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19361. phiStart = phiStart !== undefined ? phiStart : 0;
  19362. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19363. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19364. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19365. var x, y, vertices = [], uvs = [];
  19366. for ( y = 0; y <= this.heightSegments; y ++ ) {
  19367. var verticesRow = [];
  19368. var uvsRow = [];
  19369. for ( x = 0; x <= this.widthSegments; x ++ ) {
  19370. var u = x / this.widthSegments;
  19371. var v = y / this.heightSegments;
  19372. var vertex = new THREE.Vector3();
  19373. vertex.x = - this.radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19374. vertex.y = this.radius * Math.cos( thetaStart + v * thetaLength );
  19375. vertex.z = this.radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19376. this.vertices.push( vertex );
  19377. verticesRow.push( this.vertices.length - 1 );
  19378. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19379. }
  19380. vertices.push( verticesRow );
  19381. uvs.push( uvsRow );
  19382. }
  19383. for ( y = 0; y < this.heightSegments; y ++ ) {
  19384. for ( x = 0; x < this.widthSegments; x ++ ) {
  19385. var v1 = vertices[ y ][ x + 1 ];
  19386. var v2 = vertices[ y ][ x ];
  19387. var v3 = vertices[ y + 1 ][ x ];
  19388. var v4 = vertices[ y + 1 ][ x + 1 ];
  19389. var n1 = this.vertices[ v1 ].clone().normalize();
  19390. var n2 = this.vertices[ v2 ].clone().normalize();
  19391. var n3 = this.vertices[ v3 ].clone().normalize();
  19392. var n4 = this.vertices[ v4 ].clone().normalize();
  19393. var uv1 = uvs[ y ][ x + 1 ].clone();
  19394. var uv2 = uvs[ y ][ x ].clone();
  19395. var uv3 = uvs[ y + 1 ][ x ].clone();
  19396. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19397. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19398. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19399. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19400. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19401. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19402. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19403. } else {
  19404. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19405. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19406. }
  19407. }
  19408. }
  19409. this.computeCentroids();
  19410. this.computeFaceNormals();
  19411. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19412. };
  19413. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19414. /**
  19415. * @author zz85 / http://www.lab4games.net/zz85/blog
  19416. * @author alteredq / http://alteredqualia.com/
  19417. *
  19418. * For creating 3D text geometry in three.js
  19419. *
  19420. * Text = 3D Text
  19421. *
  19422. * parameters = {
  19423. * size: <float>, // size of the text
  19424. * height: <float>, // thickness to extrude text
  19425. * curveSegments: <int>, // number of points on the curves
  19426. *
  19427. * font: <string>, // font name
  19428. * weight: <string>, // font weight (normal, bold)
  19429. * style: <string>, // font style (normal, italics)
  19430. *
  19431. * bevelEnabled: <bool>, // turn on bevel
  19432. * bevelThickness: <float>, // how deep into text bevel goes
  19433. * bevelSize: <float>, // how far from text outline is bevel
  19434. * }
  19435. *
  19436. */
  19437. /* Usage Examples
  19438. // TextGeometry wrapper
  19439. var text3d = new TextGeometry( text, options );
  19440. // Complete manner
  19441. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19442. var text3d = new ExtrudeGeometry( textShapes, options );
  19443. */
  19444. THREE.TextGeometry = function ( text, parameters ) {
  19445. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19446. // translate parameters to ExtrudeGeometry API
  19447. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19448. // defaults
  19449. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19450. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19451. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19452. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19453. };
  19454. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19455. /**
  19456. * @author oosmoxiecode
  19457. * @author mrdoob / http://mrdoob.com/
  19458. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19459. */
  19460. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19461. THREE.Geometry.call( this );
  19462. var scope = this;
  19463. this.radius = radius || 100;
  19464. this.tube = tube || 40;
  19465. this.radialSegments = radialSegments || 8;
  19466. this.tubularSegments = tubularSegments || 6;
  19467. this.arc = arc || Math.PI * 2;
  19468. var center = new THREE.Vector3(), uvs = [], normals = [];
  19469. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19470. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19471. var u = i / this.tubularSegments * this.arc;
  19472. var v = j / this.radialSegments * Math.PI * 2;
  19473. center.x = this.radius * Math.cos( u );
  19474. center.y = this.radius * Math.sin( u );
  19475. var vertex = new THREE.Vector3();
  19476. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19477. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19478. vertex.z = this.tube * Math.sin( v );
  19479. this.vertices.push( vertex );
  19480. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19481. normals.push( vertex.clone().sub( center ).normalize() );
  19482. }
  19483. }
  19484. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19485. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19486. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19487. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19488. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19489. var d = ( this.tubularSegments + 1 ) * j + i;
  19490. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  19491. face.normal.add( normals[ a ] );
  19492. face.normal.add( normals[ b ] );
  19493. face.normal.add( normals[ c ] );
  19494. face.normal.add( normals[ d ] );
  19495. face.normal.normalize();
  19496. this.faces.push( face );
  19497. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19498. }
  19499. }
  19500. this.computeCentroids();
  19501. };
  19502. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19503. /**
  19504. * @author oosmoxiecode
  19505. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19506. */
  19507. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19508. THREE.Geometry.call( this );
  19509. var scope = this;
  19510. this.radius = radius || 100;
  19511. this.tube = tube || 40;
  19512. this.radialSegments = radialSegments || 64;
  19513. this.tubularSegments = tubularSegments || 8;
  19514. this.p = p || 2;
  19515. this.q = q || 3;
  19516. this.heightScale = heightScale || 1;
  19517. this.grid = new Array( this.radialSegments );
  19518. var tang = new THREE.Vector3();
  19519. var n = new THREE.Vector3();
  19520. var bitan = new THREE.Vector3();
  19521. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19522. this.grid[ i ] = new Array( this.tubularSegments );
  19523. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19524. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19525. var v = j / this.tubularSegments * 2 * Math.PI;
  19526. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  19527. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  19528. var cx, cy;
  19529. tang.subVectors( p2, p1 );
  19530. n.addVectors( p2, p1 );
  19531. bitan.crossVectors( tang, n );
  19532. n.crossVectors( bitan, tang );
  19533. bitan.normalize();
  19534. n.normalize();
  19535. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19536. cy = this.tube * Math.sin( v );
  19537. p1.x += cx * n.x + cy * bitan.x;
  19538. p1.y += cx * n.y + cy * bitan.y;
  19539. p1.z += cx * n.z + cy * bitan.z;
  19540. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  19541. }
  19542. }
  19543. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19544. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19545. var ip = ( i + 1 ) % this.radialSegments;
  19546. var jp = ( j + 1 ) % this.tubularSegments;
  19547. var a = this.grid[ i ][ j ];
  19548. var b = this.grid[ ip ][ j ];
  19549. var c = this.grid[ ip ][ jp ];
  19550. var d = this.grid[ i ][ jp ];
  19551. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19552. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19553. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19554. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19555. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19556. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  19557. }
  19558. }
  19559. this.computeCentroids();
  19560. this.computeFaceNormals();
  19561. this.computeVertexNormals();
  19562. function vert( x, y, z ) {
  19563. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19564. }
  19565. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  19566. var cu = Math.cos( u );
  19567. var cv = Math.cos( v );
  19568. var su = Math.sin( u );
  19569. var quOverP = in_q / in_p * u;
  19570. var cs = Math.cos( quOverP );
  19571. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19572. var ty = radius * ( 2 + cs ) * su * 0.5;
  19573. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19574. return new THREE.Vector3( tx, ty, tz );
  19575. }
  19576. };
  19577. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19578. /**
  19579. * @author WestLangley / https://github.com/WestLangley
  19580. * @author zz85 / https://github.com/zz85
  19581. * @author miningold / https://github.com/miningold
  19582. *
  19583. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19584. *
  19585. * Creates a tube which extrudes along a 3d spline
  19586. *
  19587. * Uses parallel transport frames as described in
  19588. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19589. */
  19590. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  19591. THREE.Geometry.call( this );
  19592. this.path = path;
  19593. this.segments = segments || 64;
  19594. this.radius = radius || 1;
  19595. this.radiusSegments = radiusSegments || 8;
  19596. this.closed = closed || false;
  19597. if ( debug ) this.debug = new THREE.Object3D();
  19598. this.grid = [];
  19599. var scope = this,
  19600. tangent,
  19601. normal,
  19602. binormal,
  19603. numpoints = this.segments + 1,
  19604. x, y, z,
  19605. tx, ty, tz,
  19606. u, v,
  19607. cx, cy,
  19608. pos, pos2 = new THREE.Vector3(),
  19609. i, j,
  19610. ip, jp,
  19611. a, b, c, d,
  19612. uva, uvb, uvc, uvd;
  19613. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19614. tangents = frames.tangents,
  19615. normals = frames.normals,
  19616. binormals = frames.binormals;
  19617. // proxy internals
  19618. this.tangents = tangents;
  19619. this.normals = normals;
  19620. this.binormals = binormals;
  19621. function vert( x, y, z ) {
  19622. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19623. }
  19624. // consruct the grid
  19625. for ( i = 0; i < numpoints; i++ ) {
  19626. this.grid[ i ] = [];
  19627. u = i / ( numpoints - 1 );
  19628. pos = path.getPointAt( u );
  19629. tangent = tangents[ i ];
  19630. normal = normals[ i ];
  19631. binormal = binormals[ i ];
  19632. if ( this.debug ) {
  19633. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  19634. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  19635. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  19636. }
  19637. for ( j = 0; j < this.radiusSegments; j++ ) {
  19638. v = j / this.radiusSegments * 2 * Math.PI;
  19639. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19640. cy = this.radius * Math.sin( v );
  19641. pos2.copy( pos );
  19642. pos2.x += cx * normal.x + cy * binormal.x;
  19643. pos2.y += cx * normal.y + cy * binormal.y;
  19644. pos2.z += cx * normal.z + cy * binormal.z;
  19645. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19646. }
  19647. }
  19648. // construct the mesh
  19649. for ( i = 0; i < this.segments; i++ ) {
  19650. for ( j = 0; j < this.radiusSegments; j++ ) {
  19651. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  19652. jp = (j + 1) % this.radiusSegments;
  19653. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19654. b = this.grid[ ip ][ j ];
  19655. c = this.grid[ ip ][ jp ];
  19656. d = this.grid[ i ][ jp ];
  19657. uva = new THREE.Vector2( i / this.segments, j / this.radiusSegments );
  19658. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radiusSegments );
  19659. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  19660. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radiusSegments );
  19661. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19662. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  19663. }
  19664. }
  19665. this.computeCentroids();
  19666. this.computeFaceNormals();
  19667. this.computeVertexNormals();
  19668. };
  19669. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19670. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19671. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19672. var tangent = new THREE.Vector3(),
  19673. normal = new THREE.Vector3(),
  19674. binormal = new THREE.Vector3(),
  19675. tangents = [],
  19676. normals = [],
  19677. binormals = [],
  19678. vec = new THREE.Vector3(),
  19679. mat = new THREE.Matrix4(),
  19680. numpoints = segments + 1,
  19681. theta,
  19682. epsilon = 0.0001,
  19683. smallest,
  19684. tx, ty, tz,
  19685. i, u, v;
  19686. // expose internals
  19687. this.tangents = tangents;
  19688. this.normals = normals;
  19689. this.binormals = binormals;
  19690. // compute the tangent vectors for each segment on the path
  19691. for ( i = 0; i < numpoints; i++ ) {
  19692. u = i / ( numpoints - 1 );
  19693. tangents[ i ] = path.getTangentAt( u );
  19694. tangents[ i ].normalize();
  19695. }
  19696. initialNormal3();
  19697. function initialNormal1(lastBinormal) {
  19698. // fixed start binormal. Has dangers of 0 vectors
  19699. normals[ 0 ] = new THREE.Vector3();
  19700. binormals[ 0 ] = new THREE.Vector3();
  19701. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19702. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19703. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19704. }
  19705. function initialNormal2() {
  19706. // This uses the Frenet-Serret formula for deriving binormal
  19707. var t2 = path.getTangentAt( epsilon );
  19708. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19709. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19710. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19711. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19712. }
  19713. function initialNormal3() {
  19714. // select an initial normal vector perpenicular to the first tangent vector,
  19715. // and in the direction of the smallest tangent xyz component
  19716. normals[ 0 ] = new THREE.Vector3();
  19717. binormals[ 0 ] = new THREE.Vector3();
  19718. smallest = Number.MAX_VALUE;
  19719. tx = Math.abs( tangents[ 0 ].x );
  19720. ty = Math.abs( tangents[ 0 ].y );
  19721. tz = Math.abs( tangents[ 0 ].z );
  19722. if ( tx <= smallest ) {
  19723. smallest = tx;
  19724. normal.set( 1, 0, 0 );
  19725. }
  19726. if ( ty <= smallest ) {
  19727. smallest = ty;
  19728. normal.set( 0, 1, 0 );
  19729. }
  19730. if ( tz <= smallest ) {
  19731. normal.set( 0, 0, 1 );
  19732. }
  19733. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19734. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19735. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19736. }
  19737. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19738. for ( i = 1; i < numpoints; i++ ) {
  19739. normals[ i ] = normals[ i-1 ].clone();
  19740. binormals[ i ] = binormals[ i-1 ].clone();
  19741. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  19742. if ( vec.length() > epsilon ) {
  19743. vec.normalize();
  19744. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  19745. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19746. }
  19747. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19748. }
  19749. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19750. if ( closed ) {
  19751. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  19752. theta /= ( numpoints - 1 );
  19753. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19754. theta = -theta;
  19755. }
  19756. for ( i = 1; i < numpoints; i++ ) {
  19757. // twist a little...
  19758. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19759. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19760. }
  19761. }
  19762. };
  19763. /**
  19764. * @author clockworkgeek / https://github.com/clockworkgeek
  19765. * @author timothypratley / https://github.com/timothypratley
  19766. */
  19767. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19768. THREE.Geometry.call( this );
  19769. radius = radius || 1;
  19770. detail = detail || 0;
  19771. var that = this;
  19772. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19773. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19774. }
  19775. var midpoints = [], p = this.vertices;
  19776. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19777. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  19778. }
  19779. this.mergeVertices();
  19780. // Apply radius
  19781. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19782. this.vertices[ i ].multiplyScalar( radius );
  19783. }
  19784. // Project vector onto sphere's surface
  19785. function prepare( vector ) {
  19786. var vertex = vector.normalize().clone();
  19787. vertex.index = that.vertices.push( vertex ) - 1;
  19788. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19789. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19790. var v = inclination( vector ) / Math.PI + 0.5;
  19791. vertex.uv = new THREE.Vector2( u, 1 - v );
  19792. return vertex;
  19793. }
  19794. // Approximate a curved face with recursively sub-divided triangles.
  19795. function make( v1, v2, v3, detail ) {
  19796. if ( detail < 1 ) {
  19797. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19798. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19799. face.normal = face.centroid.clone().normalize();
  19800. that.faces.push( face );
  19801. var azi = azimuth( face.centroid );
  19802. that.faceVertexUvs[ 0 ].push( [
  19803. correctUV( v1.uv, v1, azi ),
  19804. correctUV( v2.uv, v2, azi ),
  19805. correctUV( v3.uv, v3, azi )
  19806. ] );
  19807. } else {
  19808. detail -= 1;
  19809. // split triangle into 4 smaller triangles
  19810. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  19811. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  19812. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  19813. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  19814. }
  19815. }
  19816. function midpoint( v1, v2 ) {
  19817. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  19818. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  19819. var mid = midpoints[ v1.index ][ v2.index ];
  19820. if ( mid === undefined ) {
  19821. // generate mean point and project to surface with prepare()
  19822. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  19823. new THREE.Vector3().addVectors( v1, v2 ).divideScalar( 2 )
  19824. );
  19825. }
  19826. return mid;
  19827. }
  19828. // Angle around the Y axis, counter-clockwise when looking from above.
  19829. function azimuth( vector ) {
  19830. return Math.atan2( vector.z, -vector.x );
  19831. }
  19832. // Angle above the XZ plane.
  19833. function inclination( vector ) {
  19834. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19835. }
  19836. // Texture fixing helper. Spheres have some odd behaviours.
  19837. function correctUV( uv, vector, azimuth ) {
  19838. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19839. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19840. return uv;
  19841. }
  19842. this.computeCentroids();
  19843. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19844. };
  19845. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19846. /**
  19847. * @author timothypratley / https://github.com/timothypratley
  19848. */
  19849. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19850. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19851. var vertices = [
  19852. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19853. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19854. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19855. ];
  19856. var faces = [
  19857. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19858. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19859. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19860. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19861. ];
  19862. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19863. };
  19864. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19865. /**
  19866. * @author timothypratley / https://github.com/timothypratley
  19867. */
  19868. THREE.OctahedronGeometry = function ( radius, detail ) {
  19869. var vertices = [
  19870. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19871. ];
  19872. var faces = [
  19873. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19874. ];
  19875. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19876. };
  19877. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19878. /**
  19879. * @author timothypratley / https://github.com/timothypratley
  19880. */
  19881. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19882. var vertices = [
  19883. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19884. ];
  19885. var faces = [
  19886. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19887. ];
  19888. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19889. };
  19890. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19891. /**
  19892. * @author zz85 / https://github.com/zz85
  19893. * Parametric Surfaces Geometry
  19894. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19895. *
  19896. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  19897. *
  19898. */
  19899. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  19900. THREE.Geometry.call( this );
  19901. var verts = this.vertices;
  19902. var faces = this.faces;
  19903. var uvs = this.faceVertexUvs[ 0 ];
  19904. useTris = (useTris === undefined) ? false : useTris;
  19905. var i, il, j, p;
  19906. var u, v;
  19907. var stackCount = stacks + 1;
  19908. var sliceCount = slices + 1;
  19909. for ( i = 0; i <= stacks; i ++ ) {
  19910. v = i / stacks;
  19911. for ( j = 0; j <= slices; j ++ ) {
  19912. u = j / slices;
  19913. p = func( u, v );
  19914. verts.push( p );
  19915. }
  19916. }
  19917. var a, b, c, d;
  19918. var uva, uvb, uvc, uvd;
  19919. for ( i = 0; i < stacks; i ++ ) {
  19920. for ( j = 0; j < slices; j ++ ) {
  19921. a = i * sliceCount + j;
  19922. b = i * sliceCount + j + 1;
  19923. c = (i + 1) * sliceCount + j;
  19924. d = (i + 1) * sliceCount + j + 1;
  19925. uva = new THREE.Vector2( j / slices, i / stacks );
  19926. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  19927. uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  19928. uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19929. if ( useTris ) {
  19930. faces.push( new THREE.Face3( a, b, c ) );
  19931. faces.push( new THREE.Face3( b, d, c ) );
  19932. uvs.push( [ uva, uvb, uvc ] );
  19933. uvs.push( [ uvb, uvd, uvc ] );
  19934. } else {
  19935. faces.push( new THREE.Face4( a, b, d, c ) );
  19936. uvs.push( [ uva, uvb, uvd, uvc ] );
  19937. }
  19938. }
  19939. }
  19940. // console.log(this);
  19941. // magic bullet
  19942. // var diff = this.mergeVertices();
  19943. // console.log('removed ', diff, ' vertices by merging');
  19944. this.computeCentroids();
  19945. this.computeFaceNormals();
  19946. this.computeVertexNormals();
  19947. };
  19948. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19949. /**
  19950. * @author qiao / https://github.com/qiao
  19951. * @fileoverview This is a convex hull generator using the incremental method.
  19952. * The complexity is O(n^2) where n is the number of vertices.
  19953. * O(nlogn) algorithms do exist, but they are much more complicated.
  19954. *
  19955. * Benchmark:
  19956. *
  19957. * Platform: CPU: P7350 @2.00GHz Engine: V8
  19958. *
  19959. * Num Vertices Time(ms)
  19960. *
  19961. * 10 1
  19962. * 20 3
  19963. * 30 19
  19964. * 40 48
  19965. * 50 107
  19966. */
  19967. THREE.ConvexGeometry = function( vertices ) {
  19968. THREE.Geometry.call( this );
  19969. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  19970. for ( var i = 3; i < vertices.length; i++ ) {
  19971. addPoint( i );
  19972. }
  19973. function addPoint( vertexId ) {
  19974. var vertex = vertices[ vertexId ].clone();
  19975. var mag = vertex.length();
  19976. vertex.x += mag * randomOffset();
  19977. vertex.y += mag * randomOffset();
  19978. vertex.z += mag * randomOffset();
  19979. var hole = [];
  19980. for ( var f = 0; f < faces.length; ) {
  19981. var face = faces[ f ];
  19982. // for each face, if the vertex can see it,
  19983. // then we try to add the face's edges into the hole.
  19984. if ( visible( face, vertex ) ) {
  19985. for ( var e = 0; e < 3; e++ ) {
  19986. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  19987. var boundary = true;
  19988. // remove duplicated edges.
  19989. for ( var h = 0; h < hole.length; h++ ) {
  19990. if ( equalEdge( hole[ h ], edge ) ) {
  19991. hole[ h ] = hole[ hole.length - 1 ];
  19992. hole.pop();
  19993. boundary = false;
  19994. break;
  19995. }
  19996. }
  19997. if ( boundary ) {
  19998. hole.push( edge );
  19999. }
  20000. }
  20001. // remove faces[ f ]
  20002. faces[ f ] = faces[ faces.length - 1 ];
  20003. faces.pop();
  20004. } else { // not visible
  20005. f++;
  20006. }
  20007. }
  20008. // construct the new faces formed by the edges of the hole and the vertex
  20009. for ( var h = 0; h < hole.length; h++ ) {
  20010. faces.push( [
  20011. hole[ h ][ 0 ],
  20012. hole[ h ][ 1 ],
  20013. vertexId
  20014. ] );
  20015. }
  20016. }
  20017. /**
  20018. * Whether the face is visible from the vertex
  20019. */
  20020. function visible( face, vertex ) {
  20021. var va = vertices[ face[ 0 ] ];
  20022. var vb = vertices[ face[ 1 ] ];
  20023. var vc = vertices[ face[ 2 ] ];
  20024. var n = normal( va, vb, vc );
  20025. // distance from face to origin
  20026. var dist = n.dot( va );
  20027. return n.dot( vertex ) >= dist;
  20028. }
  20029. /**
  20030. * Face normal
  20031. */
  20032. function normal( va, vb, vc ) {
  20033. var cb = new THREE.Vector3();
  20034. var ab = new THREE.Vector3();
  20035. cb.subVectors( vc, vb );
  20036. ab.subVectors( va, vb );
  20037. cb.cross( ab );
  20038. cb.normalize();
  20039. return cb;
  20040. }
  20041. /**
  20042. * Detect whether two edges are equal.
  20043. * Note that when constructing the convex hull, two same edges can only
  20044. * be of the negative direction.
  20045. */
  20046. function equalEdge( ea, eb ) {
  20047. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  20048. }
  20049. /**
  20050. * Create a random offset between -1e-6 and 1e-6.
  20051. */
  20052. function randomOffset() {
  20053. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  20054. }
  20055. /**
  20056. * XXX: Not sure if this is the correct approach. Need someone to review.
  20057. */
  20058. function vertexUv( vertex ) {
  20059. var mag = vertex.length();
  20060. return new THREE.Vector2( vertex.x / mag, vertex.y / mag );
  20061. }
  20062. // Push vertices into `this.vertices`, skipping those inside the hull
  20063. var id = 0;
  20064. var newId = new Array( vertices.length ); // map from old vertex id to new id
  20065. for ( var i = 0; i < faces.length; i++ ) {
  20066. var face = faces[ i ];
  20067. for ( var j = 0; j < 3; j++ ) {
  20068. if ( newId[ face[ j ] ] === undefined ) {
  20069. newId[ face[ j ] ] = id++;
  20070. this.vertices.push( vertices[ face[ j ] ] );
  20071. }
  20072. face[ j ] = newId[ face[ j ] ];
  20073. }
  20074. }
  20075. // Convert faces into instances of THREE.Face3
  20076. for ( var i = 0; i < faces.length; i++ ) {
  20077. this.faces.push( new THREE.Face3(
  20078. faces[ i ][ 0 ],
  20079. faces[ i ][ 1 ],
  20080. faces[ i ][ 2 ]
  20081. ) );
  20082. }
  20083. // Compute UVs
  20084. for ( var i = 0; i < this.faces.length; i++ ) {
  20085. var face = this.faces[ i ];
  20086. this.faceVertexUvs[ 0 ].push( [
  20087. vertexUv( this.vertices[ face.a ] ),
  20088. vertexUv( this.vertices[ face.b ] ),
  20089. vertexUv( this.vertices[ face.c ])
  20090. ] );
  20091. }
  20092. this.computeCentroids();
  20093. this.computeFaceNormals();
  20094. this.computeVertexNormals();
  20095. };
  20096. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20097. /**
  20098. * @author sroucheray / http://sroucheray.org/
  20099. * @author mrdoob / http://mrdoob.com/
  20100. */
  20101. THREE.AxisHelper = function ( size ) {
  20102. var geometry = new THREE.Geometry();
  20103. geometry.vertices.push(
  20104. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  20105. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  20106. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  20107. );
  20108. geometry.colors.push(
  20109. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20110. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20111. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20112. );
  20113. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20114. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20115. };
  20116. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20117. /**
  20118. * @author WestLangley / http://github.com/WestLangley
  20119. * @author zz85 / https://github.com/zz85
  20120. * @author bhouston / https://exocortex.com
  20121. *
  20122. * Creates an arrow for visualizing directions
  20123. *
  20124. * Parameters:
  20125. * dir - Vector3
  20126. * origin - Vector3
  20127. * length - Number
  20128. * hex - color in hex value
  20129. */
  20130. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  20131. THREE.Object3D.call( this );
  20132. if ( length === undefined ) length = 20;
  20133. if ( hex === undefined ) hex = 0xffff00;
  20134. var lineGeometry = new THREE.Geometry();
  20135. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20136. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20137. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20138. this.add( this.line );
  20139. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  20140. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20141. this.cone.position.set( 0, 1, 0 );
  20142. this.add( this.cone );
  20143. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  20144. this.setDirection( dir );
  20145. this.setLength( length );
  20146. };
  20147. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20148. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  20149. var d = THREE.ArrowHelper.__v1.copy( dir ).normalize();
  20150. if ( d.y > 0.999 ) {
  20151. this.rotation.set( 0, 0, 0 );
  20152. } else if ( d.y < - 0.999 ) {
  20153. this.rotation.set( Math.PI, 0, 0 );
  20154. } else {
  20155. var axis = THREE.ArrowHelper.__v2.set( d.z, 0, - d.x ).normalize();
  20156. var radians = Math.acos( d.y );
  20157. var quaternion = THREE.ArrowHelper.__q1.setFromAxisAngle( axis, radians );
  20158. this.rotation.setEulerFromQuaternion( quaternion, this.eulerOrder );
  20159. }
  20160. };
  20161. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20162. this.scale.set( length, length, length );
  20163. };
  20164. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20165. this.line.material.color.setHex( hex );
  20166. this.cone.material.color.setHex( hex );
  20167. };
  20168. THREE.ArrowHelper.__v1 = new THREE.Vector3();
  20169. THREE.ArrowHelper.__v2 = new THREE.Vector3();
  20170. THREE.ArrowHelper.__q1 = new THREE.Quaternion();
  20171. /**
  20172. * @author alteredq / http://alteredqualia.com/
  20173. *
  20174. * - shows frustum, line of sight and up of the camera
  20175. * - suitable for fast updates
  20176. * - based on frustum visualization in lightgl.js shadowmap example
  20177. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20178. */
  20179. THREE.CameraHelper = function ( camera ) {
  20180. THREE.Line.call( this );
  20181. var scope = this;
  20182. this.geometry = new THREE.Geometry();
  20183. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20184. this.type = THREE.LinePieces;
  20185. this.matrixWorld = camera.matrixWorld;
  20186. this.matrixAutoUpdate = false;
  20187. this.pointMap = {};
  20188. // colors
  20189. var hexFrustum = 0xffaa00;
  20190. var hexCone = 0xff0000;
  20191. var hexUp = 0x00aaff;
  20192. var hexTarget = 0xffffff;
  20193. var hexCross = 0x333333;
  20194. // near
  20195. addLine( "n1", "n2", hexFrustum );
  20196. addLine( "n2", "n4", hexFrustum );
  20197. addLine( "n4", "n3", hexFrustum );
  20198. addLine( "n3", "n1", hexFrustum );
  20199. // far
  20200. addLine( "f1", "f2", hexFrustum );
  20201. addLine( "f2", "f4", hexFrustum );
  20202. addLine( "f4", "f3", hexFrustum );
  20203. addLine( "f3", "f1", hexFrustum );
  20204. // sides
  20205. addLine( "n1", "f1", hexFrustum );
  20206. addLine( "n2", "f2", hexFrustum );
  20207. addLine( "n3", "f3", hexFrustum );
  20208. addLine( "n4", "f4", hexFrustum );
  20209. // cone
  20210. addLine( "p", "n1", hexCone );
  20211. addLine( "p", "n2", hexCone );
  20212. addLine( "p", "n3", hexCone );
  20213. addLine( "p", "n4", hexCone );
  20214. // up
  20215. addLine( "u1", "u2", hexUp );
  20216. addLine( "u2", "u3", hexUp );
  20217. addLine( "u3", "u1", hexUp );
  20218. // target
  20219. addLine( "c", "t", hexTarget );
  20220. addLine( "p", "c", hexCross );
  20221. // cross
  20222. addLine( "cn1", "cn2", hexCross );
  20223. addLine( "cn3", "cn4", hexCross );
  20224. addLine( "cf1", "cf2", hexCross );
  20225. addLine( "cf3", "cf4", hexCross );
  20226. this.camera = camera;
  20227. function addLine( a, b, hex ) {
  20228. addPoint( a, hex );
  20229. addPoint( b, hex );
  20230. }
  20231. function addPoint( id, hex ) {
  20232. scope.geometry.vertices.push( new THREE.Vector3() );
  20233. scope.geometry.colors.push( new THREE.Color( hex ) );
  20234. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  20235. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  20236. }
  20237. this.update( camera );
  20238. };
  20239. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20240. THREE.CameraHelper.prototype.update = function () {
  20241. var scope = this;
  20242. var w = 1, h = 1;
  20243. // we need just camera projection matrix
  20244. // world matrix must be identity
  20245. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  20246. // center / target
  20247. setPoint( "c", 0, 0, -1 );
  20248. setPoint( "t", 0, 0, 1 );
  20249. // near
  20250. setPoint( "n1", -w, -h, -1 );
  20251. setPoint( "n2", w, -h, -1 );
  20252. setPoint( "n3", -w, h, -1 );
  20253. setPoint( "n4", w, h, -1 );
  20254. // far
  20255. setPoint( "f1", -w, -h, 1 );
  20256. setPoint( "f2", w, -h, 1 );
  20257. setPoint( "f3", -w, h, 1 );
  20258. setPoint( "f4", w, h, 1 );
  20259. // up
  20260. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20261. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20262. setPoint( "u3", 0, h * 2, -1 );
  20263. // cross
  20264. setPoint( "cf1", -w, 0, 1 );
  20265. setPoint( "cf2", w, 0, 1 );
  20266. setPoint( "cf3", 0, -h, 1 );
  20267. setPoint( "cf4", 0, h, 1 );
  20268. setPoint( "cn1", -w, 0, -1 );
  20269. setPoint( "cn2", w, 0, -1 );
  20270. setPoint( "cn3", 0, -h, -1 );
  20271. setPoint( "cn4", 0, h, -1 );
  20272. function setPoint( point, x, y, z ) {
  20273. THREE.CameraHelper.__v.set( x, y, z );
  20274. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  20275. var points = scope.pointMap[ point ];
  20276. if ( points !== undefined ) {
  20277. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20278. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  20279. }
  20280. }
  20281. }
  20282. this.geometry.verticesNeedUpdate = true;
  20283. };
  20284. THREE.CameraHelper.__projector = new THREE.Projector();
  20285. THREE.CameraHelper.__v = new THREE.Vector3();
  20286. THREE.CameraHelper.__c = new THREE.Camera();
  20287. /**
  20288. * @author alteredq / http://alteredqualia.com/
  20289. *
  20290. * - shows directional light color, intensity, position, orientation and target
  20291. */
  20292. THREE.DirectionalLightHelper = function ( light, sphereSize ) {
  20293. THREE.Object3D.call( this );
  20294. this.light = light;
  20295. // position
  20296. this.position = light.position;
  20297. // direction
  20298. this.direction = new THREE.Vector3();
  20299. this.direction.subVectors( light.target.position, light.position );
  20300. // color
  20301. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20302. this.color = light.color.clone();
  20303. this.color.multiplyScalar( intensity );
  20304. var hexColor = this.color.getHex();
  20305. // light helper
  20306. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20307. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20308. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20309. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20310. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20311. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20312. this.add( this.lightSphere );
  20313. this.add( this.lightRays );
  20314. this.lightSphere.userData.isGizmo = true;
  20315. this.lightSphere.userData.gizmoSubject = light;
  20316. this.lightSphere.userData.gizmoRoot = this;
  20317. // light target helper
  20318. this.targetSphere = null;
  20319. if ( light.target.userData.targetInverse !== undefined ) {
  20320. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20321. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20322. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20323. this.targetSphere.position = light.target.position;
  20324. this.targetSphere.userData.isGizmo = true;
  20325. this.targetSphere.userData.gizmoSubject = light.target;
  20326. this.targetSphere.userData.gizmoRoot = this.targetSphere;
  20327. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20328. var lineGeometry = new THREE.Geometry();
  20329. lineGeometry.vertices.push( this.position.clone() );
  20330. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20331. lineGeometry.computeLineDistances();
  20332. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20333. this.targetLine.userData.isGizmo = true;
  20334. }
  20335. //
  20336. this.userData.isGizmo = true;
  20337. }
  20338. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20339. THREE.DirectionalLightHelper.prototype.update = function () {
  20340. // update arrow orientation
  20341. // pointing from light to target
  20342. this.direction.subVectors( this.light.target.position, this.light.position );
  20343. // update arrow, spheres, rays and line colors to light color * light intensity
  20344. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20345. this.color.copy( this.light.color );
  20346. this.color.multiplyScalar( intensity );
  20347. this.lightSphere.material.color.copy( this.color );
  20348. this.lightRays.material.color.copy( this.color );
  20349. // Only update targetSphere and targetLine if available
  20350. if ( this.targetSphere !== null ) {
  20351. this.targetSphere.material.color.copy( this.color );
  20352. this.targetLine.material.color.copy( this.color );
  20353. // update target line vertices
  20354. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20355. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20356. this.targetLine.geometry.computeLineDistances();
  20357. this.targetLine.geometry.verticesNeedUpdate = true;
  20358. }
  20359. }
  20360. /**
  20361. * @author alteredq / http://alteredqualia.com/
  20362. *
  20363. * - shows hemisphere light intensity, sky and ground colors and directions
  20364. */
  20365. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20366. THREE.Object3D.call( this );
  20367. this.light = light;
  20368. // position
  20369. this.position = light.position;
  20370. //
  20371. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20372. // sky color
  20373. this.color = light.color.clone();
  20374. this.color.multiplyScalar( intensity );
  20375. var hexColor = this.color.getHex();
  20376. // ground color
  20377. this.groundColor = light.groundColor.clone();
  20378. this.groundColor.multiplyScalar( intensity );
  20379. var hexColorGround = this.groundColor.getHex();
  20380. // double colored light bulb
  20381. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, 0, Math.PI * 0.5 );
  20382. var bulbGroundGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, Math.PI * 0.5, Math.PI );
  20383. var bulbSkyMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20384. var bulbGroundMaterial = new THREE.MeshBasicMaterial( { color: hexColorGround, fog: false } );
  20385. for ( var i = 0, il = bulbGeometry.faces.length; i < il; i ++ ) {
  20386. bulbGeometry.faces[ i ].materialIndex = 0;
  20387. }
  20388. for ( var i = 0, il = bulbGroundGeometry.faces.length; i < il; i ++ ) {
  20389. bulbGroundGeometry.faces[ i ].materialIndex = 1;
  20390. }
  20391. THREE.GeometryUtils.merge( bulbGeometry, bulbGroundGeometry );
  20392. this.lightSphere = new THREE.Mesh( bulbGeometry, new THREE.MeshFaceMaterial( [ bulbSkyMaterial, bulbGroundMaterial ] ) );
  20393. // arrows for sky and ground light directions
  20394. this.lightArrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * 1.1, 0 ), arrowLength, hexColor );
  20395. this.lightArrow.rotation.x = Math.PI;
  20396. this.lightArrowGround = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * -1.1, 0 ), arrowLength, hexColorGround );
  20397. var joint = new THREE.Object3D();
  20398. joint.rotation.x = -Math.PI * 0.5;
  20399. joint.add( this.lightSphere );
  20400. joint.add( this.lightArrow );
  20401. joint.add( this.lightArrowGround );
  20402. this.add( joint );
  20403. //
  20404. this.lightSphere.userData.isGizmo = true;
  20405. this.lightSphere.userData.gizmoSubject = light;
  20406. this.lightSphere.userData.gizmoRoot = this;
  20407. //
  20408. this.userData.isGizmo = true;
  20409. //
  20410. this.target = new THREE.Vector3();
  20411. this.lookAt( this.target );
  20412. }
  20413. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20414. THREE.HemisphereLightHelper.prototype.update = function () {
  20415. // update sphere sky and ground colors to light color * light intensity
  20416. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20417. this.color.copy( this.light.color );
  20418. this.color.multiplyScalar( intensity );
  20419. this.groundColor.copy( this.light.groundColor );
  20420. this.groundColor.multiplyScalar( intensity );
  20421. this.lightSphere.material.materials[ 0 ].color.copy( this.color );
  20422. this.lightSphere.material.materials[ 1 ].color.copy( this.groundColor );
  20423. this.lightArrow.setColor( this.color.getHex() );
  20424. this.lightArrowGround.setColor( this.groundColor.getHex() );
  20425. this.lookAt( this.target );
  20426. }
  20427. /**
  20428. * @author alteredq / http://alteredqualia.com/
  20429. *
  20430. * - shows point light color, intensity, position and distance
  20431. */
  20432. THREE.PointLightHelper = function ( light, sphereSize ) {
  20433. THREE.Object3D.call( this );
  20434. this.light = light;
  20435. // position
  20436. this.position = light.position;
  20437. // color
  20438. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20439. this.color = light.color.clone();
  20440. this.color.multiplyScalar( intensity );
  20441. var hexColor = this.color.getHex();
  20442. // light helper
  20443. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20444. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20445. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20446. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20447. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20448. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20449. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20450. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20451. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20452. var d = light.distance;
  20453. if ( d === 0.0 ) {
  20454. this.lightDistance.visible = false;
  20455. } else {
  20456. this.lightDistance.scale.set( d, d, d );
  20457. }
  20458. this.add( this.lightSphere );
  20459. this.add( this.lightRays );
  20460. this.add( this.lightDistance );
  20461. //
  20462. this.lightSphere.userData.isGizmo = true;
  20463. this.lightSphere.userData.gizmoSubject = light;
  20464. this.lightSphere.userData.gizmoRoot = this;
  20465. //
  20466. this.userData.isGizmo = true;
  20467. }
  20468. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20469. THREE.PointLightHelper.prototype.update = function () {
  20470. // update sphere and rays colors to light color * light intensity
  20471. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20472. this.color.copy( this.light.color );
  20473. this.color.multiplyScalar( intensity );
  20474. this.lightSphere.material.color.copy( this.color );
  20475. this.lightRays.material.color.copy( this.color );
  20476. this.lightDistance.material.color.copy( this.color );
  20477. //
  20478. var d = this.light.distance;
  20479. if ( d === 0.0 ) {
  20480. this.lightDistance.visible = false;
  20481. } else {
  20482. this.lightDistance.visible = true;
  20483. this.lightDistance.scale.set( d, d, d );
  20484. }
  20485. }
  20486. /**
  20487. * @author alteredq / http://alteredqualia.com/
  20488. *
  20489. * - shows spot light color, intensity, position, orientation, light cone and target
  20490. */
  20491. THREE.SpotLightHelper = function ( light, sphereSize ) {
  20492. THREE.Object3D.call( this );
  20493. this.light = light;
  20494. // position
  20495. this.position = light.position;
  20496. // direction
  20497. this.direction = new THREE.Vector3();
  20498. this.direction.subVectors( light.target.position, light.position );
  20499. // color
  20500. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20501. this.color = light.color.clone();
  20502. this.color.multiplyScalar( intensity );
  20503. var hexColor = this.color.getHex();
  20504. // light helper
  20505. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20506. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20507. var coneGeometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  20508. var coneMatrix = new THREE.Matrix4();
  20509. coneMatrix.rotateX( -Math.PI/2 );
  20510. coneMatrix.translate( new THREE.Vector3( 0, -0.5, 0 ) );
  20511. coneGeometry.applyMatrix( coneMatrix );
  20512. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20513. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20514. var coneMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  20515. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20516. this.lightCone = new THREE.Mesh( coneGeometry, coneMaterial );
  20517. var coneLength = light.distance ? light.distance : 10000;
  20518. var coneWidth = coneLength * Math.tan( light.angle * 0.5 ) * 2;
  20519. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20520. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20521. this.gyroscope = new THREE.Gyroscope();
  20522. this.gyroscope.add( this.lightSphere );
  20523. this.gyroscope.add( this.lightRays );
  20524. this.add( this.gyroscope );
  20525. this.add( this.lightCone );
  20526. this.lookAt( light.target.position );
  20527. this.lightSphere.userData.isGizmo = true;
  20528. this.lightSphere.userData.gizmoSubject = light;
  20529. this.lightSphere.userData.gizmoRoot = this;
  20530. // light target helper
  20531. this.targetSphere = null;
  20532. if ( light.target.userData.targetInverse !== undefined ) {
  20533. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20534. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20535. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20536. this.targetSphere.position = light.target.position;
  20537. this.targetSphere.userData.isGizmo = true;
  20538. this.targetSphere.userData.gizmoSubject = light.target;
  20539. this.targetSphere.userData.gizmoRoot = this.targetSphere;
  20540. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20541. var lineGeometry = new THREE.Geometry();
  20542. lineGeometry.vertices.push( this.position.clone() );
  20543. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20544. lineGeometry.computeLineDistances();
  20545. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20546. this.targetLine.userData.isGizmo = true;
  20547. }
  20548. //
  20549. this.userData.isGizmo = true;
  20550. }
  20551. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20552. THREE.SpotLightHelper.prototype.update = function () {
  20553. // update arrow orientation
  20554. // pointing from light to target
  20555. this.direction.subVectors( this.light.target.position, this.light.position );
  20556. // update light cone orientation and size
  20557. this.lookAt( this.light.target.position );
  20558. var coneLength = this.light.distance ? this.light.distance : 10000;
  20559. var coneWidth = coneLength * Math.tan( this.light.angle * 0.5 ) * 2;
  20560. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20561. // update arrow, spheres, rays and line colors to light color * light intensity
  20562. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20563. this.color.copy( this.light.color );
  20564. this.color.multiplyScalar( intensity );
  20565. this.lightSphere.material.color.copy( this.color );
  20566. this.lightRays.material.color.copy( this.color );
  20567. this.lightCone.material.color.copy( this.color );
  20568. // Only update targetSphere and targetLine if available
  20569. if ( this.targetSphere !== null ) {
  20570. this.targetSphere.material.color.copy( this.color );
  20571. this.targetLine.material.color.copy( this.color );
  20572. // update target line vertices
  20573. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20574. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20575. this.targetLine.geometry.computeLineDistances();
  20576. this.targetLine.geometry.verticesNeedUpdate = true;
  20577. }
  20578. };
  20579. /**
  20580. * @author alteredq / http://alteredqualia.com/
  20581. */
  20582. THREE.ImmediateRenderObject = function () {
  20583. THREE.Object3D.call( this );
  20584. this.render = function ( renderCallback ) { };
  20585. };
  20586. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20587. /**
  20588. * @author mikael emtinger / http://gomo.se/
  20589. * @author alteredq / http://alteredqualia.com/
  20590. */
  20591. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20592. THREE.Object3D.call( this );
  20593. this.lensFlares = [];
  20594. this.positionScreen = new THREE.Vector3();
  20595. this.customUpdateCallback = undefined;
  20596. if( texture !== undefined ) {
  20597. this.add( texture, size, distance, blending, color );
  20598. }
  20599. };
  20600. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20601. /*
  20602. * Add: adds another flare
  20603. */
  20604. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20605. if( size === undefined ) size = -1;
  20606. if( distance === undefined ) distance = 0;
  20607. if( opacity === undefined ) opacity = 1;
  20608. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20609. if( blending === undefined ) blending = THREE.NormalBlending;
  20610. distance = Math.min( distance, Math.max( 0, distance ) );
  20611. this.lensFlares.push( { texture: texture, // THREE.Texture
  20612. size: size, // size in pixels (-1 = use texture.width)
  20613. distance: distance, // distance (0-1) from light source (0=at light source)
  20614. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20615. scale: 1, // scale
  20616. rotation: 1, // rotation
  20617. opacity: opacity, // opacity
  20618. color: color, // color
  20619. blending: blending } ); // blending
  20620. };
  20621. /*
  20622. * Update lens flares update positions on all flares based on the screen position
  20623. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20624. */
  20625. THREE.LensFlare.prototype.updateLensFlares = function () {
  20626. var f, fl = this.lensFlares.length;
  20627. var flare;
  20628. var vecX = -this.positionScreen.x * 2;
  20629. var vecY = -this.positionScreen.y * 2;
  20630. for( f = 0; f < fl; f ++ ) {
  20631. flare = this.lensFlares[ f ];
  20632. flare.x = this.positionScreen.x + vecX * flare.distance;
  20633. flare.y = this.positionScreen.y + vecY * flare.distance;
  20634. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20635. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20636. }
  20637. };
  20638. /**
  20639. * @author alteredq / http://alteredqualia.com/
  20640. */
  20641. THREE.MorphBlendMesh = function( geometry, material ) {
  20642. THREE.Mesh.call( this, geometry, material );
  20643. this.animationsMap = {};
  20644. this.animationsList = [];
  20645. // prepare default animation
  20646. // (all frames played together in 1 second)
  20647. var numFrames = this.geometry.morphTargets.length;
  20648. var name = "__default";
  20649. var startFrame = 0;
  20650. var endFrame = numFrames - 1;
  20651. var fps = numFrames / 1;
  20652. this.createAnimation( name, startFrame, endFrame, fps );
  20653. this.setAnimationWeight( name, 1 );
  20654. };
  20655. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20656. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20657. var animation = {
  20658. startFrame: start,
  20659. endFrame: end,
  20660. length: end - start + 1,
  20661. fps: fps,
  20662. duration: ( end - start ) / fps,
  20663. lastFrame: 0,
  20664. currentFrame: 0,
  20665. active: false,
  20666. time: 0,
  20667. direction: 1,
  20668. weight: 1,
  20669. directionBackwards: false,
  20670. mirroredLoop: false
  20671. };
  20672. this.animationsMap[ name ] = animation;
  20673. this.animationsList.push( animation );
  20674. };
  20675. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20676. var pattern = /([a-z]+)(\d+)/;
  20677. var firstAnimation, frameRanges = {};
  20678. var geometry = this.geometry;
  20679. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20680. var morph = geometry.morphTargets[ i ];
  20681. var chunks = morph.name.match( pattern );
  20682. if ( chunks && chunks.length > 1 ) {
  20683. var name = chunks[ 1 ];
  20684. var num = chunks[ 2 ];
  20685. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20686. var range = frameRanges[ name ];
  20687. if ( i < range.start ) range.start = i;
  20688. if ( i > range.end ) range.end = i;
  20689. if ( ! firstAnimation ) firstAnimation = name;
  20690. }
  20691. }
  20692. for ( var name in frameRanges ) {
  20693. var range = frameRanges[ name ];
  20694. this.createAnimation( name, range.start, range.end, fps );
  20695. }
  20696. this.firstAnimation = firstAnimation;
  20697. };
  20698. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20699. var animation = this.animationsMap[ name ];
  20700. if ( animation ) {
  20701. animation.direction = 1;
  20702. animation.directionBackwards = false;
  20703. }
  20704. };
  20705. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20706. var animation = this.animationsMap[ name ];
  20707. if ( animation ) {
  20708. animation.direction = -1;
  20709. animation.directionBackwards = true;
  20710. }
  20711. };
  20712. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20713. var animation = this.animationsMap[ name ];
  20714. if ( animation ) {
  20715. animation.fps = fps;
  20716. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20717. }
  20718. };
  20719. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20720. var animation = this.animationsMap[ name ];
  20721. if ( animation ) {
  20722. animation.duration = duration;
  20723. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20724. }
  20725. };
  20726. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20727. var animation = this.animationsMap[ name ];
  20728. if ( animation ) {
  20729. animation.weight = weight;
  20730. }
  20731. };
  20732. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20733. var animation = this.animationsMap[ name ];
  20734. if ( animation ) {
  20735. animation.time = time;
  20736. }
  20737. };
  20738. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20739. var time = 0;
  20740. var animation = this.animationsMap[ name ];
  20741. if ( animation ) {
  20742. time = animation.time;
  20743. }
  20744. return time;
  20745. };
  20746. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20747. var duration = -1;
  20748. var animation = this.animationsMap[ name ];
  20749. if ( animation ) {
  20750. duration = animation.duration;
  20751. }
  20752. return duration;
  20753. };
  20754. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20755. var animation = this.animationsMap[ name ];
  20756. if ( animation ) {
  20757. animation.time = 0;
  20758. animation.active = true;
  20759. } else {
  20760. console.warn( "animation[" + name + "] undefined" );
  20761. }
  20762. };
  20763. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20764. var animation = this.animationsMap[ name ];
  20765. if ( animation ) {
  20766. animation.active = false;
  20767. }
  20768. };
  20769. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20770. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20771. var animation = this.animationsList[ i ];
  20772. if ( ! animation.active ) continue;
  20773. var frameTime = animation.duration / animation.length;
  20774. animation.time += animation.direction * delta;
  20775. if ( animation.mirroredLoop ) {
  20776. if ( animation.time > animation.duration || animation.time < 0 ) {
  20777. animation.direction *= -1;
  20778. if ( animation.time > animation.duration ) {
  20779. animation.time = animation.duration;
  20780. animation.directionBackwards = true;
  20781. }
  20782. if ( animation.time < 0 ) {
  20783. animation.time = 0;
  20784. animation.directionBackwards = false;
  20785. }
  20786. }
  20787. } else {
  20788. animation.time = animation.time % animation.duration;
  20789. if ( animation.time < 0 ) animation.time += animation.duration;
  20790. }
  20791. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20792. var weight = animation.weight;
  20793. if ( keyframe !== animation.currentFrame ) {
  20794. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20795. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20796. this.morphTargetInfluences[ keyframe ] = 0;
  20797. animation.lastFrame = animation.currentFrame;
  20798. animation.currentFrame = keyframe;
  20799. }
  20800. var mix = ( animation.time % frameTime ) / frameTime;
  20801. if ( animation.directionBackwards ) mix = 1 - mix;
  20802. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20803. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20804. }
  20805. };
  20806. /**
  20807. * @author mikael emtinger / http://gomo.se/
  20808. * @author alteredq / http://alteredqualia.com/
  20809. */
  20810. THREE.LensFlarePlugin = function () {
  20811. var _gl, _renderer, _precision, _lensFlare = {};
  20812. this.init = function ( renderer ) {
  20813. _gl = renderer.context;
  20814. _renderer = renderer;
  20815. _precision = renderer.getPrecision();
  20816. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20817. _lensFlare.faces = new Uint16Array( 6 );
  20818. var i = 0;
  20819. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20820. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20821. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20822. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20823. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20824. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20825. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20826. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20827. i = 0;
  20828. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20829. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20830. // buffers
  20831. _lensFlare.vertexBuffer = _gl.createBuffer();
  20832. _lensFlare.elementBuffer = _gl.createBuffer();
  20833. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20834. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20835. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20836. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20837. // textures
  20838. _lensFlare.tempTexture = _gl.createTexture();
  20839. _lensFlare.occlusionTexture = _gl.createTexture();
  20840. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20841. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20842. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20843. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20844. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20845. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20846. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20847. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20848. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20849. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20850. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20851. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20852. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20853. _lensFlare.hasVertexTexture = false;
  20854. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  20855. } else {
  20856. _lensFlare.hasVertexTexture = true;
  20857. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  20858. }
  20859. _lensFlare.attributes = {};
  20860. _lensFlare.uniforms = {};
  20861. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20862. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20863. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20864. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20865. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20866. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20867. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20868. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20869. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20870. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20871. };
  20872. /*
  20873. * Render lens flares
  20874. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20875. * reads these back and calculates occlusion.
  20876. * Then _lensFlare.update_lensFlares() is called to re-position and
  20877. * update transparency of flares. Then they are rendered.
  20878. *
  20879. */
  20880. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20881. var flares = scene.__webglFlares,
  20882. nFlares = flares.length;
  20883. if ( ! nFlares ) return;
  20884. var tempPosition = new THREE.Vector3();
  20885. var invAspect = viewportHeight / viewportWidth,
  20886. halfViewportWidth = viewportWidth * 0.5,
  20887. halfViewportHeight = viewportHeight * 0.5;
  20888. var size = 16 / viewportHeight,
  20889. scale = new THREE.Vector2( size * invAspect, size );
  20890. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20891. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20892. var uniforms = _lensFlare.uniforms,
  20893. attributes = _lensFlare.attributes;
  20894. // set _lensFlare program and reset blending
  20895. _gl.useProgram( _lensFlare.program );
  20896. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20897. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20898. // loop through all lens flares to update their occlusion and positions
  20899. // setup gl and common used attribs/unforms
  20900. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20901. _gl.uniform1i( uniforms.map, 1 );
  20902. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20903. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20904. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20905. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20906. _gl.disable( _gl.CULL_FACE );
  20907. _gl.depthMask( false );
  20908. var i, j, jl, flare, sprite;
  20909. for ( i = 0; i < nFlares; i ++ ) {
  20910. size = 16 / viewportHeight;
  20911. scale.set( size * invAspect, size );
  20912. // calc object screen position
  20913. flare = flares[ i ];
  20914. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20915. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  20916. tempPosition.applyProjection( camera.projectionMatrix );
  20917. // setup arrays for gl programs
  20918. screenPosition.copy( tempPosition )
  20919. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20920. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20921. // screen cull
  20922. if ( _lensFlare.hasVertexTexture || (
  20923. screenPositionPixels.x > 0 &&
  20924. screenPositionPixels.x < viewportWidth &&
  20925. screenPositionPixels.y > 0 &&
  20926. screenPositionPixels.y < viewportHeight ) ) {
  20927. // save current RGB to temp texture
  20928. _gl.activeTexture( _gl.TEXTURE1 );
  20929. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20930. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20931. // render pink quad
  20932. _gl.uniform1i( uniforms.renderType, 0 );
  20933. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20934. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20935. _gl.disable( _gl.BLEND );
  20936. _gl.enable( _gl.DEPTH_TEST );
  20937. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20938. // copy result to occlusionMap
  20939. _gl.activeTexture( _gl.TEXTURE0 );
  20940. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20941. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20942. // restore graphics
  20943. _gl.uniform1i( uniforms.renderType, 1 );
  20944. _gl.disable( _gl.DEPTH_TEST );
  20945. _gl.activeTexture( _gl.TEXTURE1 );
  20946. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20947. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20948. // update object positions
  20949. flare.positionScreen.copy( screenPosition )
  20950. if ( flare.customUpdateCallback ) {
  20951. flare.customUpdateCallback( flare );
  20952. } else {
  20953. flare.updateLensFlares();
  20954. }
  20955. // render flares
  20956. _gl.uniform1i( uniforms.renderType, 2 );
  20957. _gl.enable( _gl.BLEND );
  20958. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  20959. sprite = flare.lensFlares[ j ];
  20960. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  20961. screenPosition.x = sprite.x;
  20962. screenPosition.y = sprite.y;
  20963. screenPosition.z = sprite.z;
  20964. size = sprite.size * sprite.scale / viewportHeight;
  20965. scale.x = size * invAspect;
  20966. scale.y = size;
  20967. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20968. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20969. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20970. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20971. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20972. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20973. _renderer.setTexture( sprite.texture, 1 );
  20974. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20975. }
  20976. }
  20977. }
  20978. }
  20979. // restore gl
  20980. _gl.enable( _gl.CULL_FACE );
  20981. _gl.enable( _gl.DEPTH_TEST );
  20982. _gl.depthMask( true );
  20983. };
  20984. function createProgram ( shader, precision ) {
  20985. var program = _gl.createProgram();
  20986. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20987. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20988. var prefix = "precision " + precision + " float;\n";
  20989. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  20990. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  20991. _gl.compileShader( fragmentShader );
  20992. _gl.compileShader( vertexShader );
  20993. _gl.attachShader( program, fragmentShader );
  20994. _gl.attachShader( program, vertexShader );
  20995. _gl.linkProgram( program );
  20996. return program;
  20997. };
  20998. };
  20999. /**
  21000. * @author alteredq / http://alteredqualia.com/
  21001. */
  21002. THREE.ShadowMapPlugin = function () {
  21003. var _gl,
  21004. _renderer,
  21005. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21006. _frustum = new THREE.Frustum(),
  21007. _projScreenMatrix = new THREE.Matrix4(),
  21008. _min = new THREE.Vector3(),
  21009. _max = new THREE.Vector3(),
  21010. _matrixPosition = new THREE.Vector3();
  21011. this.init = function ( renderer ) {
  21012. _gl = renderer.context;
  21013. _renderer = renderer;
  21014. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21015. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21016. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21017. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21018. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21019. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21020. _depthMaterial._shadowPass = true;
  21021. _depthMaterialMorph._shadowPass = true;
  21022. _depthMaterialSkin._shadowPass = true;
  21023. _depthMaterialMorphSkin._shadowPass = true;
  21024. };
  21025. this.render = function ( scene, camera ) {
  21026. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21027. this.update( scene, camera );
  21028. };
  21029. this.update = function ( scene, camera ) {
  21030. var i, il, j, jl, n,
  21031. shadowMap, shadowMatrix, shadowCamera,
  21032. program, buffer, material,
  21033. webglObject, object, light,
  21034. renderList,
  21035. lights = [],
  21036. k = 0,
  21037. fog = null;
  21038. // set GL state for depth map
  21039. _gl.clearColor( 1, 1, 1, 1 );
  21040. _gl.disable( _gl.BLEND );
  21041. _gl.enable( _gl.CULL_FACE );
  21042. _gl.frontFace( _gl.CCW );
  21043. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21044. _gl.cullFace( _gl.FRONT );
  21045. } else {
  21046. _gl.cullFace( _gl.BACK );
  21047. }
  21048. _renderer.setDepthTest( true );
  21049. // preprocess lights
  21050. // - skip lights that are not casting shadows
  21051. // - create virtual lights for cascaded shadow maps
  21052. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21053. light = scene.__lights[ i ];
  21054. if ( ! light.castShadow ) continue;
  21055. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21056. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21057. var virtualLight;
  21058. if ( ! light.shadowCascadeArray[ n ] ) {
  21059. virtualLight = createVirtualLight( light, n );
  21060. virtualLight.originalCamera = camera;
  21061. var gyro = new THREE.Gyroscope();
  21062. gyro.position = light.shadowCascadeOffset;
  21063. gyro.add( virtualLight );
  21064. gyro.add( virtualLight.target );
  21065. camera.add( gyro );
  21066. light.shadowCascadeArray[ n ] = virtualLight;
  21067. console.log( "Created virtualLight", virtualLight );
  21068. } else {
  21069. virtualLight = light.shadowCascadeArray[ n ];
  21070. }
  21071. updateVirtualLight( light, n );
  21072. lights[ k ] = virtualLight;
  21073. k ++;
  21074. }
  21075. } else {
  21076. lights[ k ] = light;
  21077. k ++;
  21078. }
  21079. }
  21080. // render depth map
  21081. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21082. light = lights[ i ];
  21083. if ( ! light.shadowMap ) {
  21084. var shadowFilter = THREE.LinearFilter;
  21085. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21086. shadowFilter = THREE.NearestFilter;
  21087. }
  21088. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21089. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21090. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21091. light.shadowMatrix = new THREE.Matrix4();
  21092. }
  21093. if ( ! light.shadowCamera ) {
  21094. if ( light instanceof THREE.SpotLight ) {
  21095. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21096. } else if ( light instanceof THREE.DirectionalLight ) {
  21097. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21098. } else {
  21099. console.error( "Unsupported light type for shadow" );
  21100. continue;
  21101. }
  21102. scene.add( light.shadowCamera );
  21103. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21104. }
  21105. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21106. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21107. light.shadowCamera.add( light.cameraHelper );
  21108. }
  21109. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21110. updateShadowCamera( camera, light );
  21111. }
  21112. shadowMap = light.shadowMap;
  21113. shadowMatrix = light.shadowMatrix;
  21114. shadowCamera = light.shadowCamera;
  21115. shadowCamera.position.getPositionFromMatrix( light.matrixWorld );
  21116. _matrixPosition.getPositionFromMatrix( light.target.matrixWorld );
  21117. shadowCamera.lookAt( _matrixPosition );
  21118. shadowCamera.updateMatrixWorld();
  21119. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21120. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21121. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21122. // compute shadow matrix
  21123. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21124. 0.0, 0.5, 0.0, 0.5,
  21125. 0.0, 0.0, 0.5, 0.5,
  21126. 0.0, 0.0, 0.0, 1.0 );
  21127. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21128. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21129. // update camera matrices and frustum
  21130. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21131. _frustum.setFromMatrix( _projScreenMatrix );
  21132. // render shadow map
  21133. _renderer.setRenderTarget( shadowMap );
  21134. _renderer.clear();
  21135. // set object matrices & frustum culling
  21136. renderList = scene.__webglObjects;
  21137. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21138. webglObject = renderList[ j ];
  21139. object = webglObject.object;
  21140. webglObject.render = false;
  21141. if ( object.visible && object.castShadow ) {
  21142. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21143. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21144. webglObject.render = true;
  21145. }
  21146. }
  21147. }
  21148. // render regular objects
  21149. var objectMaterial, useMorphing, useSkinning;
  21150. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21151. webglObject = renderList[ j ];
  21152. if ( webglObject.render ) {
  21153. object = webglObject.object;
  21154. buffer = webglObject.buffer;
  21155. // culling is overriden globally for all objects
  21156. // while rendering depth map
  21157. // need to deal with MeshFaceMaterial somehow
  21158. // in that case just use the first of material.materials for now
  21159. // (proper solution would require to break objects by materials
  21160. // similarly to regular rendering and then set corresponding
  21161. // depth materials per each chunk instead of just once per object)
  21162. objectMaterial = getObjectMaterial( object );
  21163. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21164. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21165. if ( object.customDepthMaterial ) {
  21166. material = object.customDepthMaterial;
  21167. } else if ( useSkinning ) {
  21168. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21169. } else if ( useMorphing ) {
  21170. material = _depthMaterialMorph;
  21171. } else {
  21172. material = _depthMaterial;
  21173. }
  21174. if ( buffer instanceof THREE.BufferGeometry ) {
  21175. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21176. } else {
  21177. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21178. }
  21179. }
  21180. }
  21181. // set matrices and render immediate objects
  21182. renderList = scene.__webglObjectsImmediate;
  21183. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21184. webglObject = renderList[ j ];
  21185. object = webglObject.object;
  21186. if ( object.visible && object.castShadow ) {
  21187. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21188. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21189. }
  21190. }
  21191. }
  21192. // restore GL state
  21193. var clearColor = _renderer.getClearColor(),
  21194. clearAlpha = _renderer.getClearAlpha();
  21195. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21196. _gl.enable( _gl.BLEND );
  21197. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21198. _gl.cullFace( _gl.BACK );
  21199. }
  21200. };
  21201. function createVirtualLight( light, cascade ) {
  21202. var virtualLight = new THREE.DirectionalLight();
  21203. virtualLight.isVirtual = true;
  21204. virtualLight.onlyShadow = true;
  21205. virtualLight.castShadow = true;
  21206. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21207. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21208. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21209. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21210. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21211. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21212. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21213. virtualLight.shadowDarkness = light.shadowDarkness;
  21214. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21215. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21216. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21217. virtualLight.pointsWorld = [];
  21218. virtualLight.pointsFrustum = [];
  21219. var pointsWorld = virtualLight.pointsWorld,
  21220. pointsFrustum = virtualLight.pointsFrustum;
  21221. for ( var i = 0; i < 8; i ++ ) {
  21222. pointsWorld[ i ] = new THREE.Vector3();
  21223. pointsFrustum[ i ] = new THREE.Vector3();
  21224. }
  21225. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21226. var farZ = light.shadowCascadeFarZ[ cascade ];
  21227. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21228. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21229. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21230. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21231. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21232. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21233. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21234. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21235. return virtualLight;
  21236. }
  21237. // Synchronize virtual light with the original light
  21238. function updateVirtualLight( light, cascade ) {
  21239. var virtualLight = light.shadowCascadeArray[ cascade ];
  21240. virtualLight.position.copy( light.position );
  21241. virtualLight.target.position.copy( light.target.position );
  21242. virtualLight.lookAt( virtualLight.target );
  21243. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21244. virtualLight.shadowDarkness = light.shadowDarkness;
  21245. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21246. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21247. var farZ = light.shadowCascadeFarZ[ cascade ];
  21248. var pointsFrustum = virtualLight.pointsFrustum;
  21249. pointsFrustum[ 0 ].z = nearZ;
  21250. pointsFrustum[ 1 ].z = nearZ;
  21251. pointsFrustum[ 2 ].z = nearZ;
  21252. pointsFrustum[ 3 ].z = nearZ;
  21253. pointsFrustum[ 4 ].z = farZ;
  21254. pointsFrustum[ 5 ].z = farZ;
  21255. pointsFrustum[ 6 ].z = farZ;
  21256. pointsFrustum[ 7 ].z = farZ;
  21257. }
  21258. // Fit shadow camera's ortho frustum to camera frustum
  21259. function updateShadowCamera( camera, light ) {
  21260. var shadowCamera = light.shadowCamera,
  21261. pointsFrustum = light.pointsFrustum,
  21262. pointsWorld = light.pointsWorld;
  21263. _min.set( Infinity, Infinity, Infinity );
  21264. _max.set( -Infinity, -Infinity, -Infinity );
  21265. for ( var i = 0; i < 8; i ++ ) {
  21266. var p = pointsWorld[ i ];
  21267. p.copy( pointsFrustum[ i ] );
  21268. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21269. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21270. if ( p.x < _min.x ) _min.x = p.x;
  21271. if ( p.x > _max.x ) _max.x = p.x;
  21272. if ( p.y < _min.y ) _min.y = p.y;
  21273. if ( p.y > _max.y ) _max.y = p.y;
  21274. if ( p.z < _min.z ) _min.z = p.z;
  21275. if ( p.z > _max.z ) _max.z = p.z;
  21276. }
  21277. shadowCamera.left = _min.x;
  21278. shadowCamera.right = _max.x;
  21279. shadowCamera.top = _max.y;
  21280. shadowCamera.bottom = _min.y;
  21281. // can't really fit near/far
  21282. //shadowCamera.near = _min.z;
  21283. //shadowCamera.far = _max.z;
  21284. shadowCamera.updateProjectionMatrix();
  21285. }
  21286. // For the moment just ignore objects that have multiple materials with different animation methods
  21287. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21288. function getObjectMaterial( object ) {
  21289. return object.material instanceof THREE.MeshFaceMaterial
  21290. ? object.material.materials[ 0 ]
  21291. : object.material;
  21292. };
  21293. };
  21294. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21295. /**
  21296. * @author mikael emtinger / http://gomo.se/
  21297. * @author alteredq / http://alteredqualia.com/
  21298. */
  21299. THREE.SpritePlugin = function () {
  21300. var _gl, _renderer, _precision, _sprite = {};
  21301. this.init = function ( renderer ) {
  21302. _gl = renderer.context;
  21303. _renderer = renderer;
  21304. _precision = renderer.getPrecision();
  21305. _sprite.vertices = new Float32Array( 8 + 8 );
  21306. _sprite.faces = new Uint16Array( 6 );
  21307. var i = 0;
  21308. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21309. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21310. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21311. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21312. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21313. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21314. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21315. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21316. i = 0;
  21317. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21318. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21319. _sprite.vertexBuffer = _gl.createBuffer();
  21320. _sprite.elementBuffer = _gl.createBuffer();
  21321. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21322. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21323. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21324. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21325. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ], _precision );
  21326. _sprite.attributes = {};
  21327. _sprite.uniforms = {};
  21328. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21329. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21330. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21331. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21332. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21333. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21334. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21335. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21336. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21337. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21338. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21339. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  21340. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21341. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21342. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21343. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21344. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21345. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21346. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21347. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21348. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21349. };
  21350. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21351. var sprites = scene.__webglSprites,
  21352. nSprites = sprites.length;
  21353. if ( ! nSprites ) return;
  21354. var attributes = _sprite.attributes,
  21355. uniforms = _sprite.uniforms;
  21356. var invAspect = viewportHeight / viewportWidth;
  21357. var halfViewportWidth = viewportWidth * 0.5,
  21358. halfViewportHeight = viewportHeight * 0.5;
  21359. // setup gl
  21360. _gl.useProgram( _sprite.program );
  21361. _gl.enableVertexAttribArray( attributes.position );
  21362. _gl.enableVertexAttribArray( attributes.uv );
  21363. _gl.disable( _gl.CULL_FACE );
  21364. _gl.enable( _gl.BLEND );
  21365. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21366. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21367. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21368. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21369. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21370. _gl.activeTexture( _gl.TEXTURE0 );
  21371. _gl.uniform1i( uniforms.map, 0 );
  21372. var oldFogType = 0;
  21373. var sceneFogType = 0;
  21374. var fog = scene.fog;
  21375. if ( fog ) {
  21376. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21377. if ( fog instanceof THREE.Fog ) {
  21378. _gl.uniform1f( uniforms.fogNear, fog.near );
  21379. _gl.uniform1f( uniforms.fogFar, fog.far );
  21380. _gl.uniform1i( uniforms.fogType, 1 );
  21381. oldFogType = 1;
  21382. sceneFogType = 1;
  21383. } else if ( fog instanceof THREE.FogExp2 ) {
  21384. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21385. _gl.uniform1i( uniforms.fogType, 2 );
  21386. oldFogType = 2;
  21387. sceneFogType = 2;
  21388. }
  21389. } else {
  21390. _gl.uniform1i( uniforms.fogType, 0 );
  21391. oldFogType = 0;
  21392. sceneFogType = 0;
  21393. }
  21394. // update positions and sort
  21395. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21396. for( i = 0; i < nSprites; i ++ ) {
  21397. sprite = sprites[ i ];
  21398. material = sprite.material;
  21399. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21400. if ( ! material.useScreenCoordinates ) {
  21401. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21402. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21403. } else {
  21404. sprite.z = - sprite.position.z;
  21405. }
  21406. }
  21407. sprites.sort( painterSortStable );
  21408. // render all sprites
  21409. for( i = 0; i < nSprites; i ++ ) {
  21410. sprite = sprites[ i ];
  21411. material = sprite.material;
  21412. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21413. if ( material.map && material.map.image && material.map.image.width ) {
  21414. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21415. if ( material.useScreenCoordinates === true ) {
  21416. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21417. _gl.uniform3f(
  21418. uniforms.screenPosition,
  21419. ( ( sprite.position.x * _renderer.devicePixelRatio ) - halfViewportWidth ) / halfViewportWidth,
  21420. ( halfViewportHeight - ( sprite.position.y * _renderer.devicePixelRatio ) ) / halfViewportHeight,
  21421. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21422. );
  21423. scale[ 0 ] = _renderer.devicePixelRatio;
  21424. scale[ 1 ] = _renderer.devicePixelRatio;
  21425. } else {
  21426. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21427. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21428. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21429. scale[ 0 ] = 1;
  21430. scale[ 1 ] = 1;
  21431. }
  21432. if ( scene.fog && material.fog ) {
  21433. fogType = sceneFogType;
  21434. } else {
  21435. fogType = 0;
  21436. }
  21437. if ( oldFogType !== fogType ) {
  21438. _gl.uniform1i( uniforms.fogType, fogType );
  21439. oldFogType = fogType;
  21440. }
  21441. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21442. scale[ 0 ] *= size * invAspect * sprite.scale.x
  21443. scale[ 1 ] *= size * sprite.scale.y;
  21444. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21445. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21446. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21447. _gl.uniform1f( uniforms.opacity, material.opacity );
  21448. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21449. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21450. _gl.uniform2fv( uniforms.scale, scale );
  21451. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21452. _renderer.setDepthTest( material.depthTest );
  21453. _renderer.setDepthWrite( material.depthWrite );
  21454. _renderer.setTexture( material.map, 0 );
  21455. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21456. }
  21457. }
  21458. // restore gl
  21459. _gl.enable( _gl.CULL_FACE );
  21460. };
  21461. function createProgram ( shader, precision ) {
  21462. var program = _gl.createProgram();
  21463. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21464. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21465. var prefix = "precision " + precision + " float;\n";
  21466. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21467. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21468. _gl.compileShader( fragmentShader );
  21469. _gl.compileShader( vertexShader );
  21470. _gl.attachShader( program, fragmentShader );
  21471. _gl.attachShader( program, vertexShader );
  21472. _gl.linkProgram( program );
  21473. return program;
  21474. };
  21475. function painterSortStable ( a, b ) {
  21476. if ( a.z !== b.z ) {
  21477. return b.z - a.z;
  21478. } else {
  21479. return b.id - a.id;
  21480. }
  21481. };
  21482. };
  21483. /**
  21484. * @author alteredq / http://alteredqualia.com/
  21485. */
  21486. THREE.DepthPassPlugin = function () {
  21487. this.enabled = false;
  21488. this.renderTarget = null;
  21489. var _gl,
  21490. _renderer,
  21491. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21492. _frustum = new THREE.Frustum(),
  21493. _projScreenMatrix = new THREE.Matrix4();
  21494. this.init = function ( renderer ) {
  21495. _gl = renderer.context;
  21496. _renderer = renderer;
  21497. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21498. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21499. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21500. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21501. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21502. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21503. _depthMaterial._shadowPass = true;
  21504. _depthMaterialMorph._shadowPass = true;
  21505. _depthMaterialSkin._shadowPass = true;
  21506. _depthMaterialMorphSkin._shadowPass = true;
  21507. };
  21508. this.render = function ( scene, camera ) {
  21509. if ( ! this.enabled ) return;
  21510. this.update( scene, camera );
  21511. };
  21512. this.update = function ( scene, camera ) {
  21513. var i, il, j, jl, n,
  21514. program, buffer, material,
  21515. webglObject, object, light,
  21516. renderList,
  21517. fog = null;
  21518. // set GL state for depth map
  21519. _gl.clearColor( 1, 1, 1, 1 );
  21520. _gl.disable( _gl.BLEND );
  21521. _renderer.setDepthTest( true );
  21522. // update scene
  21523. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21524. // update camera matrices and frustum
  21525. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21526. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21527. _frustum.setFromMatrix( _projScreenMatrix );
  21528. // render depth map
  21529. _renderer.setRenderTarget( this.renderTarget );
  21530. _renderer.clear();
  21531. // set object matrices & frustum culling
  21532. renderList = scene.__webglObjects;
  21533. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21534. webglObject = renderList[ j ];
  21535. object = webglObject.object;
  21536. webglObject.render = false;
  21537. if ( object.visible ) {
  21538. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21539. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21540. webglObject.render = true;
  21541. }
  21542. }
  21543. }
  21544. // render regular objects
  21545. var objectMaterial, useMorphing, useSkinning;
  21546. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21547. webglObject = renderList[ j ];
  21548. if ( webglObject.render ) {
  21549. object = webglObject.object;
  21550. buffer = webglObject.buffer;
  21551. // todo: create proper depth material for particles
  21552. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21553. objectMaterial = getObjectMaterial( object );
  21554. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21555. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21556. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21557. if ( object.customDepthMaterial ) {
  21558. material = object.customDepthMaterial;
  21559. } else if ( useSkinning ) {
  21560. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21561. } else if ( useMorphing ) {
  21562. material = _depthMaterialMorph;
  21563. } else {
  21564. material = _depthMaterial;
  21565. }
  21566. if ( buffer instanceof THREE.BufferGeometry ) {
  21567. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21568. } else {
  21569. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21570. }
  21571. }
  21572. }
  21573. // set matrices and render immediate objects
  21574. renderList = scene.__webglObjectsImmediate;
  21575. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21576. webglObject = renderList[ j ];
  21577. object = webglObject.object;
  21578. if ( object.visible ) {
  21579. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21580. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21581. }
  21582. }
  21583. // restore GL state
  21584. var clearColor = _renderer.getClearColor(),
  21585. clearAlpha = _renderer.getClearAlpha();
  21586. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21587. _gl.enable( _gl.BLEND );
  21588. };
  21589. // For the moment just ignore objects that have multiple materials with different animation methods
  21590. // Only the first material will be taken into account for deciding which depth material to use
  21591. function getObjectMaterial( object ) {
  21592. return object.material instanceof THREE.MeshFaceMaterial
  21593. ? object.material.materials[ 0 ]
  21594. : object.material;
  21595. };
  21596. };
  21597. /**
  21598. * @author mikael emtinger / http://gomo.se/
  21599. *
  21600. */
  21601. THREE.ShaderFlares = {
  21602. 'lensFlareVertexTexture': {
  21603. vertexShader: [
  21604. "uniform lowp int renderType;",
  21605. "uniform vec3 screenPosition;",
  21606. "uniform vec2 scale;",
  21607. "uniform float rotation;",
  21608. "uniform sampler2D occlusionMap;",
  21609. "attribute vec2 position;",
  21610. "attribute vec2 uv;",
  21611. "varying vec2 vUV;",
  21612. "varying float vVisibility;",
  21613. "void main() {",
  21614. "vUV = uv;",
  21615. "vec2 pos = position;",
  21616. "if( renderType == 2 ) {",
  21617. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21618. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21619. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21620. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21621. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21622. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21623. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21624. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21625. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21626. "vVisibility = ( visibility.r / 9.0 ) *",
  21627. "( 1.0 - visibility.g / 9.0 ) *",
  21628. "( visibility.b / 9.0 ) *",
  21629. "( 1.0 - visibility.a / 9.0 );",
  21630. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21631. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21632. "}",
  21633. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21634. "}"
  21635. ].join( "\n" ),
  21636. fragmentShader: [
  21637. "uniform lowp int renderType;",
  21638. "uniform sampler2D map;",
  21639. "uniform float opacity;",
  21640. "uniform vec3 color;",
  21641. "varying vec2 vUV;",
  21642. "varying float vVisibility;",
  21643. "void main() {",
  21644. // pink square
  21645. "if( renderType == 0 ) {",
  21646. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21647. // restore
  21648. "} else if( renderType == 1 ) {",
  21649. "gl_FragColor = texture2D( map, vUV );",
  21650. // flare
  21651. "} else {",
  21652. "vec4 texture = texture2D( map, vUV );",
  21653. "texture.a *= opacity * vVisibility;",
  21654. "gl_FragColor = texture;",
  21655. "gl_FragColor.rgb *= color;",
  21656. "}",
  21657. "}"
  21658. ].join( "\n" )
  21659. },
  21660. 'lensFlare': {
  21661. vertexShader: [
  21662. "uniform lowp int renderType;",
  21663. "uniform vec3 screenPosition;",
  21664. "uniform vec2 scale;",
  21665. "uniform float rotation;",
  21666. "attribute vec2 position;",
  21667. "attribute vec2 uv;",
  21668. "varying vec2 vUV;",
  21669. "void main() {",
  21670. "vUV = uv;",
  21671. "vec2 pos = position;",
  21672. "if( renderType == 2 ) {",
  21673. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21674. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21675. "}",
  21676. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21677. "}"
  21678. ].join( "\n" ),
  21679. fragmentShader: [
  21680. "precision mediump float;",
  21681. "uniform lowp int renderType;",
  21682. "uniform sampler2D map;",
  21683. "uniform sampler2D occlusionMap;",
  21684. "uniform float opacity;",
  21685. "uniform vec3 color;",
  21686. "varying vec2 vUV;",
  21687. "void main() {",
  21688. // pink square
  21689. "if( renderType == 0 ) {",
  21690. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21691. // restore
  21692. "} else if( renderType == 1 ) {",
  21693. "gl_FragColor = texture2D( map, vUV );",
  21694. // flare
  21695. "} else {",
  21696. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21697. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21698. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21699. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21700. "visibility = ( 1.0 - visibility / 4.0 );",
  21701. "vec4 texture = texture2D( map, vUV );",
  21702. "texture.a *= opacity * visibility;",
  21703. "gl_FragColor = texture;",
  21704. "gl_FragColor.rgb *= color;",
  21705. "}",
  21706. "}"
  21707. ].join( "\n" )
  21708. }
  21709. };
  21710. /**
  21711. * @author mikael emtinger / http://gomo.se/
  21712. * @author alteredq / http://alteredqualia.com/
  21713. *
  21714. */
  21715. THREE.ShaderSprite = {
  21716. 'sprite': {
  21717. vertexShader: [
  21718. "uniform int useScreenCoordinates;",
  21719. "uniform int sizeAttenuation;",
  21720. "uniform vec3 screenPosition;",
  21721. "uniform mat4 modelViewMatrix;",
  21722. "uniform mat4 projectionMatrix;",
  21723. "uniform float rotation;",
  21724. "uniform vec2 scale;",
  21725. "uniform vec2 alignment;",
  21726. "uniform vec2 uvOffset;",
  21727. "uniform vec2 uvScale;",
  21728. "attribute vec2 position;",
  21729. "attribute vec2 uv;",
  21730. "varying vec2 vUV;",
  21731. "void main() {",
  21732. "vUV = uvOffset + uv * uvScale;",
  21733. "vec2 alignedPosition = position + alignment;",
  21734. "vec2 rotatedPosition;",
  21735. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21736. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21737. "vec4 finalPosition;",
  21738. "if( useScreenCoordinates != 0 ) {",
  21739. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21740. "} else {",
  21741. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21742. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  21743. "}",
  21744. "gl_Position = finalPosition;",
  21745. "}"
  21746. ].join( "\n" ),
  21747. fragmentShader: [
  21748. "uniform vec3 color;",
  21749. "uniform sampler2D map;",
  21750. "uniform float opacity;",
  21751. "uniform int fogType;",
  21752. "uniform vec3 fogColor;",
  21753. "uniform float fogDensity;",
  21754. "uniform float fogNear;",
  21755. "uniform float fogFar;",
  21756. "uniform float alphaTest;",
  21757. "varying vec2 vUV;",
  21758. "void main() {",
  21759. "vec4 texture = texture2D( map, vUV );",
  21760. "if ( texture.a < alphaTest ) discard;",
  21761. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21762. "if ( fogType > 0 ) {",
  21763. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  21764. "float fogFactor = 0.0;",
  21765. "if ( fogType == 1 ) {",
  21766. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  21767. "} else {",
  21768. "const float LOG2 = 1.442695;",
  21769. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  21770. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  21771. "}",
  21772. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  21773. "}",
  21774. "}"
  21775. ].join( "\n" )
  21776. }
  21777. };