three.js 792 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. * @author bhouston / http://exocortex.com
  5. */
  6. var THREE = THREE || { REVISION: '60dev' };
  7. self.console = self.console || {
  8. info: function () {},
  9. log: function () {},
  10. debug: function () {},
  11. warn: function () {},
  12. error: function () {}
  13. };
  14. String.prototype.trim = String.prototype.trim || function () {
  15. return this.replace( /^\s+|\s+$/g, '' );
  16. };
  17. // based on https://github.com/documentcloud/underscore/blob/bf657be243a075b5e72acc8a83e6f12a564d8f55/underscore.js#L767
  18. THREE.extend = function ( obj, source ) {
  19. // ECMAScript5 compatibility based on: http://www.nczonline.net/blog/2012/12/11/are-your-mixins-ecmascript-5-compatible/
  20. if ( Object.keys ) {
  21. var keys = Object.keys( source );
  22. for (var i = 0, il = keys.length; i < il; i++) {
  23. var prop = keys[i];
  24. Object.defineProperty( obj, prop, Object.getOwnPropertyDescriptor( source, prop ) );
  25. }
  26. } else {
  27. var safeHasOwnProperty = {}.hasOwnProperty;
  28. for ( var prop in source ) {
  29. if ( safeHasOwnProperty.call( source, prop ) ) {
  30. obj[prop] = source[prop];
  31. }
  32. }
  33. }
  34. return obj;
  35. };
  36. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  37. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  38. // requestAnimationFrame polyfill by Erik Möller
  39. // fixes from Paul Irish and Tino Zijdel
  40. // using 'self' instead of 'window' for compatibility with both NodeJS and IE10.
  41. ( function () {
  42. var lastTime = 0;
  43. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  44. for ( var x = 0; x < vendors.length && !self.requestAnimationFrame; ++ x ) {
  45. self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ];
  46. self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  47. }
  48. if ( self.requestAnimationFrame === undefined && self['setTimeout'] !== undefined ) {
  49. self.requestAnimationFrame = function ( callback ) {
  50. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  51. var id = self.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  52. lastTime = currTime + timeToCall;
  53. return id;
  54. };
  55. }
  56. if( self.cancelAnimationFrame === undefined && self['clearTimeout'] !== undefined ) {
  57. self.cancelAnimationFrame = function ( id ) { self.clearTimeout( id ) };
  58. }
  59. }() );
  60. // GL STATE CONSTANTS
  61. THREE.CullFaceNone = 0;
  62. THREE.CullFaceBack = 1;
  63. THREE.CullFaceFront = 2;
  64. THREE.CullFaceFrontBack = 3;
  65. THREE.FrontFaceDirectionCW = 0;
  66. THREE.FrontFaceDirectionCCW = 1;
  67. // SHADOWING TYPES
  68. THREE.BasicShadowMap = 0;
  69. THREE.PCFShadowMap = 1;
  70. THREE.PCFSoftShadowMap = 2;
  71. // MATERIAL CONSTANTS
  72. // side
  73. THREE.FrontSide = 0;
  74. THREE.BackSide = 1;
  75. THREE.DoubleSide = 2;
  76. // shading
  77. THREE.NoShading = 0;
  78. THREE.FlatShading = 1;
  79. THREE.SmoothShading = 2;
  80. // colors
  81. THREE.NoColors = 0;
  82. THREE.FaceColors = 1;
  83. THREE.VertexColors = 2;
  84. // blending modes
  85. THREE.NoBlending = 0;
  86. THREE.NormalBlending = 1;
  87. THREE.AdditiveBlending = 2;
  88. THREE.SubtractiveBlending = 3;
  89. THREE.MultiplyBlending = 4;
  90. THREE.CustomBlending = 5;
  91. // custom blending equations
  92. // (numbers start from 100 not to clash with other
  93. // mappings to OpenGL constants defined in Texture.js)
  94. THREE.AddEquation = 100;
  95. THREE.SubtractEquation = 101;
  96. THREE.ReverseSubtractEquation = 102;
  97. // custom blending destination factors
  98. THREE.ZeroFactor = 200;
  99. THREE.OneFactor = 201;
  100. THREE.SrcColorFactor = 202;
  101. THREE.OneMinusSrcColorFactor = 203;
  102. THREE.SrcAlphaFactor = 204;
  103. THREE.OneMinusSrcAlphaFactor = 205;
  104. THREE.DstAlphaFactor = 206;
  105. THREE.OneMinusDstAlphaFactor = 207;
  106. // custom blending source factors
  107. //THREE.ZeroFactor = 200;
  108. //THREE.OneFactor = 201;
  109. //THREE.SrcAlphaFactor = 204;
  110. //THREE.OneMinusSrcAlphaFactor = 205;
  111. //THREE.DstAlphaFactor = 206;
  112. //THREE.OneMinusDstAlphaFactor = 207;
  113. THREE.DstColorFactor = 208;
  114. THREE.OneMinusDstColorFactor = 209;
  115. THREE.SrcAlphaSaturateFactor = 210;
  116. // TEXTURE CONSTANTS
  117. THREE.MultiplyOperation = 0;
  118. THREE.MixOperation = 1;
  119. THREE.AddOperation = 2;
  120. // Mapping modes
  121. THREE.UVMapping = function () {};
  122. THREE.CubeReflectionMapping = function () {};
  123. THREE.CubeRefractionMapping = function () {};
  124. THREE.SphericalReflectionMapping = function () {};
  125. THREE.SphericalRefractionMapping = function () {};
  126. // Wrapping modes
  127. THREE.RepeatWrapping = 1000;
  128. THREE.ClampToEdgeWrapping = 1001;
  129. THREE.MirroredRepeatWrapping = 1002;
  130. // Filters
  131. THREE.NearestFilter = 1003;
  132. THREE.NearestMipMapNearestFilter = 1004;
  133. THREE.NearestMipMapLinearFilter = 1005;
  134. THREE.LinearFilter = 1006;
  135. THREE.LinearMipMapNearestFilter = 1007;
  136. THREE.LinearMipMapLinearFilter = 1008;
  137. // Data types
  138. THREE.UnsignedByteType = 1009;
  139. THREE.ByteType = 1010;
  140. THREE.ShortType = 1011;
  141. THREE.UnsignedShortType = 1012;
  142. THREE.IntType = 1013;
  143. THREE.UnsignedIntType = 1014;
  144. THREE.FloatType = 1015;
  145. // Pixel types
  146. //THREE.UnsignedByteType = 1009;
  147. THREE.UnsignedShort4444Type = 1016;
  148. THREE.UnsignedShort5551Type = 1017;
  149. THREE.UnsignedShort565Type = 1018;
  150. // Pixel formats
  151. THREE.AlphaFormat = 1019;
  152. THREE.RGBFormat = 1020;
  153. THREE.RGBAFormat = 1021;
  154. THREE.LuminanceFormat = 1022;
  155. THREE.LuminanceAlphaFormat = 1023;
  156. // Compressed texture formats
  157. THREE.RGB_S3TC_DXT1_Format = 2001;
  158. THREE.RGBA_S3TC_DXT1_Format = 2002;
  159. THREE.RGBA_S3TC_DXT3_Format = 2003;
  160. THREE.RGBA_S3TC_DXT5_Format = 2004;
  161. /*
  162. // Potential future PVRTC compressed texture formats
  163. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  164. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  165. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  166. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  167. */
  168. /**
  169. * @author mrdoob / http://mrdoob.com/
  170. */
  171. THREE.Color = function ( value ) {
  172. if ( value !== undefined ) this.set( value );
  173. return this;
  174. };
  175. THREE.Color.prototype = {
  176. constructor: THREE.Color,
  177. r: 1, g: 1, b: 1,
  178. set: function ( value ) {
  179. if ( value instanceof THREE.Color ) {
  180. this.copy( value );
  181. } else if ( typeof value === 'number' ) {
  182. this.setHex( value );
  183. } else if ( typeof value === 'string' ) {
  184. this.setStyle( value );
  185. }
  186. return this;
  187. },
  188. setHex: function ( hex ) {
  189. hex = Math.floor( hex );
  190. this.r = ( hex >> 16 & 255 ) / 255;
  191. this.g = ( hex >> 8 & 255 ) / 255;
  192. this.b = ( hex & 255 ) / 255;
  193. return this;
  194. },
  195. setRGB: function ( r, g, b ) {
  196. this.r = r;
  197. this.g = g;
  198. this.b = b;
  199. return this;
  200. },
  201. setHSL: function ( h, s, l ) {
  202. // h,s,l ranges are in 0.0 - 1.0
  203. if ( s === 0 ) {
  204. this.r = this.g = this.b = l;
  205. } else {
  206. var hue2rgb = function ( p, q, t ) {
  207. if ( t < 0 ) t += 1;
  208. if ( t > 1 ) t -= 1;
  209. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  210. if ( t < 1 / 2 ) return q;
  211. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  212. return p;
  213. };
  214. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  215. var q = ( 2 * l ) - p;
  216. this.r = hue2rgb( q, p, h + 1 / 3 );
  217. this.g = hue2rgb( q, p, h );
  218. this.b = hue2rgb( q, p, h - 1 / 3 );
  219. }
  220. return this;
  221. },
  222. setStyle: function ( style ) {
  223. // rgb(255,0,0)
  224. if ( /^rgb\((\d+),(\d+),(\d+)\)$/i.test( style ) ) {
  225. var color = /^rgb\((\d+),(\d+),(\d+)\)$/i.exec( style );
  226. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  227. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  228. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  229. return this;
  230. }
  231. // rgb(100%,0%,0%)
  232. if ( /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test( style ) ) {
  233. var color = /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec( style );
  234. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  235. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  236. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  237. return this;
  238. }
  239. // #ff0000
  240. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  241. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  242. this.setHex( parseInt( color[ 1 ], 16 ) );
  243. return this;
  244. }
  245. // #f00
  246. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  247. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  248. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  249. return this;
  250. }
  251. // red
  252. if ( /^(\w+)$/i.test( style ) ) {
  253. this.setHex( THREE.ColorKeywords[ style ] );
  254. return this;
  255. }
  256. },
  257. copy: function ( color ) {
  258. this.r = color.r;
  259. this.g = color.g;
  260. this.b = color.b;
  261. return this;
  262. },
  263. copyGammaToLinear: function ( color ) {
  264. this.r = color.r * color.r;
  265. this.g = color.g * color.g;
  266. this.b = color.b * color.b;
  267. return this;
  268. },
  269. copyLinearToGamma: function ( color ) {
  270. this.r = Math.sqrt( color.r );
  271. this.g = Math.sqrt( color.g );
  272. this.b = Math.sqrt( color.b );
  273. return this;
  274. },
  275. convertGammaToLinear: function () {
  276. var r = this.r, g = this.g, b = this.b;
  277. this.r = r * r;
  278. this.g = g * g;
  279. this.b = b * b;
  280. return this;
  281. },
  282. convertLinearToGamma: function () {
  283. this.r = Math.sqrt( this.r );
  284. this.g = Math.sqrt( this.g );
  285. this.b = Math.sqrt( this.b );
  286. return this;
  287. },
  288. getHex: function () {
  289. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  290. },
  291. getHexString: function () {
  292. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  293. },
  294. getHSL: function () {
  295. var hsl = { h: 0, s: 0, l: 0 };
  296. return function () {
  297. // h,s,l ranges are in 0.0 - 1.0
  298. var r = this.r, g = this.g, b = this.b;
  299. var max = Math.max( r, g, b );
  300. var min = Math.min( r, g, b );
  301. var hue, saturation;
  302. var lightness = ( min + max ) / 2.0;
  303. if ( min === max ) {
  304. hue = 0;
  305. saturation = 0;
  306. } else {
  307. var delta = max - min;
  308. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  309. switch ( max ) {
  310. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  311. case g: hue = ( b - r ) / delta + 2; break;
  312. case b: hue = ( r - g ) / delta + 4; break;
  313. }
  314. hue /= 6;
  315. }
  316. hsl.h = hue;
  317. hsl.s = saturation;
  318. hsl.l = lightness;
  319. return hsl;
  320. };
  321. }(),
  322. getStyle: function () {
  323. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  324. },
  325. offsetHSL: function ( h, s, l ) {
  326. var hsl = this.getHSL();
  327. hsl.h += h; hsl.s += s; hsl.l += l;
  328. this.setHSL( hsl.h, hsl.s, hsl.l );
  329. return this;
  330. },
  331. add: function ( color ) {
  332. this.r += color.r;
  333. this.g += color.g;
  334. this.b += color.b;
  335. return this;
  336. },
  337. addColors: function ( color1, color2 ) {
  338. this.r = color1.r + color2.r;
  339. this.g = color1.g + color2.g;
  340. this.b = color1.b + color2.b;
  341. return this;
  342. },
  343. addScalar: function ( s ) {
  344. this.r += s;
  345. this.g += s;
  346. this.b += s;
  347. return this;
  348. },
  349. multiply: function ( color ) {
  350. this.r *= color.r;
  351. this.g *= color.g;
  352. this.b *= color.b;
  353. return this;
  354. },
  355. multiplyScalar: function ( s ) {
  356. this.r *= s;
  357. this.g *= s;
  358. this.b *= s;
  359. return this;
  360. },
  361. lerp: function ( color, alpha ) {
  362. this.r += ( color.r - this.r ) * alpha;
  363. this.g += ( color.g - this.g ) * alpha;
  364. this.b += ( color.b - this.b ) * alpha;
  365. return this;
  366. },
  367. equals: function ( c ) {
  368. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  369. },
  370. fromArray: function ( array ) {
  371. this.r = array[ 0 ];
  372. this.g = array[ 1 ];
  373. this.b = array[ 2 ];
  374. return this;
  375. },
  376. toArray: function () {
  377. return [ this.r, this.g, this.b ];
  378. },
  379. clone: function () {
  380. return new THREE.Color().setRGB( this.r, this.g, this.b );
  381. }
  382. };
  383. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  384. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  385. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  386. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  387. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  388. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  389. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  390. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  391. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  392. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  393. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  394. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  395. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  396. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  397. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  398. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  399. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  400. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  401. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  402. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  403. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  404. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  405. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  406. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  407. /**
  408. * @author mikael emtinger / http://gomo.se/
  409. * @author alteredq / http://alteredqualia.com/
  410. * @author WestLangley / http://github.com/WestLangley
  411. * @author bhouston / http://exocortex.com
  412. */
  413. THREE.Quaternion = function ( x, y, z, w ) {
  414. this._x = x || 0;
  415. this._y = y || 0;
  416. this._z = z || 0;
  417. this._w = ( w !== undefined ) ? w : 1;
  418. };
  419. THREE.Quaternion.prototype = {
  420. constructor: THREE.Quaternion,
  421. _x: 0,_y: 0, _z: 0, _w: 0,
  422. _euler: undefined,
  423. _updateEuler: function ( callback ) {
  424. if ( this._euler !== undefined ) {
  425. this._euler.setFromQuaternion( this, undefined, false );
  426. }
  427. },
  428. get x () {
  429. return this._x;
  430. },
  431. set x ( value ) {
  432. this._x = value;
  433. this._updateEuler();
  434. },
  435. get y () {
  436. return this._y;
  437. },
  438. set y ( value ) {
  439. this._y = value;
  440. this._updateEuler();
  441. },
  442. get z () {
  443. return this._z;
  444. },
  445. set z ( value ) {
  446. this._z = value;
  447. this._updateEuler();
  448. },
  449. get w () {
  450. return this._w;
  451. },
  452. set w ( value ) {
  453. this._w = value;
  454. this._updateEuler();
  455. },
  456. set: function ( x, y, z, w ) {
  457. this._x = x;
  458. this._y = y;
  459. this._z = z;
  460. this._w = w;
  461. this._updateEuler();
  462. return this;
  463. },
  464. copy: function ( quaternion ) {
  465. this._x = quaternion._x;
  466. this._y = quaternion._y;
  467. this._z = quaternion._z;
  468. this._w = quaternion._w;
  469. this._updateEuler();
  470. return this;
  471. },
  472. setFromEuler: function ( euler, update ) {
  473. if ( typeof euler['order'] === undefined ) {
  474. console.error( 'ERROR: Quaternion\'s .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  475. }
  476. // http://www.mathworks.com/matlabcentral/fileexchange/
  477. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  478. // content/SpinCalc.m
  479. var c1 = Math.cos( euler._x / 2 );
  480. var c2 = Math.cos( euler._y / 2 );
  481. var c3 = Math.cos( euler._z / 2 );
  482. var s1 = Math.sin( euler._x / 2 );
  483. var s2 = Math.sin( euler._y / 2 );
  484. var s3 = Math.sin( euler._z / 2 );
  485. if ( euler.order === undefined || euler.order === 'XYZ' ) {
  486. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  487. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  488. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  489. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  490. } else if ( euler.order === 'YXZ' ) {
  491. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  492. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  493. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  494. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  495. } else if ( euler.order === 'ZXY' ) {
  496. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  497. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  498. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  499. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  500. } else if ( euler.order === 'ZYX' ) {
  501. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  502. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  503. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  504. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  505. } else if ( euler.order === 'YZX' ) {
  506. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  507. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  508. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  509. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  510. } else if ( euler.order === 'XZY' ) {
  511. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  512. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  513. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  514. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  515. }
  516. if ( update !== false ) this._updateEuler();
  517. return this;
  518. },
  519. setFromAxisAngle: function ( axis, angle ) {
  520. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  521. // axis have to be normalized
  522. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  523. this._x = axis.x * s;
  524. this._y = axis.y * s;
  525. this._z = axis.z * s;
  526. this._w = Math.cos( halfAngle );
  527. this._updateEuler();
  528. return this;
  529. },
  530. setFromRotationMatrix: function ( m ) {
  531. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  532. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  533. var te = m.elements,
  534. m11 = te[0], m12 = te[4], m13 = te[8],
  535. m21 = te[1], m22 = te[5], m23 = te[9],
  536. m31 = te[2], m32 = te[6], m33 = te[10],
  537. trace = m11 + m22 + m33,
  538. s;
  539. if ( trace > 0 ) {
  540. s = 0.5 / Math.sqrt( trace + 1.0 );
  541. this._w = 0.25 / s;
  542. this._x = ( m32 - m23 ) * s;
  543. this._y = ( m13 - m31 ) * s;
  544. this._z = ( m21 - m12 ) * s;
  545. } else if ( m11 > m22 && m11 > m33 ) {
  546. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  547. this._w = (m32 - m23 ) / s;
  548. this._x = 0.25 * s;
  549. this._y = (m12 + m21 ) / s;
  550. this._z = (m13 + m31 ) / s;
  551. } else if ( m22 > m33 ) {
  552. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  553. this._w = (m13 - m31 ) / s;
  554. this._x = (m12 + m21 ) / s;
  555. this._y = 0.25 * s;
  556. this._z = (m23 + m32 ) / s;
  557. } else {
  558. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  559. this._w = ( m21 - m12 ) / s;
  560. this._x = ( m13 + m31 ) / s;
  561. this._y = ( m23 + m32 ) / s;
  562. this._z = 0.25 * s;
  563. }
  564. this._updateEuler();
  565. return this;
  566. },
  567. inverse: function () {
  568. this.conjugate().normalize();
  569. return this;
  570. },
  571. conjugate: function () {
  572. this._x *= -1;
  573. this._y *= -1;
  574. this._z *= -1;
  575. this._updateEuler();
  576. return this;
  577. },
  578. lengthSq: function () {
  579. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  580. },
  581. length: function () {
  582. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  583. },
  584. normalize: function () {
  585. var l = this.length();
  586. if ( l === 0 ) {
  587. this._x = 0;
  588. this._y = 0;
  589. this._z = 0;
  590. this._w = 1;
  591. } else {
  592. l = 1 / l;
  593. this._x = this._x * l;
  594. this._y = this._y * l;
  595. this._z = this._z * l;
  596. this._w = this._w * l;
  597. }
  598. return this;
  599. },
  600. multiply: function ( q, p ) {
  601. if ( p !== undefined ) {
  602. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  603. return this.multiplyQuaternions( q, p );
  604. }
  605. return this.multiplyQuaternions( this, q );
  606. },
  607. multiplyQuaternions: function ( a, b ) {
  608. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  609. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  610. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  611. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  612. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  613. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  614. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  615. this._updateEuler();
  616. return this;
  617. },
  618. multiplyVector3: function ( vector ) {
  619. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  620. return vector.applyQuaternion( this );
  621. },
  622. slerp: function ( qb, t ) {
  623. var x = this._x, y = this._y, z = this._z, w = this._w;
  624. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  625. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  626. if ( cosHalfTheta < 0 ) {
  627. this._w = -qb._w;
  628. this._x = -qb._x;
  629. this._y = -qb._y;
  630. this._z = -qb._z;
  631. cosHalfTheta = -cosHalfTheta;
  632. } else {
  633. this.copy( qb );
  634. }
  635. if ( cosHalfTheta >= 1.0 ) {
  636. this._w = w;
  637. this._x = x;
  638. this._y = y;
  639. this._z = z;
  640. return this;
  641. }
  642. var halfTheta = Math.acos( cosHalfTheta );
  643. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  644. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  645. this._w = 0.5 * ( w + this._w );
  646. this._x = 0.5 * ( x + this._x );
  647. this._y = 0.5 * ( y + this._y );
  648. this._z = 0.5 * ( z + this._z );
  649. return this;
  650. }
  651. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  652. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  653. this._w = ( w * ratioA + this._w * ratioB );
  654. this._x = ( x * ratioA + this._x * ratioB );
  655. this._y = ( y * ratioA + this._y * ratioB );
  656. this._z = ( z * ratioA + this._z * ratioB );
  657. this._updateEuler();
  658. return this;
  659. },
  660. equals: function ( quaternion ) {
  661. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  662. },
  663. fromArray: function ( array ) {
  664. this._x = array[ 0 ];
  665. this._y = array[ 1 ];
  666. this._z = array[ 2 ];
  667. this._w = array[ 3 ];
  668. this._updateEuler();
  669. return this;
  670. },
  671. toArray: function () {
  672. return [ this._x, this._y, this._z, this._w ];
  673. },
  674. clone: function () {
  675. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  676. }
  677. };
  678. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  679. return qm.copy( qa ).slerp( qb, t );
  680. }
  681. /**
  682. * @author mrdoob / http://mrdoob.com/
  683. * @author philogb / http://blog.thejit.org/
  684. * @author egraether / http://egraether.com/
  685. * @author zz85 / http://www.lab4games.net/zz85/blog
  686. */
  687. THREE.Vector2 = function ( x, y ) {
  688. this.x = x || 0;
  689. this.y = y || 0;
  690. };
  691. THREE.Vector2.prototype = {
  692. constructor: THREE.Vector2,
  693. set: function ( x, y ) {
  694. this.x = x;
  695. this.y = y;
  696. return this;
  697. },
  698. setX: function ( x ) {
  699. this.x = x;
  700. return this;
  701. },
  702. setY: function ( y ) {
  703. this.y = y;
  704. return this;
  705. },
  706. setComponent: function ( index, value ) {
  707. switch ( index ) {
  708. case 0: this.x = value; break;
  709. case 1: this.y = value; break;
  710. default: throw new Error( "index is out of range: " + index );
  711. }
  712. },
  713. getComponent: function ( index ) {
  714. switch ( index ) {
  715. case 0: return this.x;
  716. case 1: return this.y;
  717. default: throw new Error( "index is out of range: " + index );
  718. }
  719. },
  720. copy: function ( v ) {
  721. this.x = v.x;
  722. this.y = v.y;
  723. return this;
  724. },
  725. add: function ( v, w ) {
  726. if ( w !== undefined ) {
  727. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  728. return this.addVectors( v, w );
  729. }
  730. this.x += v.x;
  731. this.y += v.y;
  732. return this;
  733. },
  734. addVectors: function ( a, b ) {
  735. this.x = a.x + b.x;
  736. this.y = a.y + b.y;
  737. return this;
  738. },
  739. addScalar: function ( s ) {
  740. this.x += s;
  741. this.y += s;
  742. return this;
  743. },
  744. sub: function ( v, w ) {
  745. if ( w !== undefined ) {
  746. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  747. return this.subVectors( v, w );
  748. }
  749. this.x -= v.x;
  750. this.y -= v.y;
  751. return this;
  752. },
  753. subVectors: function ( a, b ) {
  754. this.x = a.x - b.x;
  755. this.y = a.y - b.y;
  756. return this;
  757. },
  758. multiplyScalar: function ( s ) {
  759. this.x *= s;
  760. this.y *= s;
  761. return this;
  762. },
  763. divideScalar: function ( scalar ) {
  764. if ( scalar !== 0 ) {
  765. var invScalar = 1 / scalar;
  766. this.x *= invScalar;
  767. this.y *= invScalar;
  768. } else {
  769. this.x = 0;
  770. this.y = 0;
  771. }
  772. return this;
  773. },
  774. min: function ( v ) {
  775. if ( this.x > v.x ) {
  776. this.x = v.x;
  777. }
  778. if ( this.y > v.y ) {
  779. this.y = v.y;
  780. }
  781. return this;
  782. },
  783. max: function ( v ) {
  784. if ( this.x < v.x ) {
  785. this.x = v.x;
  786. }
  787. if ( this.y < v.y ) {
  788. this.y = v.y;
  789. }
  790. return this;
  791. },
  792. clamp: function ( min, max ) {
  793. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  794. if ( this.x < min.x ) {
  795. this.x = min.x;
  796. } else if ( this.x > max.x ) {
  797. this.x = max.x;
  798. }
  799. if ( this.y < min.y ) {
  800. this.y = min.y;
  801. } else if ( this.y > max.y ) {
  802. this.y = max.y;
  803. }
  804. return this;
  805. },
  806. negate: function() {
  807. return this.multiplyScalar( - 1 );
  808. },
  809. dot: function ( v ) {
  810. return this.x * v.x + this.y * v.y;
  811. },
  812. lengthSq: function () {
  813. return this.x * this.x + this.y * this.y;
  814. },
  815. length: function () {
  816. return Math.sqrt( this.x * this.x + this.y * this.y );
  817. },
  818. normalize: function () {
  819. return this.divideScalar( this.length() );
  820. },
  821. distanceTo: function ( v ) {
  822. return Math.sqrt( this.distanceToSquared( v ) );
  823. },
  824. distanceToSquared: function ( v ) {
  825. var dx = this.x - v.x, dy = this.y - v.y;
  826. return dx * dx + dy * dy;
  827. },
  828. setLength: function ( l ) {
  829. var oldLength = this.length();
  830. if ( oldLength !== 0 && l !== oldLength ) {
  831. this.multiplyScalar( l / oldLength );
  832. }
  833. return this;
  834. },
  835. lerp: function ( v, alpha ) {
  836. this.x += ( v.x - this.x ) * alpha;
  837. this.y += ( v.y - this.y ) * alpha;
  838. return this;
  839. },
  840. equals: function( v ) {
  841. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  842. },
  843. fromArray: function ( array ) {
  844. this.x = array[ 0 ];
  845. this.y = array[ 1 ];
  846. return this;
  847. },
  848. toArray: function () {
  849. return [ this.x, this.y ];
  850. },
  851. clone: function () {
  852. return new THREE.Vector2( this.x, this.y );
  853. }
  854. };
  855. /**
  856. * @author mrdoob / http://mrdoob.com/
  857. * @author *kile / http://kile.stravaganza.org/
  858. * @author philogb / http://blog.thejit.org/
  859. * @author mikael emtinger / http://gomo.se/
  860. * @author egraether / http://egraether.com/
  861. * @author WestLangley / http://github.com/WestLangley
  862. */
  863. THREE.Vector3 = function ( x, y, z ) {
  864. this.x = x || 0;
  865. this.y = y || 0;
  866. this.z = z || 0;
  867. };
  868. THREE.Vector3.prototype = {
  869. constructor: THREE.Vector3,
  870. set: function ( x, y, z ) {
  871. this.x = x;
  872. this.y = y;
  873. this.z = z;
  874. return this;
  875. },
  876. setX: function ( x ) {
  877. this.x = x;
  878. return this;
  879. },
  880. setY: function ( y ) {
  881. this.y = y;
  882. return this;
  883. },
  884. setZ: function ( z ) {
  885. this.z = z;
  886. return this;
  887. },
  888. setComponent: function ( index, value ) {
  889. switch ( index ) {
  890. case 0: this.x = value; break;
  891. case 1: this.y = value; break;
  892. case 2: this.z = value; break;
  893. default: throw new Error( "index is out of range: " + index );
  894. }
  895. },
  896. getComponent: function ( index ) {
  897. switch ( index ) {
  898. case 0: return this.x;
  899. case 1: return this.y;
  900. case 2: return this.z;
  901. default: throw new Error( "index is out of range: " + index );
  902. }
  903. },
  904. copy: function ( v ) {
  905. this.x = v.x;
  906. this.y = v.y;
  907. this.z = v.z;
  908. return this;
  909. },
  910. add: function ( v, w ) {
  911. if ( w !== undefined ) {
  912. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  913. return this.addVectors( v, w );
  914. }
  915. this.x += v.x;
  916. this.y += v.y;
  917. this.z += v.z;
  918. return this;
  919. },
  920. addScalar: function ( s ) {
  921. this.x += s;
  922. this.y += s;
  923. this.z += s;
  924. return this;
  925. },
  926. addVectors: function ( a, b ) {
  927. this.x = a.x + b.x;
  928. this.y = a.y + b.y;
  929. this.z = a.z + b.z;
  930. return this;
  931. },
  932. sub: function ( v, w ) {
  933. if ( w !== undefined ) {
  934. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  935. return this.subVectors( v, w );
  936. }
  937. this.x -= v.x;
  938. this.y -= v.y;
  939. this.z -= v.z;
  940. return this;
  941. },
  942. subVectors: function ( a, b ) {
  943. this.x = a.x - b.x;
  944. this.y = a.y - b.y;
  945. this.z = a.z - b.z;
  946. return this;
  947. },
  948. multiply: function ( v, w ) {
  949. if ( w !== undefined ) {
  950. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  951. return this.multiplyVectors( v, w );
  952. }
  953. this.x *= v.x;
  954. this.y *= v.y;
  955. this.z *= v.z;
  956. return this;
  957. },
  958. multiplyScalar: function ( scalar ) {
  959. this.x *= scalar;
  960. this.y *= scalar;
  961. this.z *= scalar;
  962. return this;
  963. },
  964. multiplyVectors: function ( a, b ) {
  965. this.x = a.x * b.x;
  966. this.y = a.y * b.y;
  967. this.z = a.z * b.z;
  968. return this;
  969. },
  970. applyMatrix3: function ( m ) {
  971. var x = this.x;
  972. var y = this.y;
  973. var z = this.z;
  974. var e = m.elements;
  975. this.x = e[0] * x + e[3] * y + e[6] * z;
  976. this.y = e[1] * x + e[4] * y + e[7] * z;
  977. this.z = e[2] * x + e[5] * y + e[8] * z;
  978. return this;
  979. },
  980. applyMatrix4: function ( m ) {
  981. // input: THREE.Matrix4 affine matrix
  982. var x = this.x, y = this.y, z = this.z;
  983. var e = m.elements;
  984. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  985. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  986. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  987. return this;
  988. },
  989. applyProjection: function ( m ) {
  990. // input: THREE.Matrix4 projection matrix
  991. var x = this.x, y = this.y, z = this.z;
  992. var e = m.elements;
  993. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  994. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  995. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  996. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  997. return this;
  998. },
  999. applyQuaternion: function ( q ) {
  1000. var x = this.x;
  1001. var y = this.y;
  1002. var z = this.z;
  1003. var qx = q.x;
  1004. var qy = q.y;
  1005. var qz = q.z;
  1006. var qw = q.w;
  1007. // calculate quat * vector
  1008. var ix = qw * x + qy * z - qz * y;
  1009. var iy = qw * y + qz * x - qx * z;
  1010. var iz = qw * z + qx * y - qy * x;
  1011. var iw = -qx * x - qy * y - qz * z;
  1012. // calculate result * inverse quat
  1013. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1014. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1015. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1016. return this;
  1017. },
  1018. transformDirection: function ( m ) {
  1019. // input: THREE.Matrix4 affine matrix
  1020. // vector interpreted as a direction
  1021. var x = this.x, y = this.y, z = this.z;
  1022. var e = m.elements;
  1023. this.x = e[0] * x + e[4] * y + e[8] * z;
  1024. this.y = e[1] * x + e[5] * y + e[9] * z;
  1025. this.z = e[2] * x + e[6] * y + e[10] * z;
  1026. this.normalize();
  1027. return this;
  1028. },
  1029. divide: function ( v ) {
  1030. this.x /= v.x;
  1031. this.y /= v.y;
  1032. this.z /= v.z;
  1033. return this;
  1034. },
  1035. divideScalar: function ( scalar ) {
  1036. if ( scalar !== 0 ) {
  1037. var invScalar = 1 / scalar;
  1038. this.x *= invScalar;
  1039. this.y *= invScalar;
  1040. this.z *= invScalar;
  1041. } else {
  1042. this.x = 0;
  1043. this.y = 0;
  1044. this.z = 0;
  1045. }
  1046. return this;
  1047. },
  1048. min: function ( v ) {
  1049. if ( this.x > v.x ) {
  1050. this.x = v.x;
  1051. }
  1052. if ( this.y > v.y ) {
  1053. this.y = v.y;
  1054. }
  1055. if ( this.z > v.z ) {
  1056. this.z = v.z;
  1057. }
  1058. return this;
  1059. },
  1060. max: function ( v ) {
  1061. if ( this.x < v.x ) {
  1062. this.x = v.x;
  1063. }
  1064. if ( this.y < v.y ) {
  1065. this.y = v.y;
  1066. }
  1067. if ( this.z < v.z ) {
  1068. this.z = v.z;
  1069. }
  1070. return this;
  1071. },
  1072. clamp: function ( min, max ) {
  1073. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1074. if ( this.x < min.x ) {
  1075. this.x = min.x;
  1076. } else if ( this.x > max.x ) {
  1077. this.x = max.x;
  1078. }
  1079. if ( this.y < min.y ) {
  1080. this.y = min.y;
  1081. } else if ( this.y > max.y ) {
  1082. this.y = max.y;
  1083. }
  1084. if ( this.z < min.z ) {
  1085. this.z = min.z;
  1086. } else if ( this.z > max.z ) {
  1087. this.z = max.z;
  1088. }
  1089. return this;
  1090. },
  1091. negate: function () {
  1092. return this.multiplyScalar( - 1 );
  1093. },
  1094. dot: function ( v ) {
  1095. return this.x * v.x + this.y * v.y + this.z * v.z;
  1096. },
  1097. lengthSq: function () {
  1098. return this.x * this.x + this.y * this.y + this.z * this.z;
  1099. },
  1100. length: function () {
  1101. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1102. },
  1103. lengthManhattan: function () {
  1104. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1105. },
  1106. normalize: function () {
  1107. return this.divideScalar( this.length() );
  1108. },
  1109. setLength: function ( l ) {
  1110. var oldLength = this.length();
  1111. if ( oldLength !== 0 && l !== oldLength ) {
  1112. this.multiplyScalar( l / oldLength );
  1113. }
  1114. return this;
  1115. },
  1116. lerp: function ( v, alpha ) {
  1117. this.x += ( v.x - this.x ) * alpha;
  1118. this.y += ( v.y - this.y ) * alpha;
  1119. this.z += ( v.z - this.z ) * alpha;
  1120. return this;
  1121. },
  1122. cross: function ( v, w ) {
  1123. if ( w !== undefined ) {
  1124. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1125. return this.crossVectors( v, w );
  1126. }
  1127. var x = this.x, y = this.y, z = this.z;
  1128. this.x = y * v.z - z * v.y;
  1129. this.y = z * v.x - x * v.z;
  1130. this.z = x * v.y - y * v.x;
  1131. return this;
  1132. },
  1133. crossVectors: function ( a, b ) {
  1134. var ax = a.x, ay = a.y, az = a.z;
  1135. var bx = b.x, by = b.y, bz = b.z;
  1136. this.x = ay * bz - az * by;
  1137. this.y = az * bx - ax * bz;
  1138. this.z = ax * by - ay * bx;
  1139. return this;
  1140. },
  1141. angleTo: function ( v ) {
  1142. var theta = this.dot( v ) / ( this.length() * v.length() );
  1143. // clamp, to handle numerical problems
  1144. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1145. },
  1146. distanceTo: function ( v ) {
  1147. return Math.sqrt( this.distanceToSquared( v ) );
  1148. },
  1149. distanceToSquared: function ( v ) {
  1150. var dx = this.x - v.x;
  1151. var dy = this.y - v.y;
  1152. var dz = this.z - v.z;
  1153. return dx * dx + dy * dy + dz * dz;
  1154. },
  1155. setEulerFromRotationMatrix: function ( m, order ) {
  1156. console.error( "REMOVED: Vector3\'s setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code.");
  1157. },
  1158. setEulerFromQuaternion: function ( q, order ) {
  1159. console.error( "REMOVED: Vector3\'s setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code.");
  1160. },
  1161. getPositionFromMatrix: function ( m ) {
  1162. this.x = m.elements[12];
  1163. this.y = m.elements[13];
  1164. this.z = m.elements[14];
  1165. return this;
  1166. },
  1167. getScaleFromMatrix: function ( m ) {
  1168. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  1169. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  1170. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  1171. this.x = sx;
  1172. this.y = sy;
  1173. this.z = sz;
  1174. return this;
  1175. },
  1176. getColumnFromMatrix: function ( index, matrix ) {
  1177. var offset = index * 4;
  1178. var me = matrix.elements;
  1179. this.x = me[ offset ];
  1180. this.y = me[ offset + 1 ];
  1181. this.z = me[ offset + 2 ];
  1182. return this;
  1183. },
  1184. equals: function ( v ) {
  1185. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1186. },
  1187. fromArray: function ( array ) {
  1188. this.x = array[ 0 ];
  1189. this.y = array[ 1 ];
  1190. this.z = array[ 2 ];
  1191. return this;
  1192. },
  1193. toArray: function () {
  1194. return [ this.x, this.y, this.z ];
  1195. },
  1196. clone: function () {
  1197. return new THREE.Vector3( this.x, this.y, this.z );
  1198. }
  1199. };
  1200. THREE.extend( THREE.Vector3.prototype, {
  1201. applyEuler: function () {
  1202. var q1 = new THREE.Quaternion();
  1203. return function ( rotation ) {
  1204. if( typeof rotation['order'] === undefined ) {
  1205. console.error( 'ERROR: Vector3\'s .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  1206. }
  1207. var quaternion = q1.setFromEuler( rotation );
  1208. this.applyQuaternion( quaternion );
  1209. return this;
  1210. };
  1211. }(),
  1212. applyAxisAngle: function () {
  1213. var q1 = new THREE.Quaternion();
  1214. return function ( axis, angle ) {
  1215. var quaternion = q1.setFromAxisAngle( axis, angle );
  1216. this.applyQuaternion( quaternion );
  1217. return this;
  1218. };
  1219. }(),
  1220. projectOnVector: function () {
  1221. var v1 = new THREE.Vector3();
  1222. return function ( vector ) {
  1223. v1.copy( vector ).normalize();
  1224. var d = this.dot( v1 );
  1225. return this.copy( v1 ).multiplyScalar( d );
  1226. };
  1227. }(),
  1228. projectOnPlane: function () {
  1229. var v1 = new THREE.Vector3();
  1230. return function ( planeNormal ) {
  1231. v1.copy( this ).projectOnVector( planeNormal );
  1232. return this.sub( v1 );
  1233. }
  1234. }(),
  1235. reflect: function () {
  1236. var v1 = new THREE.Vector3();
  1237. return function ( vector ) {
  1238. v1.copy( this ).projectOnVector( vector ).multiplyScalar( 2 );
  1239. return this.subVectors( v1, this );
  1240. }
  1241. }()
  1242. } );
  1243. /**
  1244. * @author supereggbert / http://www.paulbrunt.co.uk/
  1245. * @author philogb / http://blog.thejit.org/
  1246. * @author mikael emtinger / http://gomo.se/
  1247. * @author egraether / http://egraether.com/
  1248. * @author WestLangley / http://github.com/WestLangley
  1249. */
  1250. THREE.Vector4 = function ( x, y, z, w ) {
  1251. this.x = x || 0;
  1252. this.y = y || 0;
  1253. this.z = z || 0;
  1254. this.w = ( w !== undefined ) ? w : 1;
  1255. };
  1256. THREE.Vector4.prototype = {
  1257. constructor: THREE.Vector4,
  1258. set: function ( x, y, z, w ) {
  1259. this.x = x;
  1260. this.y = y;
  1261. this.z = z;
  1262. this.w = w;
  1263. return this;
  1264. },
  1265. setX: function ( x ) {
  1266. this.x = x;
  1267. return this;
  1268. },
  1269. setY: function ( y ) {
  1270. this.y = y;
  1271. return this;
  1272. },
  1273. setZ: function ( z ) {
  1274. this.z = z;
  1275. return this;
  1276. },
  1277. setW: function ( w ) {
  1278. this.w = w;
  1279. return this;
  1280. },
  1281. setComponent: function ( index, value ) {
  1282. switch ( index ) {
  1283. case 0: this.x = value; break;
  1284. case 1: this.y = value; break;
  1285. case 2: this.z = value; break;
  1286. case 3: this.w = value; break;
  1287. default: throw new Error( "index is out of range: " + index );
  1288. }
  1289. },
  1290. getComponent: function ( index ) {
  1291. switch ( index ) {
  1292. case 0: return this.x;
  1293. case 1: return this.y;
  1294. case 2: return this.z;
  1295. case 3: return this.w;
  1296. default: throw new Error( "index is out of range: " + index );
  1297. }
  1298. },
  1299. copy: function ( v ) {
  1300. this.x = v.x;
  1301. this.y = v.y;
  1302. this.z = v.z;
  1303. this.w = ( v.w !== undefined ) ? v.w : 1;
  1304. return this;
  1305. },
  1306. add: function ( v, w ) {
  1307. if ( w !== undefined ) {
  1308. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1309. return this.addVectors( v, w );
  1310. }
  1311. this.x += v.x;
  1312. this.y += v.y;
  1313. this.z += v.z;
  1314. this.w += v.w;
  1315. return this;
  1316. },
  1317. addScalar: function ( s ) {
  1318. this.x += s;
  1319. this.y += s;
  1320. this.z += s;
  1321. this.w += s;
  1322. return this;
  1323. },
  1324. addVectors: function ( a, b ) {
  1325. this.x = a.x + b.x;
  1326. this.y = a.y + b.y;
  1327. this.z = a.z + b.z;
  1328. this.w = a.w + b.w;
  1329. return this;
  1330. },
  1331. sub: function ( v, w ) {
  1332. if ( w !== undefined ) {
  1333. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1334. return this.subVectors( v, w );
  1335. }
  1336. this.x -= v.x;
  1337. this.y -= v.y;
  1338. this.z -= v.z;
  1339. this.w -= v.w;
  1340. return this;
  1341. },
  1342. subVectors: function ( a, b ) {
  1343. this.x = a.x - b.x;
  1344. this.y = a.y - b.y;
  1345. this.z = a.z - b.z;
  1346. this.w = a.w - b.w;
  1347. return this;
  1348. },
  1349. multiplyScalar: function ( scalar ) {
  1350. this.x *= scalar;
  1351. this.y *= scalar;
  1352. this.z *= scalar;
  1353. this.w *= scalar;
  1354. return this;
  1355. },
  1356. applyMatrix4: function ( m ) {
  1357. var x = this.x;
  1358. var y = this.y;
  1359. var z = this.z;
  1360. var w = this.w;
  1361. var e = m.elements;
  1362. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1363. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1364. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1365. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1366. return this;
  1367. },
  1368. divideScalar: function ( scalar ) {
  1369. if ( scalar !== 0 ) {
  1370. var invScalar = 1 / scalar;
  1371. this.x *= invScalar;
  1372. this.y *= invScalar;
  1373. this.z *= invScalar;
  1374. this.w *= invScalar;
  1375. } else {
  1376. this.x = 0;
  1377. this.y = 0;
  1378. this.z = 0;
  1379. this.w = 1;
  1380. }
  1381. return this;
  1382. },
  1383. setAxisAngleFromQuaternion: function ( q ) {
  1384. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1385. // q is assumed to be normalized
  1386. this.w = 2 * Math.acos( q.w );
  1387. var s = Math.sqrt( 1 - q.w * q.w );
  1388. if ( s < 0.0001 ) {
  1389. this.x = 1;
  1390. this.y = 0;
  1391. this.z = 0;
  1392. } else {
  1393. this.x = q.x / s;
  1394. this.y = q.y / s;
  1395. this.z = q.z / s;
  1396. }
  1397. return this;
  1398. },
  1399. setAxisAngleFromRotationMatrix: function ( m ) {
  1400. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1401. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1402. var angle, x, y, z, // variables for result
  1403. epsilon = 0.01, // margin to allow for rounding errors
  1404. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1405. te = m.elements,
  1406. m11 = te[0], m12 = te[4], m13 = te[8],
  1407. m21 = te[1], m22 = te[5], m23 = te[9],
  1408. m31 = te[2], m32 = te[6], m33 = te[10];
  1409. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1410. && ( Math.abs( m13 - m31 ) < epsilon )
  1411. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1412. // singularity found
  1413. // first check for identity matrix which must have +1 for all terms
  1414. // in leading diagonal and zero in other terms
  1415. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1416. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1417. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1418. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1419. // this singularity is identity matrix so angle = 0
  1420. this.set( 1, 0, 0, 0 );
  1421. return this; // zero angle, arbitrary axis
  1422. }
  1423. // otherwise this singularity is angle = 180
  1424. angle = Math.PI;
  1425. var xx = ( m11 + 1 ) / 2;
  1426. var yy = ( m22 + 1 ) / 2;
  1427. var zz = ( m33 + 1 ) / 2;
  1428. var xy = ( m12 + m21 ) / 4;
  1429. var xz = ( m13 + m31 ) / 4;
  1430. var yz = ( m23 + m32 ) / 4;
  1431. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1432. if ( xx < epsilon ) {
  1433. x = 0;
  1434. y = 0.707106781;
  1435. z = 0.707106781;
  1436. } else {
  1437. x = Math.sqrt( xx );
  1438. y = xy / x;
  1439. z = xz / x;
  1440. }
  1441. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1442. if ( yy < epsilon ) {
  1443. x = 0.707106781;
  1444. y = 0;
  1445. z = 0.707106781;
  1446. } else {
  1447. y = Math.sqrt( yy );
  1448. x = xy / y;
  1449. z = yz / y;
  1450. }
  1451. } else { // m33 is the largest diagonal term so base result on this
  1452. if ( zz < epsilon ) {
  1453. x = 0.707106781;
  1454. y = 0.707106781;
  1455. z = 0;
  1456. } else {
  1457. z = Math.sqrt( zz );
  1458. x = xz / z;
  1459. y = yz / z;
  1460. }
  1461. }
  1462. this.set( x, y, z, angle );
  1463. return this; // return 180 deg rotation
  1464. }
  1465. // as we have reached here there are no singularities so we can handle normally
  1466. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1467. + ( m13 - m31 ) * ( m13 - m31 )
  1468. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1469. if ( Math.abs( s ) < 0.001 ) s = 1;
  1470. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1471. // caught by singularity test above, but I've left it in just in case
  1472. this.x = ( m32 - m23 ) / s;
  1473. this.y = ( m13 - m31 ) / s;
  1474. this.z = ( m21 - m12 ) / s;
  1475. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1476. return this;
  1477. },
  1478. min: function ( v ) {
  1479. if ( this.x > v.x ) {
  1480. this.x = v.x;
  1481. }
  1482. if ( this.y > v.y ) {
  1483. this.y = v.y;
  1484. }
  1485. if ( this.z > v.z ) {
  1486. this.z = v.z;
  1487. }
  1488. if ( this.w > v.w ) {
  1489. this.w = v.w;
  1490. }
  1491. return this;
  1492. },
  1493. max: function ( v ) {
  1494. if ( this.x < v.x ) {
  1495. this.x = v.x;
  1496. }
  1497. if ( this.y < v.y ) {
  1498. this.y = v.y;
  1499. }
  1500. if ( this.z < v.z ) {
  1501. this.z = v.z;
  1502. }
  1503. if ( this.w < v.w ) {
  1504. this.w = v.w;
  1505. }
  1506. return this;
  1507. },
  1508. clamp: function ( min, max ) {
  1509. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1510. if ( this.x < min.x ) {
  1511. this.x = min.x;
  1512. } else if ( this.x > max.x ) {
  1513. this.x = max.x;
  1514. }
  1515. if ( this.y < min.y ) {
  1516. this.y = min.y;
  1517. } else if ( this.y > max.y ) {
  1518. this.y = max.y;
  1519. }
  1520. if ( this.z < min.z ) {
  1521. this.z = min.z;
  1522. } else if ( this.z > max.z ) {
  1523. this.z = max.z;
  1524. }
  1525. if ( this.w < min.w ) {
  1526. this.w = min.w;
  1527. } else if ( this.w > max.w ) {
  1528. this.w = max.w;
  1529. }
  1530. return this;
  1531. },
  1532. negate: function() {
  1533. return this.multiplyScalar( -1 );
  1534. },
  1535. dot: function ( v ) {
  1536. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1537. },
  1538. lengthSq: function () {
  1539. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1540. },
  1541. length: function () {
  1542. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1543. },
  1544. lengthManhattan: function () {
  1545. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1546. },
  1547. normalize: function () {
  1548. return this.divideScalar( this.length() );
  1549. },
  1550. setLength: function ( l ) {
  1551. var oldLength = this.length();
  1552. if ( oldLength !== 0 && l !== oldLength ) {
  1553. this.multiplyScalar( l / oldLength );
  1554. }
  1555. return this;
  1556. },
  1557. lerp: function ( v, alpha ) {
  1558. this.x += ( v.x - this.x ) * alpha;
  1559. this.y += ( v.y - this.y ) * alpha;
  1560. this.z += ( v.z - this.z ) * alpha;
  1561. this.w += ( v.w - this.w ) * alpha;
  1562. return this;
  1563. },
  1564. equals: function ( v ) {
  1565. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1566. },
  1567. fromArray: function ( array ) {
  1568. this.x = array[ 0 ];
  1569. this.y = array[ 1 ];
  1570. this.z = array[ 2 ];
  1571. this.w = array[ 3 ];
  1572. return this;
  1573. },
  1574. toArray: function () {
  1575. return [ this.x, this.y, this.z, this.w ];
  1576. },
  1577. clone: function () {
  1578. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1579. }
  1580. };
  1581. /**
  1582. * @author mrdoob / http://mrdoob.com/
  1583. * @author WestLangley / http://github.com/WestLangley
  1584. * @author bhouston / http://exocortex.com
  1585. */
  1586. THREE.Euler = function ( x, y, z, order ) {
  1587. this._x = x || 0;
  1588. this._y = y || 0;
  1589. this._z = z || 0;
  1590. this._order = order || THREE.Euler.DefaultOrder;
  1591. };
  1592. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1593. THREE.Euler.DefaultOrder = 'XYZ';
  1594. THREE.Euler.prototype = {
  1595. constructor: THREE.Euler,
  1596. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1597. _quaternion: undefined,
  1598. _updateQuaternion: function () {
  1599. if ( this._quaternion !== undefined ) {
  1600. this._quaternion.setFromEuler( this, false );
  1601. }
  1602. },
  1603. get x () {
  1604. return this._x;
  1605. },
  1606. set x ( value ) {
  1607. this._x = value;
  1608. this._updateQuaternion();
  1609. },
  1610. get y () {
  1611. return this._y;
  1612. },
  1613. set y ( value ) {
  1614. this._y = value;
  1615. this._updateQuaternion();
  1616. },
  1617. get z () {
  1618. return this._z;
  1619. },
  1620. set z ( value ) {
  1621. this._z = value;
  1622. this._updateQuaternion();
  1623. },
  1624. get order () {
  1625. return this._order;
  1626. },
  1627. set order ( value ) {
  1628. this._order = value;
  1629. this._updateQuaternion();
  1630. },
  1631. set: function ( x, y, z, order ) {
  1632. this._x = x;
  1633. this._y = y;
  1634. this._z = z;
  1635. this._order = order || this._order;
  1636. this._updateQuaternion();
  1637. return this;
  1638. },
  1639. copy: function ( euler ) {
  1640. this._x = euler._x;
  1641. this._y = euler._y;
  1642. this._z = euler._z;
  1643. this._order = euler._order;
  1644. this._updateQuaternion();
  1645. return this;
  1646. },
  1647. setFromRotationMatrix: function ( m, order ) {
  1648. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1649. // clamp, to handle numerical problems
  1650. function clamp( x ) {
  1651. return Math.min( Math.max( x, -1 ), 1 );
  1652. }
  1653. var te = m.elements;
  1654. var m11 = te[0], m12 = te[4], m13 = te[8];
  1655. var m21 = te[1], m22 = te[5], m23 = te[9];
  1656. var m31 = te[2], m32 = te[6], m33 = te[10];
  1657. order = order || this._order;
  1658. if ( order === 'XYZ' ) {
  1659. this._y = Math.asin( clamp( m13 ) );
  1660. if ( Math.abs( m13 ) < 0.99999 ) {
  1661. this._x = Math.atan2( - m23, m33 );
  1662. this._z = Math.atan2( - m12, m11 );
  1663. } else {
  1664. this._x = Math.atan2( m32, m22 );
  1665. this._z = 0;
  1666. }
  1667. } else if ( order === 'YXZ' ) {
  1668. this._x = Math.asin( - clamp( m23 ) );
  1669. if ( Math.abs( m23 ) < 0.99999 ) {
  1670. this._y = Math.atan2( m13, m33 );
  1671. this._z = Math.atan2( m21, m22 );
  1672. } else {
  1673. this._y = Math.atan2( - m31, m11 );
  1674. this._z = 0;
  1675. }
  1676. } else if ( order === 'ZXY' ) {
  1677. this._x = Math.asin( clamp( m32 ) );
  1678. if ( Math.abs( m32 ) < 0.99999 ) {
  1679. this._y = Math.atan2( - m31, m33 );
  1680. this._z = Math.atan2( - m12, m22 );
  1681. } else {
  1682. this._y = 0;
  1683. this._z = Math.atan2( m21, m11 );
  1684. }
  1685. } else if ( order === 'ZYX' ) {
  1686. this._y = Math.asin( - clamp( m31 ) );
  1687. if ( Math.abs( m31 ) < 0.99999 ) {
  1688. this._x = Math.atan2( m32, m33 );
  1689. this._z = Math.atan2( m21, m11 );
  1690. } else {
  1691. this._x = 0;
  1692. this._z = Math.atan2( - m12, m22 );
  1693. }
  1694. } else if ( order === 'YZX' ) {
  1695. this._z = Math.asin( clamp( m21 ) );
  1696. if ( Math.abs( m21 ) < 0.99999 ) {
  1697. this._x = Math.atan2( - m23, m22 );
  1698. this._y = Math.atan2( - m31, m11 );
  1699. } else {
  1700. this._x = 0;
  1701. this._y = Math.atan2( m13, m33 );
  1702. }
  1703. } else if ( order === 'XZY' ) {
  1704. this._z = Math.asin( - clamp( m12 ) );
  1705. if ( Math.abs( m12 ) < 0.99999 ) {
  1706. this._x = Math.atan2( m32, m22 );
  1707. this._y = Math.atan2( m13, m11 );
  1708. } else {
  1709. this._x = Math.atan2( - m23, m33 );
  1710. this._y = 0;
  1711. }
  1712. } else {
  1713. console.warn( 'WARNING: Euler.setFromRotationMatrix() given unsupported order: ' + order )
  1714. }
  1715. this._order = order;
  1716. this._updateQuaternion();
  1717. return this;
  1718. },
  1719. setFromQuaternion: function ( q, order, update ) {
  1720. // q is assumed to be normalized
  1721. // clamp, to handle numerical problems
  1722. function clamp( x ) {
  1723. return Math.min( Math.max( x, -1 ), 1 );
  1724. }
  1725. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1726. var sqx = q.x * q.x;
  1727. var sqy = q.y * q.y;
  1728. var sqz = q.z * q.z;
  1729. var sqw = q.w * q.w;
  1730. order = order || this._order;
  1731. if ( order === 'XYZ' ) {
  1732. this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1733. this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1734. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1735. } else if ( order === 'YXZ' ) {
  1736. this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1737. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1738. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1739. } else if ( order === 'ZXY' ) {
  1740. this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1741. this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1742. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1743. } else if ( order === 'ZYX' ) {
  1744. this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1745. this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1746. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1747. } else if ( order === 'YZX' ) {
  1748. this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1749. this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1750. this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1751. } else if ( order === 'XZY' ) {
  1752. this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1753. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1754. this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1755. } else {
  1756. console.warn( 'WARNING: Euler.setFromQuaternion() given unsupported order: ' + order )
  1757. }
  1758. this._order = order;
  1759. if ( update !== false ) this._updateQuaternion();
  1760. return this;
  1761. },
  1762. reorder: function () {
  1763. // WARNING: this discards revolution information -bhouston
  1764. var q = new THREE.Quaternion();
  1765. return function ( newOrder ) {
  1766. q.setFromEuler( this );
  1767. this.setFromQuaternion( q, newOrder );
  1768. };
  1769. }(),
  1770. fromArray: function ( array ) {
  1771. this._x = array[ 0 ];
  1772. this._y = array[ 1 ];
  1773. this._z = array[ 2 ];
  1774. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1775. this._updateQuaternion();
  1776. return this;
  1777. },
  1778. toArray: function () {
  1779. return [ this._x, this._y, this._z, this._order ];
  1780. },
  1781. equals: function ( euler ) {
  1782. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1783. },
  1784. clone: function () {
  1785. return new THREE.Euler( this._x, this._y, this._z, this._order );
  1786. }
  1787. };
  1788. /**
  1789. * @author bhouston / http://exocortex.com
  1790. */
  1791. THREE.Line3 = function ( start, end ) {
  1792. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1793. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1794. };
  1795. THREE.Line3.prototype = {
  1796. constructor: THREE.Line3,
  1797. set: function ( start, end ) {
  1798. this.start.copy( start );
  1799. this.end.copy( end );
  1800. return this;
  1801. },
  1802. copy: function ( line ) {
  1803. this.start.copy( line.start );
  1804. this.end.copy( line.end );
  1805. return this;
  1806. },
  1807. center: function ( optionalTarget ) {
  1808. var result = optionalTarget || new THREE.Vector3();
  1809. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1810. },
  1811. delta: function ( optionalTarget ) {
  1812. var result = optionalTarget || new THREE.Vector3();
  1813. return result.subVectors( this.end, this.start );
  1814. },
  1815. distanceSq: function () {
  1816. return this.start.distanceToSquared( this.end );
  1817. },
  1818. distance: function () {
  1819. return this.start.distanceTo( this.end );
  1820. },
  1821. at: function ( t, optionalTarget ) {
  1822. var result = optionalTarget || new THREE.Vector3();
  1823. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1824. },
  1825. closestPointToPointParameter: function() {
  1826. var startP = new THREE.Vector3();
  1827. var startEnd = new THREE.Vector3();
  1828. return function ( point, clampToLine ) {
  1829. startP.subVectors( point, this.start );
  1830. startEnd.subVectors( this.end, this.start );
  1831. var startEnd2 = startEnd.dot( startEnd );
  1832. var startEnd_startP = startEnd.dot( startP );
  1833. var t = startEnd_startP / startEnd2;
  1834. if ( clampToLine ) {
  1835. t = THREE.Math.clamp( t, 0, 1 );
  1836. }
  1837. return t;
  1838. };
  1839. }(),
  1840. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1841. var t = this.closestPointToPointParameter( point, clampToLine );
  1842. var result = optionalTarget || new THREE.Vector3();
  1843. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1844. },
  1845. applyMatrix4: function ( matrix ) {
  1846. this.start.applyMatrix4( matrix );
  1847. this.end.applyMatrix4( matrix );
  1848. return this;
  1849. },
  1850. equals: function ( line ) {
  1851. return line.start.equals( this.start ) && line.end.equals( this.end );
  1852. },
  1853. clone: function () {
  1854. return new THREE.Line3().copy( this );
  1855. }
  1856. };
  1857. /**
  1858. * @author bhouston / http://exocortex.com
  1859. */
  1860. THREE.Box2 = function ( min, max ) {
  1861. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1862. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1863. };
  1864. THREE.Box2.prototype = {
  1865. constructor: THREE.Box2,
  1866. set: function ( min, max ) {
  1867. this.min.copy( min );
  1868. this.max.copy( max );
  1869. return this;
  1870. },
  1871. setFromPoints: function ( points ) {
  1872. if ( points.length > 0 ) {
  1873. var point = points[ 0 ];
  1874. this.min.copy( point );
  1875. this.max.copy( point );
  1876. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1877. point = points[ i ];
  1878. if ( point.x < this.min.x ) {
  1879. this.min.x = point.x;
  1880. } else if ( point.x > this.max.x ) {
  1881. this.max.x = point.x;
  1882. }
  1883. if ( point.y < this.min.y ) {
  1884. this.min.y = point.y;
  1885. } else if ( point.y > this.max.y ) {
  1886. this.max.y = point.y;
  1887. }
  1888. }
  1889. } else {
  1890. this.makeEmpty();
  1891. }
  1892. return this;
  1893. },
  1894. setFromCenterAndSize: function () {
  1895. var v1 = new THREE.Vector2();
  1896. return function ( center, size ) {
  1897. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1898. this.min.copy( center ).sub( halfSize );
  1899. this.max.copy( center ).add( halfSize );
  1900. return this;
  1901. };
  1902. }(),
  1903. copy: function ( box ) {
  1904. this.min.copy( box.min );
  1905. this.max.copy( box.max );
  1906. return this;
  1907. },
  1908. makeEmpty: function () {
  1909. this.min.x = this.min.y = Infinity;
  1910. this.max.x = this.max.y = -Infinity;
  1911. return this;
  1912. },
  1913. empty: function () {
  1914. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1915. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1916. },
  1917. center: function ( optionalTarget ) {
  1918. var result = optionalTarget || new THREE.Vector2();
  1919. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1920. },
  1921. size: function ( optionalTarget ) {
  1922. var result = optionalTarget || new THREE.Vector2();
  1923. return result.subVectors( this.max, this.min );
  1924. },
  1925. expandByPoint: function ( point ) {
  1926. this.min.min( point );
  1927. this.max.max( point );
  1928. return this;
  1929. },
  1930. expandByVector: function ( vector ) {
  1931. this.min.sub( vector );
  1932. this.max.add( vector );
  1933. return this;
  1934. },
  1935. expandByScalar: function ( scalar ) {
  1936. this.min.addScalar( -scalar );
  1937. this.max.addScalar( scalar );
  1938. return this;
  1939. },
  1940. containsPoint: function ( point ) {
  1941. if ( point.x < this.min.x || point.x > this.max.x ||
  1942. point.y < this.min.y || point.y > this.max.y ) {
  1943. return false;
  1944. }
  1945. return true;
  1946. },
  1947. containsBox: function ( box ) {
  1948. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1949. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1950. return true;
  1951. }
  1952. return false;
  1953. },
  1954. getParameter: function ( point ) {
  1955. // This can potentially have a divide by zero if the box
  1956. // has a size dimension of 0.
  1957. return new THREE.Vector2(
  1958. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1959. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1960. );
  1961. },
  1962. isIntersectionBox: function ( box ) {
  1963. // using 6 splitting planes to rule out intersections.
  1964. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1965. box.max.y < this.min.y || box.min.y > this.max.y ) {
  1966. return false;
  1967. }
  1968. return true;
  1969. },
  1970. clampPoint: function ( point, optionalTarget ) {
  1971. var result = optionalTarget || new THREE.Vector2();
  1972. return result.copy( point ).clamp( this.min, this.max );
  1973. },
  1974. distanceToPoint: function () {
  1975. var v1 = new THREE.Vector2();
  1976. return function ( point ) {
  1977. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1978. return clampedPoint.sub( point ).length();
  1979. };
  1980. }(),
  1981. intersect: function ( box ) {
  1982. this.min.max( box.min );
  1983. this.max.min( box.max );
  1984. return this;
  1985. },
  1986. union: function ( box ) {
  1987. this.min.min( box.min );
  1988. this.max.max( box.max );
  1989. return this;
  1990. },
  1991. translate: function ( offset ) {
  1992. this.min.add( offset );
  1993. this.max.add( offset );
  1994. return this;
  1995. },
  1996. equals: function ( box ) {
  1997. return box.min.equals( this.min ) && box.max.equals( this.max );
  1998. },
  1999. clone: function () {
  2000. return new THREE.Box2().copy( this );
  2001. }
  2002. };
  2003. /**
  2004. * @author bhouston / http://exocortex.com
  2005. * @author WestLangley / http://github.com/WestLangley
  2006. */
  2007. THREE.Box3 = function ( min, max ) {
  2008. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2009. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  2010. };
  2011. THREE.Box3.prototype = {
  2012. constructor: THREE.Box3,
  2013. set: function ( min, max ) {
  2014. this.min.copy( min );
  2015. this.max.copy( max );
  2016. return this;
  2017. },
  2018. setFromPoints: function ( points ) {
  2019. if ( points.length > 0 ) {
  2020. var point = points[ 0 ];
  2021. this.min.copy( point );
  2022. this.max.copy( point );
  2023. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2024. point = points[ i ];
  2025. if ( point.x < this.min.x ) {
  2026. this.min.x = point.x;
  2027. } else if ( point.x > this.max.x ) {
  2028. this.max.x = point.x;
  2029. }
  2030. if ( point.y < this.min.y ) {
  2031. this.min.y = point.y;
  2032. } else if ( point.y > this.max.y ) {
  2033. this.max.y = point.y;
  2034. }
  2035. if ( point.z < this.min.z ) {
  2036. this.min.z = point.z;
  2037. } else if ( point.z > this.max.z ) {
  2038. this.max.z = point.z;
  2039. }
  2040. }
  2041. } else {
  2042. this.makeEmpty();
  2043. }
  2044. return this;
  2045. },
  2046. setFromCenterAndSize: function() {
  2047. var v1 = new THREE.Vector3();
  2048. return function ( center, size ) {
  2049. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2050. this.min.copy( center ).sub( halfSize );
  2051. this.max.copy( center ).add( halfSize );
  2052. return this;
  2053. };
  2054. }(),
  2055. setFromObject: function() {
  2056. // Computes the world-axis-aligned bounding box of an object (including its children),
  2057. // accounting for both the object's, and childrens', world transforms
  2058. var v1 = new THREE.Vector3();
  2059. return function( object ) {
  2060. var scope = this;
  2061. object.updateMatrixWorld( true );
  2062. this.makeEmpty();
  2063. object.traverse( function ( node ) {
  2064. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2065. var vertices = node.geometry.vertices;
  2066. for ( var i = 0, il = vertices.length; i < il; i++ ) {
  2067. v1.copy( vertices[ i ] );
  2068. v1.applyMatrix4( node.matrixWorld );
  2069. scope.expandByPoint( v1 );
  2070. }
  2071. }
  2072. } );
  2073. return this;
  2074. };
  2075. }(),
  2076. copy: function ( box ) {
  2077. this.min.copy( box.min );
  2078. this.max.copy( box.max );
  2079. return this;
  2080. },
  2081. makeEmpty: function () {
  2082. this.min.x = this.min.y = this.min.z = Infinity;
  2083. this.max.x = this.max.y = this.max.z = -Infinity;
  2084. return this;
  2085. },
  2086. empty: function () {
  2087. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2088. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2089. },
  2090. center: function ( optionalTarget ) {
  2091. var result = optionalTarget || new THREE.Vector3();
  2092. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2093. },
  2094. size: function ( optionalTarget ) {
  2095. var result = optionalTarget || new THREE.Vector3();
  2096. return result.subVectors( this.max, this.min );
  2097. },
  2098. expandByPoint: function ( point ) {
  2099. this.min.min( point );
  2100. this.max.max( point );
  2101. return this;
  2102. },
  2103. expandByVector: function ( vector ) {
  2104. this.min.sub( vector );
  2105. this.max.add( vector );
  2106. return this;
  2107. },
  2108. expandByScalar: function ( scalar ) {
  2109. this.min.addScalar( -scalar );
  2110. this.max.addScalar( scalar );
  2111. return this;
  2112. },
  2113. containsPoint: function ( point ) {
  2114. if ( point.x < this.min.x || point.x > this.max.x ||
  2115. point.y < this.min.y || point.y > this.max.y ||
  2116. point.z < this.min.z || point.z > this.max.z ) {
  2117. return false;
  2118. }
  2119. return true;
  2120. },
  2121. containsBox: function ( box ) {
  2122. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2123. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2124. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2125. return true;
  2126. }
  2127. return false;
  2128. },
  2129. getParameter: function ( point ) {
  2130. // This can potentially have a divide by zero if the box
  2131. // has a size dimension of 0.
  2132. return new THREE.Vector3(
  2133. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2134. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2135. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2136. );
  2137. },
  2138. isIntersectionBox: function ( box ) {
  2139. // using 6 splitting planes to rule out intersections.
  2140. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2141. box.max.y < this.min.y || box.min.y > this.max.y ||
  2142. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2143. return false;
  2144. }
  2145. return true;
  2146. },
  2147. clampPoint: function ( point, optionalTarget ) {
  2148. var result = optionalTarget || new THREE.Vector3();
  2149. return result.copy( point ).clamp( this.min, this.max );
  2150. },
  2151. distanceToPoint: function() {
  2152. var v1 = new THREE.Vector3();
  2153. return function ( point ) {
  2154. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2155. return clampedPoint.sub( point ).length();
  2156. };
  2157. }(),
  2158. getBoundingSphere: function() {
  2159. var v1 = new THREE.Vector3();
  2160. return function ( optionalTarget ) {
  2161. var result = optionalTarget || new THREE.Sphere();
  2162. result.center = this.center();
  2163. result.radius = this.size( v1 ).length() * 0.5;
  2164. return result;
  2165. };
  2166. }(),
  2167. intersect: function ( box ) {
  2168. this.min.max( box.min );
  2169. this.max.min( box.max );
  2170. return this;
  2171. },
  2172. union: function ( box ) {
  2173. this.min.min( box.min );
  2174. this.max.max( box.max );
  2175. return this;
  2176. },
  2177. applyMatrix4: function() {
  2178. var points = [
  2179. new THREE.Vector3(),
  2180. new THREE.Vector3(),
  2181. new THREE.Vector3(),
  2182. new THREE.Vector3(),
  2183. new THREE.Vector3(),
  2184. new THREE.Vector3(),
  2185. new THREE.Vector3(),
  2186. new THREE.Vector3()
  2187. ];
  2188. return function ( matrix ) {
  2189. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2190. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2191. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2192. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2193. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2194. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2195. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2196. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2197. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2198. this.makeEmpty();
  2199. this.setFromPoints( points );
  2200. return this;
  2201. };
  2202. }(),
  2203. translate: function ( offset ) {
  2204. this.min.add( offset );
  2205. this.max.add( offset );
  2206. return this;
  2207. },
  2208. equals: function ( box ) {
  2209. return box.min.equals( this.min ) && box.max.equals( this.max );
  2210. },
  2211. clone: function () {
  2212. return new THREE.Box3().copy( this );
  2213. }
  2214. };
  2215. /**
  2216. * @author alteredq / http://alteredqualia.com/
  2217. * @author WestLangley / http://github.com/WestLangley
  2218. * @author bhouston / http://exocortex.com
  2219. */
  2220. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2221. this.elements = new Float32Array(9);
  2222. this.set(
  2223. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2224. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2225. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2226. );
  2227. };
  2228. THREE.Matrix3.prototype = {
  2229. constructor: THREE.Matrix3,
  2230. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2231. var te = this.elements;
  2232. te[0] = n11; te[3] = n12; te[6] = n13;
  2233. te[1] = n21; te[4] = n22; te[7] = n23;
  2234. te[2] = n31; te[5] = n32; te[8] = n33;
  2235. return this;
  2236. },
  2237. identity: function () {
  2238. this.set(
  2239. 1, 0, 0,
  2240. 0, 1, 0,
  2241. 0, 0, 1
  2242. );
  2243. return this;
  2244. },
  2245. copy: function ( m ) {
  2246. var me = m.elements;
  2247. this.set(
  2248. me[0], me[3], me[6],
  2249. me[1], me[4], me[7],
  2250. me[2], me[5], me[8]
  2251. );
  2252. return this;
  2253. },
  2254. multiplyVector3: function ( vector ) {
  2255. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2256. return vector.applyMatrix3( this );
  2257. },
  2258. multiplyVector3Array: function() {
  2259. var v1 = new THREE.Vector3();
  2260. return function ( a ) {
  2261. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2262. v1.x = a[ i ];
  2263. v1.y = a[ i + 1 ];
  2264. v1.z = a[ i + 2 ];
  2265. v1.applyMatrix3(this);
  2266. a[ i ] = v1.x;
  2267. a[ i + 1 ] = v1.y;
  2268. a[ i + 2 ] = v1.z;
  2269. }
  2270. return a;
  2271. };
  2272. }(),
  2273. multiplyScalar: function ( s ) {
  2274. var te = this.elements;
  2275. te[0] *= s; te[3] *= s; te[6] *= s;
  2276. te[1] *= s; te[4] *= s; te[7] *= s;
  2277. te[2] *= s; te[5] *= s; te[8] *= s;
  2278. return this;
  2279. },
  2280. determinant: function () {
  2281. var te = this.elements;
  2282. var a = te[0], b = te[1], c = te[2],
  2283. d = te[3], e = te[4], f = te[5],
  2284. g = te[6], h = te[7], i = te[8];
  2285. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2286. },
  2287. getInverse: function ( matrix, throwOnInvertible ) {
  2288. // input: THREE.Matrix4
  2289. // ( based on http://code.google.com/p/webgl-mjs/ )
  2290. var me = matrix.elements;
  2291. var te = this.elements;
  2292. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2293. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2294. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2295. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2296. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2297. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2298. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2299. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2300. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2301. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2302. // no inverse
  2303. if ( det === 0 ) {
  2304. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2305. if ( throwOnInvertible || false ) {
  2306. throw new Error( msg );
  2307. } else {
  2308. console.warn( msg );
  2309. }
  2310. this.identity();
  2311. return this;
  2312. }
  2313. this.multiplyScalar( 1.0 / det );
  2314. return this;
  2315. },
  2316. transpose: function () {
  2317. var tmp, m = this.elements;
  2318. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2319. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2320. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2321. return this;
  2322. },
  2323. getNormalMatrix: function ( m ) {
  2324. // input: THREE.Matrix4
  2325. this.getInverse( m ).transpose();
  2326. return this;
  2327. },
  2328. transposeIntoArray: function ( r ) {
  2329. var m = this.elements;
  2330. r[ 0 ] = m[ 0 ];
  2331. r[ 1 ] = m[ 3 ];
  2332. r[ 2 ] = m[ 6 ];
  2333. r[ 3 ] = m[ 1 ];
  2334. r[ 4 ] = m[ 4 ];
  2335. r[ 5 ] = m[ 7 ];
  2336. r[ 6 ] = m[ 2 ];
  2337. r[ 7 ] = m[ 5 ];
  2338. r[ 8 ] = m[ 8 ];
  2339. return this;
  2340. },
  2341. clone: function () {
  2342. var te = this.elements;
  2343. return new THREE.Matrix3(
  2344. te[0], te[3], te[6],
  2345. te[1], te[4], te[7],
  2346. te[2], te[5], te[8]
  2347. );
  2348. }
  2349. };
  2350. /**
  2351. * @author mrdoob / http://mrdoob.com/
  2352. * @author supereggbert / http://www.paulbrunt.co.uk/
  2353. * @author philogb / http://blog.thejit.org/
  2354. * @author jordi_ros / http://plattsoft.com
  2355. * @author D1plo1d / http://github.com/D1plo1d
  2356. * @author alteredq / http://alteredqualia.com/
  2357. * @author mikael emtinger / http://gomo.se/
  2358. * @author timknip / http://www.floorplanner.com/
  2359. * @author bhouston / http://exocortex.com
  2360. * @author WestLangley / http://github.com/WestLangley
  2361. */
  2362. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2363. this.elements = new Float32Array( 16 );
  2364. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2365. // we should not support semi specification of Matrix4, it is just weird.
  2366. var te = this.elements;
  2367. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2368. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2369. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2370. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2371. };
  2372. THREE.Matrix4.prototype = {
  2373. constructor: THREE.Matrix4,
  2374. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2375. var te = this.elements;
  2376. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2377. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2378. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2379. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2380. return this;
  2381. },
  2382. identity: function () {
  2383. this.set(
  2384. 1, 0, 0, 0,
  2385. 0, 1, 0, 0,
  2386. 0, 0, 1, 0,
  2387. 0, 0, 0, 1
  2388. );
  2389. return this;
  2390. },
  2391. copy: function ( m ) {
  2392. this.elements.set( m.elements );
  2393. return this;
  2394. },
  2395. extractPosition: function ( m ) {
  2396. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2397. return this.copyPosition( m );
  2398. },
  2399. copyPosition: function ( m ) {
  2400. var te = this.elements;
  2401. var me = m.elements;
  2402. te[12] = me[12];
  2403. te[13] = me[13];
  2404. te[14] = me[14];
  2405. return this;
  2406. },
  2407. extractRotation: function () {
  2408. var v1 = new THREE.Vector3();
  2409. return function ( m ) {
  2410. var te = this.elements;
  2411. var me = m.elements;
  2412. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2413. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2414. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2415. te[0] = me[0] * scaleX;
  2416. te[1] = me[1] * scaleX;
  2417. te[2] = me[2] * scaleX;
  2418. te[4] = me[4] * scaleY;
  2419. te[5] = me[5] * scaleY;
  2420. te[6] = me[6] * scaleY;
  2421. te[8] = me[8] * scaleZ;
  2422. te[9] = me[9] * scaleZ;
  2423. te[10] = me[10] * scaleZ;
  2424. return this;
  2425. };
  2426. }(),
  2427. makeRotationFromEuler: function ( euler ) {
  2428. if ( typeof euler['order'] === undefined ) {
  2429. console.error( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  2430. }
  2431. var te = this.elements;
  2432. var x = euler.x, y = euler.y, z = euler.z;
  2433. var a = Math.cos( x ), b = Math.sin( x );
  2434. var c = Math.cos( y ), d = Math.sin( y );
  2435. var e = Math.cos( z ), f = Math.sin( z );
  2436. if ( euler.order === undefined || euler.order === 'XYZ' ) {
  2437. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2438. te[0] = c * e;
  2439. te[4] = - c * f;
  2440. te[8] = d;
  2441. te[1] = af + be * d;
  2442. te[5] = ae - bf * d;
  2443. te[9] = - b * c;
  2444. te[2] = bf - ae * d;
  2445. te[6] = be + af * d;
  2446. te[10] = a * c;
  2447. } else if ( euler.order === 'YXZ' ) {
  2448. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2449. te[0] = ce + df * b;
  2450. te[4] = de * b - cf;
  2451. te[8] = a * d;
  2452. te[1] = a * f;
  2453. te[5] = a * e;
  2454. te[9] = - b;
  2455. te[2] = cf * b - de;
  2456. te[6] = df + ce * b;
  2457. te[10] = a * c;
  2458. } else if ( euler.order === 'ZXY' ) {
  2459. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2460. te[0] = ce - df * b;
  2461. te[4] = - a * f;
  2462. te[8] = de + cf * b;
  2463. te[1] = cf + de * b;
  2464. te[5] = a * e;
  2465. te[9] = df - ce * b;
  2466. te[2] = - a * d;
  2467. te[6] = b;
  2468. te[10] = a * c;
  2469. } else if ( euler.order === 'ZYX' ) {
  2470. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2471. te[0] = c * e;
  2472. te[4] = be * d - af;
  2473. te[8] = ae * d + bf;
  2474. te[1] = c * f;
  2475. te[5] = bf * d + ae;
  2476. te[9] = af * d - be;
  2477. te[2] = - d;
  2478. te[6] = b * c;
  2479. te[10] = a * c;
  2480. } else if ( euler.order === 'YZX' ) {
  2481. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2482. te[0] = c * e;
  2483. te[4] = bd - ac * f;
  2484. te[8] = bc * f + ad;
  2485. te[1] = f;
  2486. te[5] = a * e;
  2487. te[9] = - b * e;
  2488. te[2] = - d * e;
  2489. te[6] = ad * f + bc;
  2490. te[10] = ac - bd * f;
  2491. } else if ( euler.order === 'XZY' ) {
  2492. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2493. te[0] = c * e;
  2494. te[4] = - f;
  2495. te[8] = d * e;
  2496. te[1] = ac * f + bd;
  2497. te[5] = a * e;
  2498. te[9] = ad * f - bc;
  2499. te[2] = bc * f - ad;
  2500. te[6] = b * e;
  2501. te[10] = bd * f + ac;
  2502. }
  2503. // last column
  2504. te[3] = 0;
  2505. te[7] = 0;
  2506. te[11] = 0;
  2507. // bottom row
  2508. te[12] = 0;
  2509. te[13] = 0;
  2510. te[14] = 0;
  2511. te[15] = 1;
  2512. return this;
  2513. },
  2514. setRotationFromQuaternion: function ( q ) {
  2515. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2516. return this.makeRotationFromQuaternion( q );
  2517. },
  2518. makeRotationFromQuaternion: function ( q ) {
  2519. var te = this.elements;
  2520. var x = q.x, y = q.y, z = q.z, w = q.w;
  2521. var x2 = x + x, y2 = y + y, z2 = z + z;
  2522. var xx = x * x2, xy = x * y2, xz = x * z2;
  2523. var yy = y * y2, yz = y * z2, zz = z * z2;
  2524. var wx = w * x2, wy = w * y2, wz = w * z2;
  2525. te[0] = 1 - ( yy + zz );
  2526. te[4] = xy - wz;
  2527. te[8] = xz + wy;
  2528. te[1] = xy + wz;
  2529. te[5] = 1 - ( xx + zz );
  2530. te[9] = yz - wx;
  2531. te[2] = xz - wy;
  2532. te[6] = yz + wx;
  2533. te[10] = 1 - ( xx + yy );
  2534. // last column
  2535. te[3] = 0;
  2536. te[7] = 0;
  2537. te[11] = 0;
  2538. // bottom row
  2539. te[12] = 0;
  2540. te[13] = 0;
  2541. te[14] = 0;
  2542. te[15] = 1;
  2543. return this;
  2544. },
  2545. lookAt: function() {
  2546. var x = new THREE.Vector3();
  2547. var y = new THREE.Vector3();
  2548. var z = new THREE.Vector3();
  2549. return function ( eye, target, up ) {
  2550. var te = this.elements;
  2551. z.subVectors( eye, target ).normalize();
  2552. if ( z.length() === 0 ) {
  2553. z.z = 1;
  2554. }
  2555. x.crossVectors( up, z ).normalize();
  2556. if ( x.length() === 0 ) {
  2557. z.x += 0.0001;
  2558. x.crossVectors( up, z ).normalize();
  2559. }
  2560. y.crossVectors( z, x );
  2561. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2562. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2563. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2564. return this;
  2565. };
  2566. }(),
  2567. multiply: function ( m, n ) {
  2568. if ( n !== undefined ) {
  2569. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2570. return this.multiplyMatrices( m, n );
  2571. }
  2572. return this.multiplyMatrices( this, m );
  2573. },
  2574. multiplyMatrices: function ( a, b ) {
  2575. var ae = a.elements;
  2576. var be = b.elements;
  2577. var te = this.elements;
  2578. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2579. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2580. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2581. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2582. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2583. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2584. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2585. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2586. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2587. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2588. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2589. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2590. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2591. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2592. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2593. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2594. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2595. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2596. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2597. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2598. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2599. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2600. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2601. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2602. return this;
  2603. },
  2604. multiplyToArray: function ( a, b, r ) {
  2605. var te = this.elements;
  2606. this.multiplyMatrices( a, b );
  2607. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2608. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2609. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2610. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2611. return this;
  2612. },
  2613. multiplyScalar: function ( s ) {
  2614. var te = this.elements;
  2615. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2616. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2617. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2618. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2619. return this;
  2620. },
  2621. multiplyVector3: function ( vector ) {
  2622. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2623. return vector.applyProjection( this );
  2624. },
  2625. multiplyVector4: function ( vector ) {
  2626. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2627. return vector.applyMatrix4( this );
  2628. },
  2629. multiplyVector3Array: function() {
  2630. var v1 = new THREE.Vector3();
  2631. return function ( a ) {
  2632. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2633. v1.x = a[ i ];
  2634. v1.y = a[ i + 1 ];
  2635. v1.z = a[ i + 2 ];
  2636. v1.applyProjection( this );
  2637. a[ i ] = v1.x;
  2638. a[ i + 1 ] = v1.y;
  2639. a[ i + 2 ] = v1.z;
  2640. }
  2641. return a;
  2642. };
  2643. }(),
  2644. rotateAxis: function ( v ) {
  2645. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2646. v.transformDirection( this );
  2647. },
  2648. crossVector: function ( vector ) {
  2649. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2650. return vector.applyMatrix4( this );
  2651. },
  2652. determinant: function () {
  2653. var te = this.elements;
  2654. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2655. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2656. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2657. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2658. //TODO: make this more efficient
  2659. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2660. return (
  2661. n41 * (
  2662. +n14 * n23 * n32
  2663. -n13 * n24 * n32
  2664. -n14 * n22 * n33
  2665. +n12 * n24 * n33
  2666. +n13 * n22 * n34
  2667. -n12 * n23 * n34
  2668. ) +
  2669. n42 * (
  2670. +n11 * n23 * n34
  2671. -n11 * n24 * n33
  2672. +n14 * n21 * n33
  2673. -n13 * n21 * n34
  2674. +n13 * n24 * n31
  2675. -n14 * n23 * n31
  2676. ) +
  2677. n43 * (
  2678. +n11 * n24 * n32
  2679. -n11 * n22 * n34
  2680. -n14 * n21 * n32
  2681. +n12 * n21 * n34
  2682. +n14 * n22 * n31
  2683. -n12 * n24 * n31
  2684. ) +
  2685. n44 * (
  2686. -n13 * n22 * n31
  2687. -n11 * n23 * n32
  2688. +n11 * n22 * n33
  2689. +n13 * n21 * n32
  2690. -n12 * n21 * n33
  2691. +n12 * n23 * n31
  2692. )
  2693. );
  2694. },
  2695. transpose: function () {
  2696. var te = this.elements;
  2697. var tmp;
  2698. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2699. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2700. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2701. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2702. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2703. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2704. return this;
  2705. },
  2706. flattenToArray: function ( flat ) {
  2707. var te = this.elements;
  2708. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2709. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2710. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2711. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2712. return flat;
  2713. },
  2714. flattenToArrayOffset: function( flat, offset ) {
  2715. var te = this.elements;
  2716. flat[ offset ] = te[0];
  2717. flat[ offset + 1 ] = te[1];
  2718. flat[ offset + 2 ] = te[2];
  2719. flat[ offset + 3 ] = te[3];
  2720. flat[ offset + 4 ] = te[4];
  2721. flat[ offset + 5 ] = te[5];
  2722. flat[ offset + 6 ] = te[6];
  2723. flat[ offset + 7 ] = te[7];
  2724. flat[ offset + 8 ] = te[8];
  2725. flat[ offset + 9 ] = te[9];
  2726. flat[ offset + 10 ] = te[10];
  2727. flat[ offset + 11 ] = te[11];
  2728. flat[ offset + 12 ] = te[12];
  2729. flat[ offset + 13 ] = te[13];
  2730. flat[ offset + 14 ] = te[14];
  2731. flat[ offset + 15 ] = te[15];
  2732. return flat;
  2733. },
  2734. getPosition: function() {
  2735. var v1 = new THREE.Vector3();
  2736. return function () {
  2737. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.getPositionFromMatrix( matrix ) instead.' );
  2738. var te = this.elements;
  2739. return v1.set( te[12], te[13], te[14] );
  2740. };
  2741. }(),
  2742. setPosition: function ( v ) {
  2743. var te = this.elements;
  2744. te[12] = v.x;
  2745. te[13] = v.y;
  2746. te[14] = v.z;
  2747. return this;
  2748. },
  2749. getInverse: function ( m, throwOnInvertible ) {
  2750. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2751. var te = this.elements;
  2752. var me = m.elements;
  2753. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2754. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2755. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2756. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2757. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2758. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2759. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2760. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2761. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2762. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2763. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2764. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2765. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2766. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2767. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2768. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2769. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2770. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2771. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2772. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2773. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2774. if ( det == 0 ) {
  2775. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2776. if ( throwOnInvertible || false ) {
  2777. throw new Error( msg );
  2778. } else {
  2779. console.warn( msg );
  2780. }
  2781. this.identity();
  2782. return this;
  2783. }
  2784. this.multiplyScalar( 1 / det );
  2785. return this;
  2786. },
  2787. translate: function ( v ) {
  2788. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2789. },
  2790. rotateX: function ( angle ) {
  2791. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2792. },
  2793. rotateY: function ( angle ) {
  2794. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2795. },
  2796. rotateZ: function ( angle ) {
  2797. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2798. },
  2799. rotateByAxis: function ( axis, angle ) {
  2800. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2801. },
  2802. scale: function ( v ) {
  2803. var te = this.elements;
  2804. var x = v.x, y = v.y, z = v.z;
  2805. te[0] *= x; te[4] *= y; te[8] *= z;
  2806. te[1] *= x; te[5] *= y; te[9] *= z;
  2807. te[2] *= x; te[6] *= y; te[10] *= z;
  2808. te[3] *= x; te[7] *= y; te[11] *= z;
  2809. return this;
  2810. },
  2811. getMaxScaleOnAxis: function () {
  2812. var te = this.elements;
  2813. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2814. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2815. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2816. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2817. },
  2818. makeTranslation: function ( x, y, z ) {
  2819. this.set(
  2820. 1, 0, 0, x,
  2821. 0, 1, 0, y,
  2822. 0, 0, 1, z,
  2823. 0, 0, 0, 1
  2824. );
  2825. return this;
  2826. },
  2827. makeRotationX: function ( theta ) {
  2828. var c = Math.cos( theta ), s = Math.sin( theta );
  2829. this.set(
  2830. 1, 0, 0, 0,
  2831. 0, c, -s, 0,
  2832. 0, s, c, 0,
  2833. 0, 0, 0, 1
  2834. );
  2835. return this;
  2836. },
  2837. makeRotationY: function ( theta ) {
  2838. var c = Math.cos( theta ), s = Math.sin( theta );
  2839. this.set(
  2840. c, 0, s, 0,
  2841. 0, 1, 0, 0,
  2842. -s, 0, c, 0,
  2843. 0, 0, 0, 1
  2844. );
  2845. return this;
  2846. },
  2847. makeRotationZ: function ( theta ) {
  2848. var c = Math.cos( theta ), s = Math.sin( theta );
  2849. this.set(
  2850. c, -s, 0, 0,
  2851. s, c, 0, 0,
  2852. 0, 0, 1, 0,
  2853. 0, 0, 0, 1
  2854. );
  2855. return this;
  2856. },
  2857. makeRotationAxis: function ( axis, angle ) {
  2858. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2859. var c = Math.cos( angle );
  2860. var s = Math.sin( angle );
  2861. var t = 1 - c;
  2862. var x = axis.x, y = axis.y, z = axis.z;
  2863. var tx = t * x, ty = t * y;
  2864. this.set(
  2865. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2866. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2867. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2868. 0, 0, 0, 1
  2869. );
  2870. return this;
  2871. },
  2872. makeScale: function ( x, y, z ) {
  2873. this.set(
  2874. x, 0, 0, 0,
  2875. 0, y, 0, 0,
  2876. 0, 0, z, 0,
  2877. 0, 0, 0, 1
  2878. );
  2879. return this;
  2880. },
  2881. compose: function ( position, quaternion, scale ) {
  2882. this.makeRotationFromQuaternion( quaternion );
  2883. this.scale( scale );
  2884. this.setPosition( position );
  2885. return this;
  2886. },
  2887. decompose: function () {
  2888. var vector = new THREE.Vector3();
  2889. var matrix = new THREE.Matrix4();
  2890. return function ( position, quaternion, scale ) {
  2891. var te = this.elements;
  2892. var sx = vector.set( te[0], te[1], te[2] ).length();
  2893. var sy = vector.set( te[4], te[5], te[6] ).length();
  2894. var sz = vector.set( te[8], te[9], te[10] ).length();
  2895. position.x = te[12];
  2896. position.y = te[13];
  2897. position.z = te[14];
  2898. // scale the rotation part
  2899. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  2900. var invSX = 1 / sx;
  2901. var invSY = 1 / sy;
  2902. var invSZ = 1 / sz;
  2903. matrix.elements[0] *= invSX;
  2904. matrix.elements[1] *= invSX;
  2905. matrix.elements[2] *= invSX;
  2906. matrix.elements[4] *= invSY;
  2907. matrix.elements[5] *= invSY;
  2908. matrix.elements[6] *= invSY;
  2909. matrix.elements[8] *= invSZ;
  2910. matrix.elements[9] *= invSZ;
  2911. matrix.elements[10] *= invSZ;
  2912. quaternion.setFromRotationMatrix( matrix );
  2913. scale.x = sx;
  2914. scale.y = sy;
  2915. scale.z = sz;
  2916. return this;
  2917. };
  2918. }(),
  2919. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2920. var te = this.elements;
  2921. var x = 2 * near / ( right - left );
  2922. var y = 2 * near / ( top - bottom );
  2923. var a = ( right + left ) / ( right - left );
  2924. var b = ( top + bottom ) / ( top - bottom );
  2925. var c = - ( far + near ) / ( far - near );
  2926. var d = - 2 * far * near / ( far - near );
  2927. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2928. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2929. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2930. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2931. return this;
  2932. },
  2933. makePerspective: function ( fov, aspect, near, far ) {
  2934. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2935. var ymin = - ymax;
  2936. var xmin = ymin * aspect;
  2937. var xmax = ymax * aspect;
  2938. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2939. },
  2940. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2941. var te = this.elements;
  2942. var w = right - left;
  2943. var h = top - bottom;
  2944. var p = far - near;
  2945. var x = ( right + left ) / w;
  2946. var y = ( top + bottom ) / h;
  2947. var z = ( far + near ) / p;
  2948. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2949. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2950. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2951. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2952. return this;
  2953. },
  2954. fromArray: function ( array ) {
  2955. this.elements.set( array );
  2956. return this;
  2957. },
  2958. toArray: function () {
  2959. var te = this.elements;
  2960. return [
  2961. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  2962. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  2963. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  2964. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  2965. ];
  2966. },
  2967. clone: function () {
  2968. var te = this.elements;
  2969. return new THREE.Matrix4(
  2970. te[0], te[4], te[8], te[12],
  2971. te[1], te[5], te[9], te[13],
  2972. te[2], te[6], te[10], te[14],
  2973. te[3], te[7], te[11], te[15]
  2974. );
  2975. }
  2976. };
  2977. /**
  2978. * @author bhouston / http://exocortex.com
  2979. */
  2980. THREE.Ray = function ( origin, direction ) {
  2981. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  2982. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  2983. };
  2984. THREE.Ray.prototype = {
  2985. constructor: THREE.Ray,
  2986. set: function ( origin, direction ) {
  2987. this.origin.copy( origin );
  2988. this.direction.copy( direction );
  2989. return this;
  2990. },
  2991. copy: function ( ray ) {
  2992. this.origin.copy( ray.origin );
  2993. this.direction.copy( ray.direction );
  2994. return this;
  2995. },
  2996. at: function ( t, optionalTarget ) {
  2997. var result = optionalTarget || new THREE.Vector3();
  2998. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2999. },
  3000. recast: function () {
  3001. var v1 = new THREE.Vector3();
  3002. return function ( t ) {
  3003. this.origin.copy( this.at( t, v1 ) );
  3004. return this;
  3005. };
  3006. }(),
  3007. closestPointToPoint: function ( point, optionalTarget ) {
  3008. var result = optionalTarget || new THREE.Vector3();
  3009. result.subVectors( point, this.origin );
  3010. var directionDistance = result.dot( this.direction );
  3011. if ( directionDistance < 0 ) {
  3012. return result.copy( this.origin );
  3013. }
  3014. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3015. },
  3016. distanceToPoint: function () {
  3017. var v1 = new THREE.Vector3();
  3018. return function ( point ) {
  3019. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3020. // point behind the ray
  3021. if ( directionDistance < 0 ) {
  3022. return this.origin.distanceTo( point );
  3023. }
  3024. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3025. return v1.distanceTo( point );
  3026. };
  3027. }(),
  3028. distanceSqToSegment: function( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3029. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3030. // It returns the min distance between the ray and the segment
  3031. // defined by v0 and v1
  3032. // It can also set two optional targets :
  3033. // - The closest point on the ray
  3034. // - The closest point on the segment
  3035. var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 );
  3036. var segDir = v1.clone().sub( v0 ).normalize();
  3037. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3038. var diff = this.origin.clone().sub( segCenter );
  3039. var a01 = - this.direction.dot( segDir );
  3040. var b0 = diff.dot( this.direction );
  3041. var b1 = - diff.dot( segDir );
  3042. var c = diff.lengthSq();
  3043. var det = Math.abs( 1 - a01 * a01 );
  3044. var s0, s1, sqrDist, extDet;
  3045. if ( det >= 0 ) {
  3046. // The ray and segment are not parallel.
  3047. s0 = a01 * b1 - b0;
  3048. s1 = a01 * b0 - b1;
  3049. extDet = segExtent * det;
  3050. if ( s0 >= 0 ) {
  3051. if ( s1 >= - extDet ) {
  3052. if ( s1 <= extDet ) {
  3053. // region 0
  3054. // Minimum at interior points of ray and segment.
  3055. var invDet = 1 / det;
  3056. s0 *= invDet;
  3057. s1 *= invDet;
  3058. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3059. } else {
  3060. // region 1
  3061. s1 = segExtent;
  3062. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3063. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3064. }
  3065. } else {
  3066. // region 5
  3067. s1 = - segExtent;
  3068. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3069. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3070. }
  3071. } else {
  3072. if ( s1 <= - extDet) {
  3073. // region 4
  3074. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3075. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3076. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3077. } else if ( s1 <= extDet ) {
  3078. // region 3
  3079. s0 = 0;
  3080. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3081. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3082. } else {
  3083. // region 2
  3084. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3085. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3086. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3087. }
  3088. }
  3089. } else {
  3090. // Ray and segment are parallel.
  3091. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3092. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3093. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3094. }
  3095. if ( optionalPointOnRay ) {
  3096. optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) );
  3097. }
  3098. if ( optionalPointOnSegment ) {
  3099. optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) );
  3100. }
  3101. return sqrDist;
  3102. },
  3103. isIntersectionSphere: function ( sphere ) {
  3104. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3105. },
  3106. isIntersectionPlane: function ( plane ) {
  3107. // check if the ray lies on the plane first
  3108. var distToPoint = plane.distanceToPoint( this.origin );
  3109. if ( distToPoint === 0 ) {
  3110. return true;
  3111. }
  3112. var denominator = plane.normal.dot( this.direction );
  3113. if ( denominator * distToPoint < 0 ) {
  3114. return true
  3115. }
  3116. // ray origin is behind the plane (and is pointing behind it)
  3117. return false;
  3118. },
  3119. distanceToPlane: function ( plane ) {
  3120. var denominator = plane.normal.dot( this.direction );
  3121. if ( denominator == 0 ) {
  3122. // line is coplanar, return origin
  3123. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3124. return 0;
  3125. }
  3126. // Null is preferable to undefined since undefined means.... it is undefined
  3127. return null;
  3128. }
  3129. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3130. // Return if the ray never intersects the plane
  3131. return t >= 0 ? t : null;
  3132. },
  3133. intersectPlane: function ( plane, optionalTarget ) {
  3134. var t = this.distanceToPlane( plane );
  3135. if ( t === null ) {
  3136. return null;
  3137. }
  3138. return this.at( t, optionalTarget );
  3139. },
  3140. applyMatrix4: function ( matrix4 ) {
  3141. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3142. this.origin.applyMatrix4( matrix4 );
  3143. this.direction.sub( this.origin );
  3144. this.direction.normalize();
  3145. return this;
  3146. },
  3147. equals: function ( ray ) {
  3148. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3149. },
  3150. clone: function () {
  3151. return new THREE.Ray().copy( this );
  3152. }
  3153. };
  3154. /**
  3155. * @author bhouston / http://exocortex.com
  3156. * @author mrdoob / http://mrdoob.com/
  3157. */
  3158. THREE.Sphere = function ( center, radius ) {
  3159. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3160. this.radius = ( radius !== undefined ) ? radius : 0;
  3161. };
  3162. THREE.Sphere.prototype = {
  3163. constructor: THREE.Sphere,
  3164. set: function ( center, radius ) {
  3165. this.center.copy( center );
  3166. this.radius = radius;
  3167. return this;
  3168. },
  3169. setFromPoints: function ( points ) {
  3170. var radiusSq, maxRadiusSq = 0;
  3171. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3172. radiusSq = points[ i ].lengthSq();
  3173. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  3174. }
  3175. this.center.set( 0, 0, 0 );
  3176. this.radius = Math.sqrt( maxRadiusSq );
  3177. return this;
  3178. },
  3179. copy: function ( sphere ) {
  3180. this.center.copy( sphere.center );
  3181. this.radius = sphere.radius;
  3182. return this;
  3183. },
  3184. empty: function () {
  3185. return ( this.radius <= 0 );
  3186. },
  3187. containsPoint: function ( point ) {
  3188. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3189. },
  3190. distanceToPoint: function ( point ) {
  3191. return ( point.distanceTo( this.center ) - this.radius );
  3192. },
  3193. intersectsSphere: function ( sphere ) {
  3194. var radiusSum = this.radius + sphere.radius;
  3195. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3196. },
  3197. clampPoint: function ( point, optionalTarget ) {
  3198. var deltaLengthSq = this.center.distanceToSquared( point );
  3199. var result = optionalTarget || new THREE.Vector3();
  3200. result.copy( point );
  3201. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3202. result.sub( this.center ).normalize();
  3203. result.multiplyScalar( this.radius ).add( this.center );
  3204. }
  3205. return result;
  3206. },
  3207. getBoundingBox: function ( optionalTarget ) {
  3208. var box = optionalTarget || new THREE.Box3();
  3209. box.set( this.center, this.center );
  3210. box.expandByScalar( this.radius );
  3211. return box;
  3212. },
  3213. applyMatrix4: function ( matrix ) {
  3214. this.center.applyMatrix4( matrix );
  3215. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3216. return this;
  3217. },
  3218. translate: function ( offset ) {
  3219. this.center.add( offset );
  3220. return this;
  3221. },
  3222. equals: function ( sphere ) {
  3223. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3224. },
  3225. clone: function () {
  3226. return new THREE.Sphere().copy( this );
  3227. }
  3228. };
  3229. /**
  3230. * @author mrdoob / http://mrdoob.com/
  3231. * @author alteredq / http://alteredqualia.com/
  3232. * @author bhouston / http://exocortex.com
  3233. */
  3234. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3235. this.planes = [
  3236. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3237. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3238. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3239. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3240. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3241. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3242. ];
  3243. };
  3244. THREE.Frustum.prototype = {
  3245. constructor: THREE.Frustum,
  3246. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3247. var planes = this.planes;
  3248. planes[0].copy( p0 );
  3249. planes[1].copy( p1 );
  3250. planes[2].copy( p2 );
  3251. planes[3].copy( p3 );
  3252. planes[4].copy( p4 );
  3253. planes[5].copy( p5 );
  3254. return this;
  3255. },
  3256. copy: function ( frustum ) {
  3257. var planes = this.planes;
  3258. for( var i = 0; i < 6; i ++ ) {
  3259. planes[i].copy( frustum.planes[i] );
  3260. }
  3261. return this;
  3262. },
  3263. setFromMatrix: function ( m ) {
  3264. var planes = this.planes;
  3265. var me = m.elements;
  3266. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3267. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3268. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3269. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3270. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3271. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3272. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3273. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3274. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3275. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3276. return this;
  3277. },
  3278. intersectsObject: function () {
  3279. var center = new THREE.Vector3();
  3280. return function ( object ) {
  3281. // this method is expanded inlined for performance reasons.
  3282. var geometry = object.geometry;
  3283. var matrix = object.matrixWorld;
  3284. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3285. var negRadius = - geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  3286. center.getPositionFromMatrix( matrix );
  3287. var planes = this.planes;
  3288. for ( var i = 0; i < 6; i ++ ) {
  3289. var distance = planes[ i ].distanceToPoint( center );
  3290. if ( distance < negRadius ) {
  3291. return false;
  3292. }
  3293. }
  3294. return true;
  3295. };
  3296. }(),
  3297. intersectsSphere: function ( sphere ) {
  3298. var planes = this.planes;
  3299. var center = sphere.center;
  3300. var negRadius = -sphere.radius;
  3301. for ( var i = 0; i < 6; i ++ ) {
  3302. var distance = planes[ i ].distanceToPoint( center );
  3303. if ( distance < negRadius ) {
  3304. return false;
  3305. }
  3306. }
  3307. return true;
  3308. },
  3309. intersectsBox : function() {
  3310. var p1 = new THREE.Vector3(),
  3311. p2 = new THREE.Vector3();
  3312. return function( box ) {
  3313. var planes = this.planes;
  3314. for ( var i = 0; i < 6 ; i ++ ) {
  3315. var plane = planes[i];
  3316. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3317. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3318. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3319. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3320. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3321. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3322. var d1 = plane.distanceToPoint( p1 );
  3323. var d2 = plane.distanceToPoint( p2 );
  3324. // if both outside plane, no intersection
  3325. if ( d1 < 0 && d2 < 0 ) {
  3326. return false;
  3327. }
  3328. }
  3329. return true;
  3330. };
  3331. }(),
  3332. containsPoint: function ( point ) {
  3333. var planes = this.planes;
  3334. for ( var i = 0; i < 6; i ++ ) {
  3335. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3336. return false;
  3337. }
  3338. }
  3339. return true;
  3340. },
  3341. clone: function () {
  3342. return new THREE.Frustum().copy( this );
  3343. }
  3344. };
  3345. /**
  3346. * @author bhouston / http://exocortex.com
  3347. */
  3348. THREE.Plane = function ( normal, constant ) {
  3349. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3350. this.constant = ( constant !== undefined ) ? constant : 0;
  3351. };
  3352. THREE.Plane.prototype = {
  3353. constructor: THREE.Plane,
  3354. set: function ( normal, constant ) {
  3355. this.normal.copy( normal );
  3356. this.constant = constant;
  3357. return this;
  3358. },
  3359. setComponents: function ( x, y, z, w ) {
  3360. this.normal.set( x, y, z );
  3361. this.constant = w;
  3362. return this;
  3363. },
  3364. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3365. this.normal.copy( normal );
  3366. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3367. return this;
  3368. },
  3369. setFromCoplanarPoints: function() {
  3370. var v1 = new THREE.Vector3();
  3371. var v2 = new THREE.Vector3();
  3372. return function ( a, b, c ) {
  3373. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3374. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3375. this.setFromNormalAndCoplanarPoint( normal, a );
  3376. return this;
  3377. };
  3378. }(),
  3379. copy: function ( plane ) {
  3380. this.normal.copy( plane.normal );
  3381. this.constant = plane.constant;
  3382. return this;
  3383. },
  3384. normalize: function () {
  3385. // Note: will lead to a divide by zero if the plane is invalid.
  3386. var inverseNormalLength = 1.0 / this.normal.length();
  3387. this.normal.multiplyScalar( inverseNormalLength );
  3388. this.constant *= inverseNormalLength;
  3389. return this;
  3390. },
  3391. negate: function () {
  3392. this.constant *= -1;
  3393. this.normal.negate();
  3394. return this;
  3395. },
  3396. distanceToPoint: function ( point ) {
  3397. return this.normal.dot( point ) + this.constant;
  3398. },
  3399. distanceToSphere: function ( sphere ) {
  3400. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3401. },
  3402. projectPoint: function ( point, optionalTarget ) {
  3403. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3404. },
  3405. orthoPoint: function ( point, optionalTarget ) {
  3406. var perpendicularMagnitude = this.distanceToPoint( point );
  3407. var result = optionalTarget || new THREE.Vector3();
  3408. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3409. },
  3410. isIntersectionLine: function ( line ) {
  3411. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3412. var startSign = this.distanceToPoint( line.start );
  3413. var endSign = this.distanceToPoint( line.end );
  3414. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3415. },
  3416. intersectLine: function() {
  3417. var v1 = new THREE.Vector3();
  3418. return function ( line, optionalTarget ) {
  3419. var result = optionalTarget || new THREE.Vector3();
  3420. var direction = line.delta( v1 );
  3421. var denominator = this.normal.dot( direction );
  3422. if ( denominator == 0 ) {
  3423. // line is coplanar, return origin
  3424. if( this.distanceToPoint( line.start ) == 0 ) {
  3425. return result.copy( line.start );
  3426. }
  3427. // Unsure if this is the correct method to handle this case.
  3428. return undefined;
  3429. }
  3430. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3431. if( t < 0 || t > 1 ) {
  3432. return undefined;
  3433. }
  3434. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3435. };
  3436. }(),
  3437. coplanarPoint: function ( optionalTarget ) {
  3438. var result = optionalTarget || new THREE.Vector3();
  3439. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3440. },
  3441. applyMatrix4: function() {
  3442. var v1 = new THREE.Vector3();
  3443. var v2 = new THREE.Vector3();
  3444. return function ( matrix, optionalNormalMatrix ) {
  3445. // compute new normal based on theory here:
  3446. // http://www.songho.ca/opengl/gl_normaltransform.html
  3447. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getNormalMatrix( matrix );
  3448. var newNormal = v1.copy( this.normal ).applyMatrix3( optionalNormalMatrix );
  3449. var newCoplanarPoint = this.coplanarPoint( v2 );
  3450. newCoplanarPoint.applyMatrix4( matrix );
  3451. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3452. return this;
  3453. };
  3454. }(),
  3455. translate: function ( offset ) {
  3456. this.constant = this.constant - offset.dot( this.normal );
  3457. return this;
  3458. },
  3459. equals: function ( plane ) {
  3460. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3461. },
  3462. clone: function () {
  3463. return new THREE.Plane().copy( this );
  3464. }
  3465. };
  3466. /**
  3467. * @author alteredq / http://alteredqualia.com/
  3468. * @author mrdoob / http://mrdoob.com/
  3469. */
  3470. THREE.Math = {
  3471. PI2: Math.PI * 2,
  3472. generateUUID: function () {
  3473. // http://www.broofa.com/Tools/Math.uuid.htm
  3474. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3475. var uuid = new Array(36);
  3476. var rnd = 0, r;
  3477. return function () {
  3478. for ( var i = 0; i < 36; i ++ ) {
  3479. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3480. uuid[ i ] = '-';
  3481. } else if ( i == 14 ) {
  3482. uuid[ i ] = '4';
  3483. } else {
  3484. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3485. r = rnd & 0xf;
  3486. rnd = rnd >> 4;
  3487. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3488. }
  3489. }
  3490. return uuid.join('');
  3491. };
  3492. }(),
  3493. // Clamp value to range <a, b>
  3494. clamp: function ( x, a, b ) {
  3495. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3496. },
  3497. // Clamp value to range <a, inf)
  3498. clampBottom: function ( x, a ) {
  3499. return x < a ? a : x;
  3500. },
  3501. // Linear mapping from range <a1, a2> to range <b1, b2>
  3502. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3503. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3504. },
  3505. // http://en.wikipedia.org/wiki/Smoothstep
  3506. smoothstep: function ( x, min, max ) {
  3507. if ( x <= min ) return 0;
  3508. if ( x >= max ) return 1;
  3509. x = ( x - min )/( max - min );
  3510. return x*x*(3 - 2*x);
  3511. },
  3512. smootherstep: function ( x, min, max ) {
  3513. if ( x <= min ) return 0;
  3514. if ( x >= max ) return 1;
  3515. x = ( x - min )/( max - min );
  3516. return x*x*x*(x*(x*6 - 15) + 10);
  3517. },
  3518. // Random float from <0, 1> with 16 bits of randomness
  3519. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3520. random16: function () {
  3521. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3522. },
  3523. // Random integer from <low, high> interval
  3524. randInt: function ( low, high ) {
  3525. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3526. },
  3527. // Random float from <low, high> interval
  3528. randFloat: function ( low, high ) {
  3529. return low + Math.random() * ( high - low );
  3530. },
  3531. // Random float from <-range/2, range/2> interval
  3532. randFloatSpread: function ( range ) {
  3533. return range * ( 0.5 - Math.random() );
  3534. },
  3535. sign: function ( x ) {
  3536. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  3537. },
  3538. degToRad: function() {
  3539. var degreeToRadiansFactor = Math.PI / 180;
  3540. return function ( degrees ) {
  3541. return degrees * degreeToRadiansFactor;
  3542. };
  3543. }(),
  3544. radToDeg: function() {
  3545. var radianToDegreesFactor = 180 / Math.PI;
  3546. return function ( radians ) {
  3547. return radians * radianToDegreesFactor;
  3548. };
  3549. }()
  3550. };
  3551. /**
  3552. * Spline from Tween.js, slightly optimized (and trashed)
  3553. * http://sole.github.com/tween.js/examples/05_spline.html
  3554. *
  3555. * @author mrdoob / http://mrdoob.com/
  3556. * @author alteredq / http://alteredqualia.com/
  3557. */
  3558. THREE.Spline = function ( points ) {
  3559. this.points = points;
  3560. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3561. point, intPoint, weight, w2, w3,
  3562. pa, pb, pc, pd;
  3563. this.initFromArray = function( a ) {
  3564. this.points = [];
  3565. for ( var i = 0; i < a.length; i++ ) {
  3566. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3567. }
  3568. };
  3569. this.getPoint = function ( k ) {
  3570. point = ( this.points.length - 1 ) * k;
  3571. intPoint = Math.floor( point );
  3572. weight = point - intPoint;
  3573. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3574. c[ 1 ] = intPoint;
  3575. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3576. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3577. pa = this.points[ c[ 0 ] ];
  3578. pb = this.points[ c[ 1 ] ];
  3579. pc = this.points[ c[ 2 ] ];
  3580. pd = this.points[ c[ 3 ] ];
  3581. w2 = weight * weight;
  3582. w3 = weight * w2;
  3583. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3584. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3585. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3586. return v3;
  3587. };
  3588. this.getControlPointsArray = function () {
  3589. var i, p, l = this.points.length,
  3590. coords = [];
  3591. for ( i = 0; i < l; i ++ ) {
  3592. p = this.points[ i ];
  3593. coords[ i ] = [ p.x, p.y, p.z ];
  3594. }
  3595. return coords;
  3596. };
  3597. // approximate length by summing linear segments
  3598. this.getLength = function ( nSubDivisions ) {
  3599. var i, index, nSamples, position,
  3600. point = 0, intPoint = 0, oldIntPoint = 0,
  3601. oldPosition = new THREE.Vector3(),
  3602. tmpVec = new THREE.Vector3(),
  3603. chunkLengths = [],
  3604. totalLength = 0;
  3605. // first point has 0 length
  3606. chunkLengths[ 0 ] = 0;
  3607. if ( !nSubDivisions ) nSubDivisions = 100;
  3608. nSamples = this.points.length * nSubDivisions;
  3609. oldPosition.copy( this.points[ 0 ] );
  3610. for ( i = 1; i < nSamples; i ++ ) {
  3611. index = i / nSamples;
  3612. position = this.getPoint( index );
  3613. tmpVec.copy( position );
  3614. totalLength += tmpVec.distanceTo( oldPosition );
  3615. oldPosition.copy( position );
  3616. point = ( this.points.length - 1 ) * index;
  3617. intPoint = Math.floor( point );
  3618. if ( intPoint != oldIntPoint ) {
  3619. chunkLengths[ intPoint ] = totalLength;
  3620. oldIntPoint = intPoint;
  3621. }
  3622. }
  3623. // last point ends with total length
  3624. chunkLengths[ chunkLengths.length ] = totalLength;
  3625. return { chunks: chunkLengths, total: totalLength };
  3626. };
  3627. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3628. var i, j,
  3629. index, indexCurrent, indexNext,
  3630. linearDistance, realDistance,
  3631. sampling, position,
  3632. newpoints = [],
  3633. tmpVec = new THREE.Vector3(),
  3634. sl = this.getLength();
  3635. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3636. for ( i = 1; i < this.points.length; i++ ) {
  3637. //tmpVec.copy( this.points[ i - 1 ] );
  3638. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3639. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3640. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3641. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3642. indexNext = i / ( this.points.length - 1 );
  3643. for ( j = 1; j < sampling - 1; j++ ) {
  3644. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3645. position = this.getPoint( index );
  3646. newpoints.push( tmpVec.copy( position ).clone() );
  3647. }
  3648. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3649. }
  3650. this.points = newpoints;
  3651. };
  3652. // Catmull-Rom
  3653. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3654. var v0 = ( p2 - p0 ) * 0.5,
  3655. v1 = ( p3 - p1 ) * 0.5;
  3656. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3657. };
  3658. };
  3659. /**
  3660. * @author bhouston / http://exocortex.com
  3661. * @author mrdoob / http://mrdoob.com/
  3662. */
  3663. THREE.Triangle = function ( a, b, c ) {
  3664. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3665. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3666. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3667. };
  3668. THREE.Triangle.normal = function() {
  3669. var v0 = new THREE.Vector3();
  3670. return function ( a, b, c, optionalTarget ) {
  3671. var result = optionalTarget || new THREE.Vector3();
  3672. result.subVectors( c, b );
  3673. v0.subVectors( a, b );
  3674. result.cross( v0 );
  3675. var resultLengthSq = result.lengthSq();
  3676. if( resultLengthSq > 0 ) {
  3677. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3678. }
  3679. return result.set( 0, 0, 0 );
  3680. };
  3681. }();
  3682. // static/instance method to calculate barycoordinates
  3683. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3684. THREE.Triangle.barycoordFromPoint = function() {
  3685. var v0 = new THREE.Vector3();
  3686. var v1 = new THREE.Vector3();
  3687. var v2 = new THREE.Vector3();
  3688. return function ( point, a, b, c, optionalTarget ) {
  3689. v0.subVectors( c, a );
  3690. v1.subVectors( b, a );
  3691. v2.subVectors( point, a );
  3692. var dot00 = v0.dot( v0 );
  3693. var dot01 = v0.dot( v1 );
  3694. var dot02 = v0.dot( v2 );
  3695. var dot11 = v1.dot( v1 );
  3696. var dot12 = v1.dot( v2 );
  3697. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3698. var result = optionalTarget || new THREE.Vector3();
  3699. // colinear or singular triangle
  3700. if( denom == 0 ) {
  3701. // arbitrary location outside of triangle?
  3702. // not sure if this is the best idea, maybe should be returning undefined
  3703. return result.set( -2, -1, -1 );
  3704. }
  3705. var invDenom = 1 / denom;
  3706. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3707. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3708. // barycoordinates must always sum to 1
  3709. return result.set( 1 - u - v, v, u );
  3710. };
  3711. }();
  3712. THREE.Triangle.containsPoint = function() {
  3713. var v1 = new THREE.Vector3();
  3714. return function ( point, a, b, c ) {
  3715. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3716. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3717. };
  3718. }();
  3719. THREE.Triangle.intersectionRay = function () {
  3720. // Compute the offset origin, edges, and normal.
  3721. var diff = new THREE.Vector3();
  3722. var edge1 = new THREE.Vector3();
  3723. var edge2 = new THREE.Vector3();
  3724. var normal = new THREE.Vector3();
  3725. return function ( ray, a, b, c, backfaceCulling ) {
  3726. //from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3727. edge1.subVectors( b, a );
  3728. edge2.subVectors( c, a );
  3729. normal.crossVectors( edge1, edge2 );
  3730. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3731. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3732. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3733. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3734. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3735. var DdN = ray.direction.dot(normal);
  3736. var sign;
  3737. if ( DdN > 0 ) {
  3738. if ( backfaceCulling ) return null;
  3739. sign = 1;
  3740. } else if ( DdN < 0 ) {
  3741. sign = - 1;
  3742. DdN = - DdN;
  3743. } else return null;
  3744. diff.subVectors( ray.origin, a );
  3745. var DdQxE2 = sign * ray.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3746. // b1 < 0, no intersection
  3747. if ( DdQxE2 < 0 )
  3748. return null;
  3749. var DdE1xQ = sign * ray.direction.dot( edge1.cross( diff ) );
  3750. // b2 < 0, no intersection
  3751. if ( DdE1xQ < 0 )
  3752. return null;
  3753. // b1+b2 > 1, no intersection
  3754. if ( DdQxE2 + DdE1xQ > DdN )
  3755. return null
  3756. // Line intersects triangle, check if ray does.
  3757. var QdN = - sign * diff.dot( normal );
  3758. // t < 0, no intersection
  3759. if ( QdN < 0 )
  3760. return null
  3761. // Ray intersects triangle.
  3762. return ray.at( QdN / DdN );
  3763. }
  3764. }();
  3765. THREE.Triangle.prototype = {
  3766. constructor: THREE.Triangle,
  3767. set: function ( a, b, c ) {
  3768. this.a.copy( a );
  3769. this.b.copy( b );
  3770. this.c.copy( c );
  3771. return this;
  3772. },
  3773. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3774. this.a.copy( points[i0] );
  3775. this.b.copy( points[i1] );
  3776. this.c.copy( points[i2] );
  3777. return this;
  3778. },
  3779. copy: function ( triangle ) {
  3780. this.a.copy( triangle.a );
  3781. this.b.copy( triangle.b );
  3782. this.c.copy( triangle.c );
  3783. return this;
  3784. },
  3785. area: function() {
  3786. var v0 = new THREE.Vector3();
  3787. var v1 = new THREE.Vector3();
  3788. return function () {
  3789. v0.subVectors( this.c, this.b );
  3790. v1.subVectors( this.a, this.b );
  3791. return v0.cross( v1 ).length() * 0.5;
  3792. };
  3793. }(),
  3794. midpoint: function ( optionalTarget ) {
  3795. var result = optionalTarget || new THREE.Vector3();
  3796. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3797. },
  3798. normal: function ( optionalTarget ) {
  3799. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3800. },
  3801. plane: function ( optionalTarget ) {
  3802. var result = optionalTarget || new THREE.Plane();
  3803. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3804. },
  3805. barycoordFromPoint: function ( point, optionalTarget ) {
  3806. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3807. },
  3808. containsPoint: function ( point ) {
  3809. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3810. },
  3811. intersectionRay: function ( ray, backfaceCulling ) {
  3812. return THREE.Triangle.intersectionRay( ray, this.a, this.b, this.c, backfaceCulling );
  3813. },
  3814. equals: function ( triangle ) {
  3815. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3816. },
  3817. clone: function () {
  3818. return new THREE.Triangle().copy( this );
  3819. }
  3820. };
  3821. /**
  3822. * @author mrdoob / http://mrdoob.com/
  3823. */
  3824. THREE.Vertex = function ( v ) {
  3825. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3826. return v;
  3827. };
  3828. /**
  3829. * @author mrdoob / http://mrdoob.com/
  3830. */
  3831. THREE.UV = function ( u, v ) {
  3832. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3833. return new THREE.Vector2( u, v );
  3834. };
  3835. /**
  3836. * @author alteredq / http://alteredqualia.com/
  3837. */
  3838. THREE.Clock = function ( autoStart ) {
  3839. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3840. this.startTime = 0;
  3841. this.oldTime = 0;
  3842. this.elapsedTime = 0;
  3843. this.running = false;
  3844. };
  3845. THREE.Clock.prototype = {
  3846. constructor: THREE.Clock,
  3847. start: function () {
  3848. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  3849. ? self.performance.now()
  3850. : Date.now();
  3851. this.oldTime = this.startTime;
  3852. this.running = true;
  3853. },
  3854. stop: function () {
  3855. this.getElapsedTime();
  3856. this.running = false;
  3857. },
  3858. getElapsedTime: function () {
  3859. this.getDelta();
  3860. return this.elapsedTime;
  3861. },
  3862. getDelta: function () {
  3863. var diff = 0;
  3864. if ( this.autoStart && ! this.running ) {
  3865. this.start();
  3866. }
  3867. if ( this.running ) {
  3868. var newTime = self.performance !== undefined && self.performance.now !== undefined
  3869. ? self.performance.now()
  3870. : Date.now();
  3871. diff = 0.001 * ( newTime - this.oldTime );
  3872. this.oldTime = newTime;
  3873. this.elapsedTime += diff;
  3874. }
  3875. return diff;
  3876. }
  3877. };
  3878. /**
  3879. * https://github.com/mrdoob/eventdispatcher.js/
  3880. */
  3881. THREE.EventDispatcher = function () {}
  3882. THREE.EventDispatcher.prototype = {
  3883. constructor: THREE.EventDispatcher,
  3884. apply: function ( object ) {
  3885. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  3886. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  3887. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  3888. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  3889. },
  3890. addEventListener: function ( type, listener ) {
  3891. if ( this._listeners === undefined ) this._listeners = {};
  3892. var listeners = this._listeners;
  3893. if ( listeners[ type ] === undefined ) {
  3894. listeners[ type ] = [];
  3895. }
  3896. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3897. listeners[ type ].push( listener );
  3898. }
  3899. },
  3900. hasEventListener: function ( type, listener ) {
  3901. if ( this._listeners === undefined ) return false;
  3902. var listeners = this._listeners;
  3903. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  3904. return true;
  3905. }
  3906. return false;
  3907. },
  3908. removeEventListener: function ( type, listener ) {
  3909. if ( this._listeners === undefined ) return;
  3910. var listeners = this._listeners;
  3911. var index = listeners[ type ].indexOf( listener );
  3912. if ( index !== - 1 ) {
  3913. listeners[ type ].splice( index, 1 );
  3914. }
  3915. },
  3916. dispatchEvent: function ( event ) {
  3917. if ( this._listeners === undefined ) return;
  3918. var listeners = this._listeners;
  3919. var listenerArray = listeners[ event.type ];
  3920. if ( listenerArray !== undefined ) {
  3921. event.target = this;
  3922. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  3923. listenerArray[ i ].call( this, event );
  3924. }
  3925. }
  3926. }
  3927. };
  3928. /**
  3929. * @author mrdoob / http://mrdoob.com/
  3930. * @author bhouston / http://exocortex.com/
  3931. * @author stephomi / http://stephaneginier.com/
  3932. */
  3933. ( function ( THREE ) {
  3934. THREE.Raycaster = function ( origin, direction, near, far ) {
  3935. this.ray = new THREE.Ray( origin, direction );
  3936. // direction is assumed to be normalized (for accurate distance calculations)
  3937. this.near = near || 0;
  3938. this.far = far || Infinity;
  3939. };
  3940. var sphere = new THREE.Sphere();
  3941. var localRay = new THREE.Ray();
  3942. var facePlane = new THREE.Plane();
  3943. var intersectPoint = new THREE.Vector3();
  3944. var matrixPosition = new THREE.Vector3();
  3945. var inverseMatrix = new THREE.Matrix4();
  3946. var descSort = function ( a, b ) {
  3947. return a.distance - b.distance;
  3948. };
  3949. var intersectObject = function ( object, raycaster, intersects ) {
  3950. if ( object instanceof THREE.Particle ) {
  3951. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3952. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  3953. if ( distance > object.scale.x ) {
  3954. return intersects;
  3955. }
  3956. intersects.push( {
  3957. distance: distance,
  3958. point: object.position,
  3959. face: null,
  3960. object: object
  3961. } );
  3962. } else if ( object instanceof THREE.LOD ) {
  3963. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3964. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  3965. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  3966. } else if ( object instanceof THREE.Mesh ) {
  3967. var geometry = object.geometry;
  3968. // Checking boundingSphere distance to ray
  3969. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3970. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3971. sphere.set( matrixPosition, geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() );
  3972. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  3973. return intersects;
  3974. }
  3975. var vertices = geometry.vertices;
  3976. if ( geometry instanceof THREE.BufferGeometry ) {
  3977. var material = object.material;
  3978. if ( material === undefined ) return intersects;
  3979. if ( geometry.dynamic === false ) return intersects;
  3980. var a, b, c;
  3981. var precision = raycaster.precision;
  3982. inverseMatrix.getInverse( object.matrixWorld );
  3983. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  3984. var fl;
  3985. var indexed = false;
  3986. if ( geometry.attributes.index ) {
  3987. indexed = true;
  3988. fl = geometry.attributes.index.numItems / 3;
  3989. } else {
  3990. fl = geometry.attributes.position.numItems / 9;
  3991. }
  3992. var vA = new THREE.Vector3();
  3993. var vB = new THREE.Vector3();
  3994. var vC = new THREE.Vector3();
  3995. var offsets = geometry.offsets;
  3996. var indices = geometry.attributes.index.array;
  3997. var positions = geometry.attributes.position.array;
  3998. var offLength = geometry.offsets.length;
  3999. for ( var oi = 0; oi < offLength; ++oi ) {
  4000. var start = offsets[ oi ].start;
  4001. var count = offsets[ oi ].count;
  4002. var index = offsets[ oi ].index;
  4003. for ( var i = start, il = start + count; i < il; i += 3 ) {
  4004. if ( indexed ) {
  4005. a = index + indices[ i ];
  4006. b = index + indices[ i + 1 ];
  4007. c = index + indices[ i + 2 ];
  4008. } else {
  4009. a = index;
  4010. b = index + 1;
  4011. c = index + 2;
  4012. }
  4013. vA.set(
  4014. positions[ a * 3 ],
  4015. positions[ a * 3 + 1 ],
  4016. positions[ a * 3 + 2 ]
  4017. );
  4018. vB.set(
  4019. positions[ b * 3 ],
  4020. positions[ b * 3 + 1 ],
  4021. positions[ b * 3 + 2 ]
  4022. );
  4023. vC.set(
  4024. positions[ c * 3 ],
  4025. positions[ c * 3 + 1 ],
  4026. positions[ c * 3 + 2 ]
  4027. );
  4028. var interPoint = THREE.Triangle.intersectionRay( localRay, vA, vB, vC, material.side !== THREE.DoubleSide );
  4029. if ( !interPoint ) continue;
  4030. interPoint.applyMatrix4( object.matrixWorld );
  4031. var distance = raycaster.ray.origin.distanceTo( interPoint );
  4032. // bail if the ray is too close to the plane
  4033. if ( distance < precision ) continue;
  4034. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  4035. intersects.push( {
  4036. distance: distance,
  4037. point: interPoint,
  4038. face: null,
  4039. faceIndex: null,
  4040. object: object
  4041. } );
  4042. }
  4043. }
  4044. } else if ( geometry instanceof THREE.Geometry ) {
  4045. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4046. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  4047. var a, b, c, d;
  4048. var precision = raycaster.precision;
  4049. inverseMatrix.getInverse( object.matrixWorld );
  4050. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4051. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  4052. var face = geometry.faces[ f ];
  4053. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  4054. if ( material === undefined ) continue;
  4055. a = vertices[ face.a ];
  4056. b = vertices[ face.b ];
  4057. c = vertices[ face.c ];
  4058. var interPoint = THREE.Triangle.intersectionRay( localRay, a, b, c, material.side !== THREE.DoubleSide );
  4059. if ( !interPoint ) {
  4060. continue;
  4061. }
  4062. interPoint.applyMatrix4( object.matrixWorld );
  4063. var distance = raycaster.ray.origin.distanceTo( interPoint );
  4064. // bail if the ray is too close to the plane
  4065. if ( distance < precision ) continue;
  4066. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  4067. intersects.push( {
  4068. distance: distance,
  4069. point: interPoint,
  4070. face: face,
  4071. faceIndex: f,
  4072. object: object
  4073. } );
  4074. }
  4075. }
  4076. } else if ( object instanceof THREE.Line ) {
  4077. var precision = raycaster.linePrecision;
  4078. var precisionSq = precision * precision;
  4079. var geometry = object.geometry;
  4080. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4081. // Checking boundingSphere distance to ray
  4082. matrixPosition.getPositionFromMatrix(object.matrixWorld);
  4083. sphere.set( matrixPosition, geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() );
  4084. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4085. return intersects;
  4086. }
  4087. inverseMatrix.getInverse( object.matrixWorld );
  4088. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4089. var vertices = geometry.vertices;
  4090. var nbVertices = vertices.length;
  4091. var interSegment = new THREE.Vector3();
  4092. var interRay = new THREE.Vector3();
  4093. var step = object.type === THREE.LineStrip ? 1 : 2;
  4094. for ( var i = 0; i < nbVertices - 1; i = i + step ) {
  4095. var distSq = localRay.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  4096. if ( distSq <= precisionSq ) {
  4097. var distance = localRay.origin.distanceTo( interRay );
  4098. if ( raycaster.near <= distance && distance <= raycaster.far ) {
  4099. intersects.push( {
  4100. distance: distance,
  4101. // What do we want? intersection point on the ray or on the segment??
  4102. // point: raycaster.ray.at( distance ),
  4103. point: interSegment.clone().applyMatrix4( object.matrixWorld ),
  4104. face: null,
  4105. faceIndex: null,
  4106. object: object
  4107. } );
  4108. }
  4109. }
  4110. }
  4111. }
  4112. };
  4113. var intersectDescendants = function ( object, raycaster, intersects ) {
  4114. var descendants = object.getDescendants();
  4115. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  4116. intersectObject( descendants[ i ], raycaster, intersects );
  4117. }
  4118. };
  4119. //
  4120. THREE.Raycaster.prototype.precision = 0.0001;
  4121. THREE.Raycaster.prototype.linePrecision = 1;
  4122. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  4123. this.ray.set( origin, direction );
  4124. // direction is assumed to be normalized (for accurate distance calculations)
  4125. };
  4126. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  4127. var intersects = [];
  4128. if ( recursive === true ) {
  4129. intersectDescendants( object, this, intersects );
  4130. }
  4131. intersectObject( object, this, intersects );
  4132. intersects.sort( descSort );
  4133. return intersects;
  4134. };
  4135. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  4136. var intersects = [];
  4137. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4138. intersectObject( objects[ i ], this, intersects );
  4139. if ( recursive === true ) {
  4140. intersectDescendants( objects[ i ], this, intersects );
  4141. }
  4142. }
  4143. intersects.sort( descSort );
  4144. return intersects;
  4145. };
  4146. }( THREE ) );
  4147. /**
  4148. * @author mrdoob / http://mrdoob.com/
  4149. * @author mikael emtinger / http://gomo.se/
  4150. * @author alteredq / http://alteredqualia.com/
  4151. * @author WestLangley / http://github.com/WestLangley
  4152. */
  4153. THREE.Object3D = function () {
  4154. this.id = THREE.Object3DIdCount ++;
  4155. this.uuid = THREE.Math.generateUUID();
  4156. this.name = '';
  4157. this.parent = undefined;
  4158. this.children = [];
  4159. this.up = new THREE.Vector3( 0, 1, 0 );
  4160. this.position = new THREE.Vector3();
  4161. this.rotation = new THREE.Euler();
  4162. this.quaternion = new THREE.Quaternion();
  4163. this.scale = new THREE.Vector3( 1, 1, 1 );
  4164. // keep rotation and quaternion in sync
  4165. this.rotation._quaternion = this.quaternion;
  4166. this.quaternion._euler = this.rotation;
  4167. this.renderDepth = null;
  4168. this.rotationAutoUpdate = true;
  4169. this.matrix = new THREE.Matrix4();
  4170. this.matrixWorld = new THREE.Matrix4();
  4171. this.matrixAutoUpdate = true;
  4172. this.matrixWorldNeedsUpdate = true;
  4173. this.visible = true;
  4174. this.castShadow = false;
  4175. this.receiveShadow = false;
  4176. this.frustumCulled = true;
  4177. this.userData = {};
  4178. };
  4179. THREE.Object3D.prototype = {
  4180. constructor: THREE.Object3D,
  4181. get eulerOrder () {
  4182. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4183. return this.rotation.order;
  4184. },
  4185. set eulerOrder ( value ) {
  4186. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4187. this.rotation.order = value;
  4188. },
  4189. get useQuaternion () {
  4190. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4191. },
  4192. set useQuaternion ( value ) {
  4193. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4194. },
  4195. applyMatrix: function () {
  4196. var m1 = new THREE.Matrix4();
  4197. return function ( matrix ) {
  4198. this.matrix.multiplyMatrices( matrix, this.matrix );
  4199. this.position.getPositionFromMatrix( this.matrix );
  4200. this.scale.getScaleFromMatrix( this.matrix );
  4201. m1.extractRotation( this.matrix );
  4202. this.quaternion.setFromRotationMatrix( m1 );
  4203. }
  4204. }(),
  4205. setRotationFromAxisAngle: function ( axis, angle ) {
  4206. // assumes axis is normalized
  4207. this.quaternion.setFromAxisAngle( axis, angle );
  4208. },
  4209. setRotationFromEuler: function ( euler ) {
  4210. this.quaternion.setFromEuler( euler, true );
  4211. },
  4212. setRotationFromMatrix: function ( m ) {
  4213. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4214. this.quaternion.setFromRotationMatrix( m );
  4215. },
  4216. setRotationFromQuaternion: function ( q ) {
  4217. // assumes q is normalized
  4218. this.quaternion.copy( q );
  4219. },
  4220. rotateOnAxis: function() {
  4221. // rotate object on axis in object space
  4222. // axis is assumed to be normalized
  4223. var q1 = new THREE.Quaternion();
  4224. return function ( axis, angle ) {
  4225. q1.setFromAxisAngle( axis, angle );
  4226. this.quaternion.multiply( q1 );
  4227. return this;
  4228. }
  4229. }(),
  4230. rotateX: function () {
  4231. var v1 = new THREE.Vector3( 1, 0, 0 );
  4232. return function ( angle ) {
  4233. return this.rotateOnAxis( v1, angle );
  4234. };
  4235. }(),
  4236. rotateY: function () {
  4237. var v1 = new THREE.Vector3( 0, 1, 0 );
  4238. return function ( angle ) {
  4239. return this.rotateOnAxis( v1, angle );
  4240. };
  4241. }(),
  4242. rotateZ: function () {
  4243. var v1 = new THREE.Vector3( 0, 0, 1 );
  4244. return function ( angle ) {
  4245. return this.rotateOnAxis( v1, angle );
  4246. };
  4247. }(),
  4248. translateOnAxis: function () {
  4249. // translate object by distance along axis in object space
  4250. // axis is assumed to be normalized
  4251. var v1 = new THREE.Vector3();
  4252. return function ( axis, distance ) {
  4253. v1.copy( axis );
  4254. v1.applyQuaternion( this.quaternion );
  4255. this.position.add( v1.multiplyScalar( distance ) );
  4256. return this;
  4257. }
  4258. }(),
  4259. translate: function ( distance, axis ) {
  4260. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  4261. return this.translateOnAxis( axis, distance );
  4262. },
  4263. translateX: function () {
  4264. var v1 = new THREE.Vector3( 1, 0, 0 );
  4265. return function ( distance ) {
  4266. return this.translateOnAxis( v1, distance );
  4267. };
  4268. }(),
  4269. translateY: function () {
  4270. var v1 = new THREE.Vector3( 0, 1, 0 );
  4271. return function ( distance ) {
  4272. return this.translateOnAxis( v1, distance );
  4273. };
  4274. }(),
  4275. translateZ: function () {
  4276. var v1 = new THREE.Vector3( 0, 0, 1 );
  4277. return function ( distance ) {
  4278. return this.translateOnAxis( v1, distance );
  4279. };
  4280. }(),
  4281. localToWorld: function ( vector ) {
  4282. return vector.applyMatrix4( this.matrixWorld );
  4283. },
  4284. worldToLocal: function () {
  4285. var m1 = new THREE.Matrix4();
  4286. return function ( vector ) {
  4287. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4288. };
  4289. }(),
  4290. lookAt: function () {
  4291. // This routine does not support objects with rotated and/or translated parent(s)
  4292. var m1 = new THREE.Matrix4();
  4293. return function ( vector ) {
  4294. m1.lookAt( vector, this.position, this.up );
  4295. this.quaternion.setFromRotationMatrix( m1 );
  4296. };
  4297. }(),
  4298. add: function ( object ) {
  4299. if ( object === this ) {
  4300. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  4301. return;
  4302. }
  4303. if ( object instanceof THREE.Object3D ) {
  4304. if ( object.parent !== undefined ) {
  4305. object.parent.remove( object );
  4306. }
  4307. object.parent = this;
  4308. object.dispatchEvent( { type: 'added' } );
  4309. this.children.push( object );
  4310. // add to scene
  4311. var scene = this;
  4312. while ( scene.parent !== undefined ) {
  4313. scene = scene.parent;
  4314. }
  4315. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4316. scene.__addObject( object );
  4317. }
  4318. }
  4319. },
  4320. remove: function ( object ) {
  4321. var index = this.children.indexOf( object );
  4322. if ( index !== - 1 ) {
  4323. object.parent = undefined;
  4324. object.dispatchEvent( { type: 'removed' } );
  4325. this.children.splice( index, 1 );
  4326. // remove from scene
  4327. var scene = this;
  4328. while ( scene.parent !== undefined ) {
  4329. scene = scene.parent;
  4330. }
  4331. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4332. scene.__removeObject( object );
  4333. }
  4334. }
  4335. },
  4336. traverse: function ( callback ) {
  4337. callback( this );
  4338. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4339. this.children[ i ].traverse( callback );
  4340. }
  4341. },
  4342. getObjectById: function ( id, recursive ) {
  4343. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4344. var child = this.children[ i ];
  4345. if ( child.id === id ) {
  4346. return child;
  4347. }
  4348. if ( recursive === true ) {
  4349. child = child.getObjectById( id, recursive );
  4350. if ( child !== undefined ) {
  4351. return child;
  4352. }
  4353. }
  4354. }
  4355. return undefined;
  4356. },
  4357. getObjectByName: function ( name, recursive ) {
  4358. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4359. var child = this.children[ i ];
  4360. if ( child.name === name ) {
  4361. return child;
  4362. }
  4363. if ( recursive === true ) {
  4364. child = child.getObjectByName( name, recursive );
  4365. if ( child !== undefined ) {
  4366. return child;
  4367. }
  4368. }
  4369. }
  4370. return undefined;
  4371. },
  4372. getChildByName: function ( name, recursive ) {
  4373. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  4374. return this.getObjectByName( name, recursive );
  4375. },
  4376. getDescendants: function ( array ) {
  4377. if ( array === undefined ) array = [];
  4378. Array.prototype.push.apply( array, this.children );
  4379. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4380. this.children[ i ].getDescendants( array );
  4381. }
  4382. return array;
  4383. },
  4384. updateMatrix: function () {
  4385. this.matrix.compose( this.position, this.quaternion, this.scale );
  4386. this.matrixWorldNeedsUpdate = true;
  4387. },
  4388. updateMatrixWorld: function ( force ) {
  4389. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4390. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4391. if ( this.parent === undefined ) {
  4392. this.matrixWorld.copy( this.matrix );
  4393. } else {
  4394. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4395. }
  4396. this.matrixWorldNeedsUpdate = false;
  4397. force = true;
  4398. }
  4399. // update children
  4400. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4401. this.children[ i ].updateMatrixWorld( force );
  4402. }
  4403. },
  4404. clone: function ( object, recursive ) {
  4405. if ( object === undefined ) object = new THREE.Object3D();
  4406. if ( recursive === undefined ) recursive = true;
  4407. object.name = this.name;
  4408. object.up.copy( this.up );
  4409. object.position.copy( this.position );
  4410. object.quaternion.copy( this.quaternion );
  4411. object.scale.copy( this.scale );
  4412. object.renderDepth = this.renderDepth;
  4413. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4414. object.matrix.copy( this.matrix );
  4415. object.matrixWorld.copy( this.matrixWorld );
  4416. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4417. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4418. object.visible = this.visible;
  4419. object.castShadow = this.castShadow;
  4420. object.receiveShadow = this.receiveShadow;
  4421. object.frustumCulled = this.frustumCulled;
  4422. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4423. if ( recursive === true ) {
  4424. for ( var i = 0; i < this.children.length; i ++ ) {
  4425. var child = this.children[ i ];
  4426. object.add( child.clone() );
  4427. }
  4428. }
  4429. return object;
  4430. }
  4431. };
  4432. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4433. THREE.Object3DIdCount = 0;
  4434. /**
  4435. * @author mrdoob / http://mrdoob.com/
  4436. * @author supereggbert / http://www.paulbrunt.co.uk/
  4437. * @author julianwa / https://github.com/julianwa
  4438. */
  4439. THREE.Projector = function () {
  4440. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4441. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4442. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  4443. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4444. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  4445. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  4446. _vector3 = new THREE.Vector3(),
  4447. _vector4 = new THREE.Vector4(),
  4448. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4449. _boundingBox = new THREE.Box3(),
  4450. _points3 = new Array( 3 ),
  4451. _points4 = new Array( 4 ),
  4452. _viewMatrix = new THREE.Matrix4(),
  4453. _viewProjectionMatrix = new THREE.Matrix4(),
  4454. _modelMatrix,
  4455. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4456. _normalMatrix = new THREE.Matrix3(),
  4457. _normalViewMatrix = new THREE.Matrix3(),
  4458. _centroid = new THREE.Vector3(),
  4459. _frustum = new THREE.Frustum(),
  4460. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4461. _clippedVertex2PositionScreen = new THREE.Vector4();
  4462. this.projectVector = function ( vector, camera ) {
  4463. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4464. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4465. return vector.applyProjection( _viewProjectionMatrix );
  4466. };
  4467. this.unprojectVector = function ( vector, camera ) {
  4468. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4469. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  4470. return vector.applyProjection( _viewProjectionMatrix );
  4471. };
  4472. this.pickingRay = function ( vector, camera ) {
  4473. // set two vectors with opposing z values
  4474. vector.z = -1.0;
  4475. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4476. this.unprojectVector( vector, camera );
  4477. this.unprojectVector( end, camera );
  4478. // find direction from vector to end
  4479. end.sub( vector ).normalize();
  4480. return new THREE.Raycaster( vector, end );
  4481. };
  4482. var getObject = function ( object ) {
  4483. _object = getNextObjectInPool();
  4484. _object.id = object.id;
  4485. _object.object = object;
  4486. if ( object.renderDepth !== null ) {
  4487. _object.z = object.renderDepth;
  4488. } else {
  4489. _vector3.getPositionFromMatrix( object.matrixWorld );
  4490. _vector3.applyProjection( _viewProjectionMatrix );
  4491. _object.z = _vector3.z;
  4492. }
  4493. return _object;
  4494. };
  4495. var projectObject = function ( object ) {
  4496. if ( object.visible === false ) return;
  4497. if ( object instanceof THREE.Light ) {
  4498. _renderData.lights.push( object );
  4499. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  4500. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4501. _renderData.objects.push( getObject( object ) );
  4502. }
  4503. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  4504. _renderData.sprites.push( getObject( object ) );
  4505. }
  4506. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4507. projectObject( object.children[ i ] );
  4508. }
  4509. };
  4510. var projectGraph = function ( root, sortObjects ) {
  4511. _objectCount = 0;
  4512. _renderData.objects.length = 0;
  4513. _renderData.sprites.length = 0;
  4514. _renderData.lights.length = 0;
  4515. projectObject( root );
  4516. if ( sortObjects === true ) {
  4517. _renderData.objects.sort( painterSort );
  4518. }
  4519. };
  4520. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4521. var visible = false,
  4522. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  4523. geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  4524. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  4525. _face3Count = 0;
  4526. _lineCount = 0;
  4527. _particleCount = 0;
  4528. _renderData.elements.length = 0;
  4529. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4530. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4531. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4532. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4533. _normalViewMatrix.getNormalMatrix( _viewMatrix );
  4534. _frustum.setFromMatrix( _viewProjectionMatrix );
  4535. projectGraph( scene, sortObjects );
  4536. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4537. object = _renderData.objects[ o ].object;
  4538. _modelMatrix = object.matrixWorld;
  4539. _vertexCount = 0;
  4540. if ( object instanceof THREE.Mesh ) {
  4541. geometry = object.geometry;
  4542. vertices = geometry.vertices;
  4543. faces = geometry.faces;
  4544. faceVertexUvs = geometry.faceVertexUvs;
  4545. _normalMatrix.getNormalMatrix( _modelMatrix );
  4546. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4547. objectMaterials = isFaceMaterial === true ? object.material : null;
  4548. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  4549. _vertex = getNextVertexInPool();
  4550. _vertex.positionWorld.copy( vertices[ v ] ).applyMatrix4( _modelMatrix );
  4551. _vertex.positionScreen.copy( _vertex.positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4552. var invW = 1 / _vertex.positionScreen.w;
  4553. _vertex.positionScreen.x *= invW;
  4554. _vertex.positionScreen.y *= invW;
  4555. _vertex.positionScreen.z *= invW;
  4556. _vertex.visible = ! ( _vertex.positionScreen.x < -1 || _vertex.positionScreen.x > 1 ||
  4557. _vertex.positionScreen.y < -1 || _vertex.positionScreen.y > 1 ||
  4558. _vertex.positionScreen.z < -1 || _vertex.positionScreen.z > 1 );
  4559. }
  4560. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  4561. face = faces[ f ];
  4562. var material = isFaceMaterial === true
  4563. ? objectMaterials.materials[ face.materialIndex ]
  4564. : object.material;
  4565. if ( material === undefined ) continue;
  4566. var side = material.side;
  4567. v1 = _vertexPool[ face.a ];
  4568. v2 = _vertexPool[ face.b ];
  4569. v3 = _vertexPool[ face.c ];
  4570. _points3[ 0 ] = v1.positionScreen;
  4571. _points3[ 1 ] = v2.positionScreen;
  4572. _points3[ 2 ] = v3.positionScreen;
  4573. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4574. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4575. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) *
  4576. ( v2.positionScreen.y - v1.positionScreen.y ) -
  4577. ( v3.positionScreen.y - v1.positionScreen.y ) *
  4578. ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4579. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4580. _face = getNextFace3InPool();
  4581. _face.id = object.id;
  4582. _face.v1.copy( v1 );
  4583. _face.v2.copy( v2 );
  4584. _face.v3.copy( v3 );
  4585. } else {
  4586. continue;
  4587. }
  4588. } else {
  4589. continue;
  4590. }
  4591. _face.normalModel.copy( face.normal );
  4592. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4593. _face.normalModel.negate();
  4594. }
  4595. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4596. _face.normalModelView.copy( _face.normalModel ).applyMatrix3( _normalViewMatrix );
  4597. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4598. faceVertexNormals = face.vertexNormals;
  4599. for ( n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) {
  4600. var normalModel = _face.vertexNormalsModel[ n ];
  4601. normalModel.copy( faceVertexNormals[ n ] );
  4602. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4603. normalModel.negate();
  4604. }
  4605. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4606. var normalModelView = _face.vertexNormalsModelView[ n ];
  4607. normalModelView.copy( normalModel ).applyMatrix3( _normalViewMatrix );
  4608. }
  4609. _face.vertexNormalsLength = faceVertexNormals.length;
  4610. for ( c = 0, cl = Math.min( faceVertexUvs.length, 3 ); c < cl; c ++ ) {
  4611. uvs = faceVertexUvs[ c ][ f ];
  4612. if ( uvs === undefined ) continue;
  4613. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  4614. _face.uvs[ c ][ u ] = uvs[ u ];
  4615. }
  4616. }
  4617. _face.color = face.color;
  4618. _face.material = material;
  4619. _centroid.copy( _face.centroidModel ).applyProjection( _viewProjectionMatrix );
  4620. _face.z = _centroid.z;
  4621. _renderData.elements.push( _face );
  4622. }
  4623. } else if ( object instanceof THREE.Line ) {
  4624. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4625. vertices = object.geometry.vertices;
  4626. v1 = getNextVertexInPool();
  4627. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4628. // Handle LineStrip and LinePieces
  4629. var step = object.type === THREE.LinePieces ? 2 : 1;
  4630. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  4631. v1 = getNextVertexInPool();
  4632. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4633. if ( ( v + 1 ) % step > 0 ) continue;
  4634. v2 = _vertexPool[ _vertexCount - 2 ];
  4635. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4636. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4637. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4638. // Perform the perspective divide
  4639. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4640. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4641. _line = getNextLineInPool();
  4642. _line.id = object.id;
  4643. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4644. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4645. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4646. _line.material = object.material;
  4647. if ( object.material.vertexColors === THREE.VertexColors ) {
  4648. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  4649. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  4650. }
  4651. _renderData.elements.push( _line );
  4652. }
  4653. }
  4654. }
  4655. }
  4656. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  4657. object = _renderData.sprites[ o ].object;
  4658. _modelMatrix = object.matrixWorld;
  4659. if ( object instanceof THREE.Particle ) {
  4660. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4661. _vector4.applyMatrix4( _viewProjectionMatrix );
  4662. var invW = 1 / _vector4.w;
  4663. _vector4.z *= invW;
  4664. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  4665. _particle = getNextParticleInPool();
  4666. _particle.id = object.id;
  4667. _particle.x = _vector4.x * invW;
  4668. _particle.y = _vector4.y * invW;
  4669. _particle.z = _vector4.z;
  4670. _particle.object = object;
  4671. _particle.rotation = object.rotation.z;
  4672. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4673. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4674. _particle.material = object.material;
  4675. _renderData.elements.push( _particle );
  4676. }
  4677. }
  4678. }
  4679. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4680. return _renderData;
  4681. };
  4682. // Pools
  4683. function getNextObjectInPool() {
  4684. if ( _objectCount === _objectPoolLength ) {
  4685. var object = new THREE.RenderableObject();
  4686. _objectPool.push( object );
  4687. _objectPoolLength ++;
  4688. _objectCount ++;
  4689. return object;
  4690. }
  4691. return _objectPool[ _objectCount ++ ];
  4692. }
  4693. function getNextVertexInPool() {
  4694. if ( _vertexCount === _vertexPoolLength ) {
  4695. var vertex = new THREE.RenderableVertex();
  4696. _vertexPool.push( vertex );
  4697. _vertexPoolLength ++;
  4698. _vertexCount ++;
  4699. return vertex;
  4700. }
  4701. return _vertexPool[ _vertexCount ++ ];
  4702. }
  4703. function getNextFace3InPool() {
  4704. if ( _face3Count === _face3PoolLength ) {
  4705. var face = new THREE.RenderableFace3();
  4706. _face3Pool.push( face );
  4707. _face3PoolLength ++;
  4708. _face3Count ++;
  4709. return face;
  4710. }
  4711. return _face3Pool[ _face3Count ++ ];
  4712. }
  4713. function getNextLineInPool() {
  4714. if ( _lineCount === _linePoolLength ) {
  4715. var line = new THREE.RenderableLine();
  4716. _linePool.push( line );
  4717. _linePoolLength ++;
  4718. _lineCount ++
  4719. return line;
  4720. }
  4721. return _linePool[ _lineCount ++ ];
  4722. }
  4723. function getNextParticleInPool() {
  4724. if ( _particleCount === _particlePoolLength ) {
  4725. var particle = new THREE.RenderableParticle();
  4726. _particlePool.push( particle );
  4727. _particlePoolLength ++;
  4728. _particleCount ++
  4729. return particle;
  4730. }
  4731. return _particlePool[ _particleCount ++ ];
  4732. }
  4733. //
  4734. function painterSort( a, b ) {
  4735. if ( a.z !== b.z ) {
  4736. return b.z - a.z;
  4737. } else if ( a.id !== b.id ) {
  4738. return a.id - b.id;
  4739. } else {
  4740. return 0;
  4741. }
  4742. }
  4743. function clipLine( s1, s2 ) {
  4744. var alpha1 = 0, alpha2 = 1,
  4745. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4746. // Z = -1 and Z = +1, respectively.
  4747. bc1near = s1.z + s1.w,
  4748. bc2near = s2.z + s2.w,
  4749. bc1far = - s1.z + s1.w,
  4750. bc2far = - s2.z + s2.w;
  4751. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4752. // Both vertices lie entirely within all clip planes.
  4753. return true;
  4754. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4755. // Both vertices lie entirely outside one of the clip planes.
  4756. return false;
  4757. } else {
  4758. // The line segment spans at least one clip plane.
  4759. if ( bc1near < 0 ) {
  4760. // v1 lies outside the near plane, v2 inside
  4761. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4762. } else if ( bc2near < 0 ) {
  4763. // v2 lies outside the near plane, v1 inside
  4764. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4765. }
  4766. if ( bc1far < 0 ) {
  4767. // v1 lies outside the far plane, v2 inside
  4768. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4769. } else if ( bc2far < 0 ) {
  4770. // v2 lies outside the far plane, v2 inside
  4771. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4772. }
  4773. if ( alpha2 < alpha1 ) {
  4774. // The line segment spans two boundaries, but is outside both of them.
  4775. // (This can't happen when we're only clipping against just near/far but good
  4776. // to leave the check here for future usage if other clip planes are added.)
  4777. return false;
  4778. } else {
  4779. // Update the s1 and s2 vertices to match the clipped line segment.
  4780. s1.lerp( s2, alpha1 );
  4781. s2.lerp( s1, 1 - alpha2 );
  4782. return true;
  4783. }
  4784. }
  4785. }
  4786. };
  4787. /**
  4788. * @author mrdoob / http://mrdoob.com/
  4789. * @author alteredq / http://alteredqualia.com/
  4790. */
  4791. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4792. this.a = a;
  4793. this.b = b;
  4794. this.c = c;
  4795. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4796. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4797. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4798. this.vertexColors = color instanceof Array ? color : [];
  4799. this.vertexTangents = [];
  4800. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4801. this.centroid = new THREE.Vector3();
  4802. };
  4803. THREE.Face3.prototype = {
  4804. constructor: THREE.Face3,
  4805. clone: function () {
  4806. var face = new THREE.Face3( this.a, this.b, this.c );
  4807. face.normal.copy( this.normal );
  4808. face.color.copy( this.color );
  4809. face.centroid.copy( this.centroid );
  4810. face.materialIndex = this.materialIndex;
  4811. var i, il;
  4812. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4813. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4814. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4815. return face;
  4816. }
  4817. };
  4818. /**
  4819. * @author mrdoob / http://mrdoob.com/
  4820. */
  4821. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4822. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  4823. };
  4824. /**
  4825. * @author mrdoob / http://mrdoob.com/
  4826. * @author kile / http://kile.stravaganza.org/
  4827. * @author alteredq / http://alteredqualia.com/
  4828. * @author mikael emtinger / http://gomo.se/
  4829. * @author zz85 / http://www.lab4games.net/zz85/blog
  4830. * @author bhouston / http://exocortex.com
  4831. */
  4832. THREE.Geometry = function () {
  4833. this.id = THREE.GeometryIdCount ++;
  4834. this.uuid = THREE.Math.generateUUID();
  4835. this.name = '';
  4836. this.vertices = [];
  4837. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  4838. this.normals = []; // one-to-one vertex normals, used in Ribbon
  4839. this.faces = [];
  4840. this.faceVertexUvs = [[]];
  4841. this.morphTargets = [];
  4842. this.morphColors = [];
  4843. this.morphNormals = [];
  4844. this.skinWeights = [];
  4845. this.skinIndices = [];
  4846. this.lineDistances = [];
  4847. this.boundingBox = null;
  4848. this.boundingSphere = null;
  4849. this.hasTangents = false;
  4850. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4851. // update flags
  4852. this.verticesNeedUpdate = false;
  4853. this.elementsNeedUpdate = false;
  4854. this.uvsNeedUpdate = false;
  4855. this.normalsNeedUpdate = false;
  4856. this.tangentsNeedUpdate = false;
  4857. this.colorsNeedUpdate = false;
  4858. this.lineDistancesNeedUpdate = false;
  4859. this.buffersNeedUpdate = false;
  4860. };
  4861. THREE.Geometry.prototype = {
  4862. constructor: THREE.Geometry,
  4863. applyMatrix: function ( matrix ) {
  4864. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  4865. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4866. var vertex = this.vertices[ i ];
  4867. vertex.applyMatrix4( matrix );
  4868. }
  4869. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4870. var face = this.faces[ i ];
  4871. face.normal.applyMatrix3( normalMatrix ).normalize();
  4872. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4873. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4874. }
  4875. face.centroid.applyMatrix4( matrix );
  4876. }
  4877. if ( this.boundingBox instanceof THREE.Box3 ) {
  4878. this.computeBoundingBox();
  4879. }
  4880. if ( this.boundingSphere instanceof THREE.Sphere ) {
  4881. this.computeBoundingSphere();
  4882. }
  4883. },
  4884. computeCentroids: function () {
  4885. var f, fl, face;
  4886. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4887. face = this.faces[ f ];
  4888. face.centroid.set( 0, 0, 0 );
  4889. face.centroid.add( this.vertices[ face.a ] );
  4890. face.centroid.add( this.vertices[ face.b ] );
  4891. face.centroid.add( this.vertices[ face.c ] );
  4892. face.centroid.divideScalar( 3 );
  4893. }
  4894. },
  4895. computeFaceNormals: function () {
  4896. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  4897. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4898. var face = this.faces[ f ];
  4899. var vA = this.vertices[ face.a ];
  4900. var vB = this.vertices[ face.b ];
  4901. var vC = this.vertices[ face.c ];
  4902. cb.subVectors( vC, vB );
  4903. ab.subVectors( vA, vB );
  4904. cb.cross( ab );
  4905. cb.normalize();
  4906. face.normal.copy( cb );
  4907. }
  4908. },
  4909. computeVertexNormals: function ( areaWeighted ) {
  4910. var v, vl, f, fl, face, vertices;
  4911. // create internal buffers for reuse when calling this method repeatedly
  4912. // (otherwise memory allocation / deallocation every frame is big resource hog)
  4913. if ( this.__tmpVertices === undefined ) {
  4914. this.__tmpVertices = new Array( this.vertices.length );
  4915. vertices = this.__tmpVertices;
  4916. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4917. vertices[ v ] = new THREE.Vector3();
  4918. }
  4919. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4920. face = this.faces[ f ];
  4921. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4922. }
  4923. } else {
  4924. vertices = this.__tmpVertices;
  4925. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4926. vertices[ v ].set( 0, 0, 0 );
  4927. }
  4928. }
  4929. if ( areaWeighted ) {
  4930. // vertex normals weighted by triangle areas
  4931. // http://www.iquilezles.org/www/articles/normals/normals.htm
  4932. var vA, vB, vC, vD;
  4933. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  4934. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  4935. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4936. face = this.faces[ f ];
  4937. vA = this.vertices[ face.a ];
  4938. vB = this.vertices[ face.b ];
  4939. vC = this.vertices[ face.c ];
  4940. cb.subVectors( vC, vB );
  4941. ab.subVectors( vA, vB );
  4942. cb.cross( ab );
  4943. vertices[ face.a ].add( cb );
  4944. vertices[ face.b ].add( cb );
  4945. vertices[ face.c ].add( cb );
  4946. }
  4947. } else {
  4948. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4949. face = this.faces[ f ];
  4950. vertices[ face.a ].add( face.normal );
  4951. vertices[ face.b ].add( face.normal );
  4952. vertices[ face.c ].add( face.normal );
  4953. }
  4954. }
  4955. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4956. vertices[ v ].normalize();
  4957. }
  4958. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4959. face = this.faces[ f ];
  4960. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4961. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4962. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4963. }
  4964. },
  4965. computeMorphNormals: function () {
  4966. var i, il, f, fl, face;
  4967. // save original normals
  4968. // - create temp variables on first access
  4969. // otherwise just copy (for faster repeated calls)
  4970. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4971. face = this.faces[ f ];
  4972. if ( ! face.__originalFaceNormal ) {
  4973. face.__originalFaceNormal = face.normal.clone();
  4974. } else {
  4975. face.__originalFaceNormal.copy( face.normal );
  4976. }
  4977. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  4978. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  4979. if ( ! face.__originalVertexNormals[ i ] ) {
  4980. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  4981. } else {
  4982. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  4983. }
  4984. }
  4985. }
  4986. // use temp geometry to compute face and vertex normals for each morph
  4987. var tmpGeo = new THREE.Geometry();
  4988. tmpGeo.faces = this.faces;
  4989. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  4990. // create on first access
  4991. if ( ! this.morphNormals[ i ] ) {
  4992. this.morphNormals[ i ] = {};
  4993. this.morphNormals[ i ].faceNormals = [];
  4994. this.morphNormals[ i ].vertexNormals = [];
  4995. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  4996. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  4997. var faceNormal, vertexNormals;
  4998. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4999. face = this.faces[ f ];
  5000. faceNormal = new THREE.Vector3();
  5001. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5002. dstNormalsFace.push( faceNormal );
  5003. dstNormalsVertex.push( vertexNormals );
  5004. }
  5005. }
  5006. var morphNormals = this.morphNormals[ i ];
  5007. // set vertices to morph target
  5008. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5009. // compute morph normals
  5010. tmpGeo.computeFaceNormals();
  5011. tmpGeo.computeVertexNormals();
  5012. // store morph normals
  5013. var faceNormal, vertexNormals;
  5014. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5015. face = this.faces[ f ];
  5016. faceNormal = morphNormals.faceNormals[ f ];
  5017. vertexNormals = morphNormals.vertexNormals[ f ];
  5018. faceNormal.copy( face.normal );
  5019. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5020. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5021. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5022. }
  5023. }
  5024. // restore original normals
  5025. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5026. face = this.faces[ f ];
  5027. face.normal = face.__originalFaceNormal;
  5028. face.vertexNormals = face.__originalVertexNormals;
  5029. }
  5030. },
  5031. computeTangents: function () {
  5032. // based on http://www.terathon.com/code/tangent.html
  5033. // tangents go to vertices
  5034. var f, fl, v, vl, i, il, vertexIndex,
  5035. face, uv, vA, vB, vC, uvA, uvB, uvC,
  5036. x1, x2, y1, y2, z1, z2,
  5037. s1, s2, t1, t2, r, t, test,
  5038. tan1 = [], tan2 = [],
  5039. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  5040. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  5041. n = new THREE.Vector3(), w;
  5042. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5043. tan1[ v ] = new THREE.Vector3();
  5044. tan2[ v ] = new THREE.Vector3();
  5045. }
  5046. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  5047. vA = context.vertices[ a ];
  5048. vB = context.vertices[ b ];
  5049. vC = context.vertices[ c ];
  5050. uvA = uv[ ua ];
  5051. uvB = uv[ ub ];
  5052. uvC = uv[ uc ];
  5053. x1 = vB.x - vA.x;
  5054. x2 = vC.x - vA.x;
  5055. y1 = vB.y - vA.y;
  5056. y2 = vC.y - vA.y;
  5057. z1 = vB.z - vA.z;
  5058. z2 = vC.z - vA.z;
  5059. s1 = uvB.x - uvA.x;
  5060. s2 = uvC.x - uvA.x;
  5061. t1 = uvB.y - uvA.y;
  5062. t2 = uvC.y - uvA.y;
  5063. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5064. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  5065. ( t2 * y1 - t1 * y2 ) * r,
  5066. ( t2 * z1 - t1 * z2 ) * r );
  5067. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  5068. ( s1 * y2 - s2 * y1 ) * r,
  5069. ( s1 * z2 - s2 * z1 ) * r );
  5070. tan1[ a ].add( sdir );
  5071. tan1[ b ].add( sdir );
  5072. tan1[ c ].add( sdir );
  5073. tan2[ a ].add( tdir );
  5074. tan2[ b ].add( tdir );
  5075. tan2[ c ].add( tdir );
  5076. }
  5077. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5078. face = this.faces[ f ];
  5079. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  5080. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  5081. }
  5082. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  5083. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5084. face = this.faces[ f ];
  5085. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i++ ) {
  5086. n.copy( face.vertexNormals[ i ] );
  5087. vertexIndex = face[ faceIndex[ i ] ];
  5088. t = tan1[ vertexIndex ];
  5089. // Gram-Schmidt orthogonalize
  5090. tmp.copy( t );
  5091. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5092. // Calculate handedness
  5093. tmp2.crossVectors( face.vertexNormals[ i ], t );
  5094. test = tmp2.dot( tan2[ vertexIndex ] );
  5095. w = (test < 0.0) ? -1.0 : 1.0;
  5096. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  5097. }
  5098. }
  5099. this.hasTangents = true;
  5100. },
  5101. computeLineDistances: function ( ) {
  5102. var d = 0;
  5103. var vertices = this.vertices;
  5104. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5105. if ( i > 0 ) {
  5106. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  5107. }
  5108. this.lineDistances[ i ] = d;
  5109. }
  5110. },
  5111. computeBoundingBox: function () {
  5112. if ( this.boundingBox === null ) {
  5113. this.boundingBox = new THREE.Box3();
  5114. }
  5115. this.boundingBox.setFromPoints( this.vertices );
  5116. },
  5117. computeBoundingSphere: function () {
  5118. if ( this.boundingSphere === null ) {
  5119. this.boundingSphere = new THREE.Sphere();
  5120. }
  5121. this.boundingSphere.setFromPoints( this.vertices );
  5122. },
  5123. /*
  5124. * Checks for duplicate vertices with hashmap.
  5125. * Duplicated vertices are removed
  5126. * and faces' vertices are updated.
  5127. */
  5128. mergeVertices: function () {
  5129. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  5130. var unique = [], changes = [];
  5131. var v, key;
  5132. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  5133. var precision = Math.pow( 10, precisionPoints );
  5134. var i,il, face;
  5135. var indices, k, j, jl, u;
  5136. // reset cache of vertices as it now will be changing.
  5137. this.__tmpVertices = undefined;
  5138. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  5139. v = this.vertices[ i ];
  5140. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  5141. if ( verticesMap[ key ] === undefined ) {
  5142. verticesMap[ key ] = i;
  5143. unique.push( this.vertices[ i ] );
  5144. changes[ i ] = unique.length - 1;
  5145. } else {
  5146. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  5147. changes[ i ] = changes[ verticesMap[ key ] ];
  5148. }
  5149. };
  5150. // if faces are completely degenerate after merging vertices, we
  5151. // have to remove them from the geometry.
  5152. var faceIndicesToRemove = [];
  5153. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  5154. face = this.faces[ i ];
  5155. face.a = changes[ face.a ];
  5156. face.b = changes[ face.b ];
  5157. face.c = changes[ face.c ];
  5158. indices = [ face.a, face.b, face.c ];
  5159. var dupIndex = -1;
  5160. // if any duplicate vertices are found in a Face3
  5161. // we have to remove the face as nothing can be saved
  5162. for ( var n = 0; n < 3; n ++ ) {
  5163. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  5164. dupIndex = n;
  5165. faceIndicesToRemove.push( i );
  5166. break;
  5167. }
  5168. }
  5169. }
  5170. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  5171. this.faces.splice( i, 1 );
  5172. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5173. this.faceVertexUvs[ j ].splice( i, 1 );
  5174. }
  5175. }
  5176. // Use unique set of vertices
  5177. var diff = this.vertices.length - unique.length;
  5178. this.vertices = unique;
  5179. return diff;
  5180. },
  5181. clone: function () {
  5182. var geometry = new THREE.Geometry();
  5183. var vertices = this.vertices;
  5184. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5185. geometry.vertices.push( vertices[ i ].clone() );
  5186. }
  5187. var faces = this.faces;
  5188. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  5189. geometry.faces.push( faces[ i ].clone() );
  5190. }
  5191. var uvs = this.faceVertexUvs[ 0 ];
  5192. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  5193. var uv = uvs[ i ], uvCopy = [];
  5194. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5195. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  5196. }
  5197. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  5198. }
  5199. return geometry;
  5200. },
  5201. dispose: function () {
  5202. this.dispatchEvent( { type: 'dispose' } );
  5203. }
  5204. };
  5205. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  5206. THREE.GeometryIdCount = 0;
  5207. /**
  5208. * @author alteredq / http://alteredqualia.com/
  5209. */
  5210. THREE.BufferGeometry = function () {
  5211. this.id = THREE.GeometryIdCount ++;
  5212. this.uuid = THREE.Math.generateUUID();
  5213. this.name = '';
  5214. // attributes
  5215. this.attributes = {};
  5216. // attributes typed arrays are kept only if dynamic flag is set
  5217. this.dynamic = true;
  5218. // offsets for chunks when using indexed elements
  5219. this.offsets = [];
  5220. // boundings
  5221. this.boundingBox = null;
  5222. this.boundingSphere = null;
  5223. this.hasTangents = false;
  5224. // for compatibility
  5225. this.morphTargets = [];
  5226. };
  5227. THREE.BufferGeometry.prototype = {
  5228. constructor: THREE.BufferGeometry,
  5229. applyMatrix: function ( matrix ) {
  5230. var positionArray;
  5231. var normalArray;
  5232. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  5233. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  5234. if ( positionArray !== undefined ) {
  5235. matrix.multiplyVector3Array( positionArray );
  5236. this.verticesNeedUpdate = true;
  5237. }
  5238. if ( normalArray !== undefined ) {
  5239. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5240. normalMatrix.multiplyVector3Array( normalArray );
  5241. this.normalizeNormals();
  5242. this.normalsNeedUpdate = true;
  5243. }
  5244. },
  5245. computeBoundingBox: function () {
  5246. if ( this.boundingBox === null ) {
  5247. this.boundingBox = new THREE.Box3();
  5248. }
  5249. var positions = this.attributes[ "position" ].array;
  5250. if ( positions ) {
  5251. var bb = this.boundingBox;
  5252. var x, y, z;
  5253. if( positions.length >= 3 ) {
  5254. bb.min.x = bb.max.x = positions[ 0 ];
  5255. bb.min.y = bb.max.y = positions[ 1 ];
  5256. bb.min.z = bb.max.z = positions[ 2 ];
  5257. }
  5258. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5259. x = positions[ i ];
  5260. y = positions[ i + 1 ];
  5261. z = positions[ i + 2 ];
  5262. // bounding box
  5263. if ( x < bb.min.x ) {
  5264. bb.min.x = x;
  5265. } else if ( x > bb.max.x ) {
  5266. bb.max.x = x;
  5267. }
  5268. if ( y < bb.min.y ) {
  5269. bb.min.y = y;
  5270. } else if ( y > bb.max.y ) {
  5271. bb.max.y = y;
  5272. }
  5273. if ( z < bb.min.z ) {
  5274. bb.min.z = z;
  5275. } else if ( z > bb.max.z ) {
  5276. bb.max.z = z;
  5277. }
  5278. }
  5279. }
  5280. if ( positions === undefined || positions.length === 0 ) {
  5281. this.boundingBox.min.set( 0, 0, 0 );
  5282. this.boundingBox.max.set( 0, 0, 0 );
  5283. }
  5284. },
  5285. computeBoundingSphere: function () {
  5286. if ( this.boundingSphere === null ) {
  5287. this.boundingSphere = new THREE.Sphere();
  5288. }
  5289. var positions = this.attributes[ "position" ].array;
  5290. if ( positions ) {
  5291. var radiusSq, maxRadiusSq = 0;
  5292. var x, y, z;
  5293. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5294. x = positions[ i ];
  5295. y = positions[ i + 1 ];
  5296. z = positions[ i + 2 ];
  5297. radiusSq = x * x + y * y + z * z;
  5298. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  5299. }
  5300. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5301. }
  5302. },
  5303. computeVertexNormals: function () {
  5304. if ( this.attributes[ "position" ] ) {
  5305. var i, il;
  5306. var j, jl;
  5307. var nVertexElements = this.attributes[ "position" ].array.length;
  5308. if ( this.attributes[ "normal" ] === undefined ) {
  5309. this.attributes[ "normal" ] = {
  5310. itemSize: 3,
  5311. array: new Float32Array( nVertexElements )
  5312. };
  5313. } else {
  5314. // reset existing normals to zero
  5315. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5316. this.attributes[ "normal" ].array[ i ] = 0;
  5317. }
  5318. }
  5319. var positions = this.attributes[ "position" ].array;
  5320. var normals = this.attributes[ "normal" ].array;
  5321. var vA, vB, vC, x, y, z,
  5322. pA = new THREE.Vector3(),
  5323. pB = new THREE.Vector3(),
  5324. pC = new THREE.Vector3(),
  5325. cb = new THREE.Vector3(),
  5326. ab = new THREE.Vector3();
  5327. // indexed elements
  5328. if ( this.attributes[ "index" ] ) {
  5329. var indices = this.attributes[ "index" ].array;
  5330. var offsets = this.offsets;
  5331. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5332. var start = offsets[ j ].start;
  5333. var count = offsets[ j ].count;
  5334. var index = offsets[ j ].index;
  5335. for ( i = start, il = start + count; i < il; i += 3 ) {
  5336. vA = index + indices[ i ];
  5337. vB = index + indices[ i + 1 ];
  5338. vC = index + indices[ i + 2 ];
  5339. x = positions[ vA * 3 ];
  5340. y = positions[ vA * 3 + 1 ];
  5341. z = positions[ vA * 3 + 2 ];
  5342. pA.set( x, y, z );
  5343. x = positions[ vB * 3 ];
  5344. y = positions[ vB * 3 + 1 ];
  5345. z = positions[ vB * 3 + 2 ];
  5346. pB.set( x, y, z );
  5347. x = positions[ vC * 3 ];
  5348. y = positions[ vC * 3 + 1 ];
  5349. z = positions[ vC * 3 + 2 ];
  5350. pC.set( x, y, z );
  5351. cb.subVectors( pC, pB );
  5352. ab.subVectors( pA, pB );
  5353. cb.cross( ab );
  5354. normals[ vA * 3 ] += cb.x;
  5355. normals[ vA * 3 + 1 ] += cb.y;
  5356. normals[ vA * 3 + 2 ] += cb.z;
  5357. normals[ vB * 3 ] += cb.x;
  5358. normals[ vB * 3 + 1 ] += cb.y;
  5359. normals[ vB * 3 + 2 ] += cb.z;
  5360. normals[ vC * 3 ] += cb.x;
  5361. normals[ vC * 3 + 1 ] += cb.y;
  5362. normals[ vC * 3 + 2 ] += cb.z;
  5363. }
  5364. }
  5365. // non-indexed elements (unconnected triangle soup)
  5366. } else {
  5367. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5368. x = positions[ i ];
  5369. y = positions[ i + 1 ];
  5370. z = positions[ i + 2 ];
  5371. pA.set( x, y, z );
  5372. x = positions[ i + 3 ];
  5373. y = positions[ i + 4 ];
  5374. z = positions[ i + 5 ];
  5375. pB.set( x, y, z );
  5376. x = positions[ i + 6 ];
  5377. y = positions[ i + 7 ];
  5378. z = positions[ i + 8 ];
  5379. pC.set( x, y, z );
  5380. cb.subVectors( pC, pB );
  5381. ab.subVectors( pA, pB );
  5382. cb.cross( ab );
  5383. normals[ i ] = cb.x;
  5384. normals[ i + 1 ] = cb.y;
  5385. normals[ i + 2 ] = cb.z;
  5386. normals[ i + 3 ] = cb.x;
  5387. normals[ i + 4 ] = cb.y;
  5388. normals[ i + 5 ] = cb.z;
  5389. normals[ i + 6 ] = cb.x;
  5390. normals[ i + 7 ] = cb.y;
  5391. normals[ i + 8 ] = cb.z;
  5392. }
  5393. }
  5394. this.normalizeNormals();
  5395. this.normalsNeedUpdate = true;
  5396. }
  5397. },
  5398. normalizeNormals: function () {
  5399. var normals = this.attributes[ "normal" ].array;
  5400. var x, y, z, n;
  5401. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5402. x = normals[ i ];
  5403. y = normals[ i + 1 ];
  5404. z = normals[ i + 2 ];
  5405. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5406. normals[ i ] *= n;
  5407. normals[ i + 1 ] *= n;
  5408. normals[ i + 2 ] *= n;
  5409. }
  5410. },
  5411. computeTangents: function () {
  5412. // based on http://www.terathon.com/code/tangent.html
  5413. // (per vertex tangents)
  5414. if ( this.attributes[ "index" ] === undefined ||
  5415. this.attributes[ "position" ] === undefined ||
  5416. this.attributes[ "normal" ] === undefined ||
  5417. this.attributes[ "uv" ] === undefined ) {
  5418. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5419. return;
  5420. }
  5421. var indices = this.attributes[ "index" ].array;
  5422. var positions = this.attributes[ "position" ].array;
  5423. var normals = this.attributes[ "normal" ].array;
  5424. var uvs = this.attributes[ "uv" ].array;
  5425. var nVertices = positions.length / 3;
  5426. if ( this.attributes[ "tangent" ] === undefined ) {
  5427. var nTangentElements = 4 * nVertices;
  5428. this.attributes[ "tangent" ] = {
  5429. itemSize: 4,
  5430. array: new Float32Array( nTangentElements )
  5431. };
  5432. }
  5433. var tangents = this.attributes[ "tangent" ].array;
  5434. var tan1 = [], tan2 = [];
  5435. for ( var k = 0; k < nVertices; k ++ ) {
  5436. tan1[ k ] = new THREE.Vector3();
  5437. tan2[ k ] = new THREE.Vector3();
  5438. }
  5439. var xA, yA, zA,
  5440. xB, yB, zB,
  5441. xC, yC, zC,
  5442. uA, vA,
  5443. uB, vB,
  5444. uC, vC,
  5445. x1, x2, y1, y2, z1, z2,
  5446. s1, s2, t1, t2, r;
  5447. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5448. function handleTriangle( a, b, c ) {
  5449. xA = positions[ a * 3 ];
  5450. yA = positions[ a * 3 + 1 ];
  5451. zA = positions[ a * 3 + 2 ];
  5452. xB = positions[ b * 3 ];
  5453. yB = positions[ b * 3 + 1 ];
  5454. zB = positions[ b * 3 + 2 ];
  5455. xC = positions[ c * 3 ];
  5456. yC = positions[ c * 3 + 1 ];
  5457. zC = positions[ c * 3 + 2 ];
  5458. uA = uvs[ a * 2 ];
  5459. vA = uvs[ a * 2 + 1 ];
  5460. uB = uvs[ b * 2 ];
  5461. vB = uvs[ b * 2 + 1 ];
  5462. uC = uvs[ c * 2 ];
  5463. vC = uvs[ c * 2 + 1 ];
  5464. x1 = xB - xA;
  5465. x2 = xC - xA;
  5466. y1 = yB - yA;
  5467. y2 = yC - yA;
  5468. z1 = zB - zA;
  5469. z2 = zC - zA;
  5470. s1 = uB - uA;
  5471. s2 = uC - uA;
  5472. t1 = vB - vA;
  5473. t2 = vC - vA;
  5474. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5475. sdir.set(
  5476. ( t2 * x1 - t1 * x2 ) * r,
  5477. ( t2 * y1 - t1 * y2 ) * r,
  5478. ( t2 * z1 - t1 * z2 ) * r
  5479. );
  5480. tdir.set(
  5481. ( s1 * x2 - s2 * x1 ) * r,
  5482. ( s1 * y2 - s2 * y1 ) * r,
  5483. ( s1 * z2 - s2 * z1 ) * r
  5484. );
  5485. tan1[ a ].add( sdir );
  5486. tan1[ b ].add( sdir );
  5487. tan1[ c ].add( sdir );
  5488. tan2[ a ].add( tdir );
  5489. tan2[ b ].add( tdir );
  5490. tan2[ c ].add( tdir );
  5491. }
  5492. var i, il;
  5493. var j, jl;
  5494. var iA, iB, iC;
  5495. var offsets = this.offsets;
  5496. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5497. var start = offsets[ j ].start;
  5498. var count = offsets[ j ].count;
  5499. var index = offsets[ j ].index;
  5500. for ( i = start, il = start + count; i < il; i += 3 ) {
  5501. iA = index + indices[ i ];
  5502. iB = index + indices[ i + 1 ];
  5503. iC = index + indices[ i + 2 ];
  5504. handleTriangle( iA, iB, iC );
  5505. }
  5506. }
  5507. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5508. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5509. var w, t, test;
  5510. function handleVertex( v ) {
  5511. n.x = normals[ v * 3 ];
  5512. n.y = normals[ v * 3 + 1 ];
  5513. n.z = normals[ v * 3 + 2 ];
  5514. n2.copy( n );
  5515. t = tan1[ v ];
  5516. // Gram-Schmidt orthogonalize
  5517. tmp.copy( t );
  5518. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5519. // Calculate handedness
  5520. tmp2.crossVectors( n2, t );
  5521. test = tmp2.dot( tan2[ v ] );
  5522. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5523. tangents[ v * 4 ] = tmp.x;
  5524. tangents[ v * 4 + 1 ] = tmp.y;
  5525. tangents[ v * 4 + 2 ] = tmp.z;
  5526. tangents[ v * 4 + 3 ] = w;
  5527. }
  5528. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5529. var start = offsets[ j ].start;
  5530. var count = offsets[ j ].count;
  5531. var index = offsets[ j ].index;
  5532. for ( i = start, il = start + count; i < il; i += 3 ) {
  5533. iA = index + indices[ i ];
  5534. iB = index + indices[ i + 1 ];
  5535. iC = index + indices[ i + 2 ];
  5536. handleVertex( iA );
  5537. handleVertex( iB );
  5538. handleVertex( iC );
  5539. }
  5540. }
  5541. this.hasTangents = true;
  5542. this.tangentsNeedUpdate = true;
  5543. },
  5544. dispose: function () {
  5545. this.dispatchEvent( { type: 'dispose' } );
  5546. }
  5547. };
  5548. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  5549. /**
  5550. * @author mrdoob / http://mrdoob.com/
  5551. * @author mikael emtinger / http://gomo.se/
  5552. * @author WestLangley / http://github.com/WestLangley
  5553. */
  5554. THREE.Camera = function () {
  5555. THREE.Object3D.call( this );
  5556. this.matrixWorldInverse = new THREE.Matrix4();
  5557. this.projectionMatrix = new THREE.Matrix4();
  5558. this.projectionMatrixInverse = new THREE.Matrix4();
  5559. };
  5560. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5561. THREE.Camera.prototype.lookAt = function () {
  5562. // This routine does not support cameras with rotated and/or translated parent(s)
  5563. var m1 = new THREE.Matrix4();
  5564. return function ( vector ) {
  5565. m1.lookAt( this.position, vector, this.up );
  5566. this.quaternion.setFromRotationMatrix( m1 );
  5567. };
  5568. }();
  5569. /**
  5570. * @author alteredq / http://alteredqualia.com/
  5571. */
  5572. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5573. THREE.Camera.call( this );
  5574. this.left = left;
  5575. this.right = right;
  5576. this.top = top;
  5577. this.bottom = bottom;
  5578. this.near = ( near !== undefined ) ? near : 0.1;
  5579. this.far = ( far !== undefined ) ? far : 2000;
  5580. this.updateProjectionMatrix();
  5581. };
  5582. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5583. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5584. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5585. };
  5586. /**
  5587. * @author mrdoob / http://mrdoob.com/
  5588. * @author greggman / http://games.greggman.com/
  5589. * @author zz85 / http://www.lab4games.net/zz85/blog
  5590. */
  5591. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5592. THREE.Camera.call( this );
  5593. this.fov = fov !== undefined ? fov : 50;
  5594. this.aspect = aspect !== undefined ? aspect : 1;
  5595. this.near = near !== undefined ? near : 0.1;
  5596. this.far = far !== undefined ? far : 2000;
  5597. this.updateProjectionMatrix();
  5598. };
  5599. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5600. /**
  5601. * Uses Focal Length (in mm) to estimate and set FOV
  5602. * 35mm (fullframe) camera is used if frame size is not specified;
  5603. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5604. */
  5605. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5606. if ( frameHeight === undefined ) frameHeight = 24;
  5607. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5608. this.updateProjectionMatrix();
  5609. }
  5610. /**
  5611. * Sets an offset in a larger frustum. This is useful for multi-window or
  5612. * multi-monitor/multi-machine setups.
  5613. *
  5614. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5615. * the monitors are in grid like this
  5616. *
  5617. * +---+---+---+
  5618. * | A | B | C |
  5619. * +---+---+---+
  5620. * | D | E | F |
  5621. * +---+---+---+
  5622. *
  5623. * then for each monitor you would call it like this
  5624. *
  5625. * var w = 1920;
  5626. * var h = 1080;
  5627. * var fullWidth = w * 3;
  5628. * var fullHeight = h * 2;
  5629. *
  5630. * --A--
  5631. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5632. * --B--
  5633. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5634. * --C--
  5635. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5636. * --D--
  5637. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5638. * --E--
  5639. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5640. * --F--
  5641. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5642. *
  5643. * Note there is no reason monitors have to be the same size or in a grid.
  5644. */
  5645. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5646. this.fullWidth = fullWidth;
  5647. this.fullHeight = fullHeight;
  5648. this.x = x;
  5649. this.y = y;
  5650. this.width = width;
  5651. this.height = height;
  5652. this.updateProjectionMatrix();
  5653. };
  5654. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5655. if ( this.fullWidth ) {
  5656. var aspect = this.fullWidth / this.fullHeight;
  5657. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5658. var bottom = -top;
  5659. var left = aspect * bottom;
  5660. var right = aspect * top;
  5661. var width = Math.abs( right - left );
  5662. var height = Math.abs( top - bottom );
  5663. this.projectionMatrix.makeFrustum(
  5664. left + this.x * width / this.fullWidth,
  5665. left + ( this.x + this.width ) * width / this.fullWidth,
  5666. top - ( this.y + this.height ) * height / this.fullHeight,
  5667. top - this.y * height / this.fullHeight,
  5668. this.near,
  5669. this.far
  5670. );
  5671. } else {
  5672. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5673. }
  5674. };
  5675. /**
  5676. * @author mrdoob / http://mrdoob.com/
  5677. * @author alteredq / http://alteredqualia.com/
  5678. */
  5679. THREE.Light = function ( hex ) {
  5680. THREE.Object3D.call( this );
  5681. this.color = new THREE.Color( hex );
  5682. };
  5683. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5684. THREE.Light.prototype.clone = function ( light ) {
  5685. if ( light === undefined ) light = new THREE.Light();
  5686. THREE.Object3D.prototype.clone.call( this, light );
  5687. light.color.copy( this.color );
  5688. return light;
  5689. };
  5690. /**
  5691. * @author mrdoob / http://mrdoob.com/
  5692. */
  5693. THREE.AmbientLight = function ( hex ) {
  5694. THREE.Light.call( this, hex );
  5695. };
  5696. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5697. THREE.AmbientLight.prototype.clone = function () {
  5698. var light = new THREE.AmbientLight();
  5699. THREE.Light.prototype.clone.call( this, light );
  5700. return light;
  5701. };
  5702. /**
  5703. * @author MPanknin / http://www.redplant.de/
  5704. * @author alteredq / http://alteredqualia.com/
  5705. */
  5706. THREE.AreaLight = function ( hex, intensity ) {
  5707. THREE.Light.call( this, hex );
  5708. this.normal = new THREE.Vector3( 0, -1, 0 );
  5709. this.right = new THREE.Vector3( 1, 0, 0 );
  5710. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5711. this.width = 1.0;
  5712. this.height = 1.0;
  5713. this.constantAttenuation = 1.5;
  5714. this.linearAttenuation = 0.5;
  5715. this.quadraticAttenuation = 0.1;
  5716. };
  5717. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5718. /**
  5719. * @author mrdoob / http://mrdoob.com/
  5720. * @author alteredq / http://alteredqualia.com/
  5721. */
  5722. THREE.DirectionalLight = function ( hex, intensity ) {
  5723. THREE.Light.call( this, hex );
  5724. this.position.set( 0, 1, 0 );
  5725. this.target = new THREE.Object3D();
  5726. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5727. this.castShadow = false;
  5728. this.onlyShadow = false;
  5729. //
  5730. this.shadowCameraNear = 50;
  5731. this.shadowCameraFar = 5000;
  5732. this.shadowCameraLeft = -500;
  5733. this.shadowCameraRight = 500;
  5734. this.shadowCameraTop = 500;
  5735. this.shadowCameraBottom = -500;
  5736. this.shadowCameraVisible = false;
  5737. this.shadowBias = 0;
  5738. this.shadowDarkness = 0.5;
  5739. this.shadowMapWidth = 512;
  5740. this.shadowMapHeight = 512;
  5741. //
  5742. this.shadowCascade = false;
  5743. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5744. this.shadowCascadeCount = 2;
  5745. this.shadowCascadeBias = [ 0, 0, 0 ];
  5746. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5747. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5748. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5749. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5750. this.shadowCascadeArray = [];
  5751. //
  5752. this.shadowMap = null;
  5753. this.shadowMapSize = null;
  5754. this.shadowCamera = null;
  5755. this.shadowMatrix = null;
  5756. };
  5757. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5758. THREE.DirectionalLight.prototype.clone = function () {
  5759. var light = new THREE.DirectionalLight();
  5760. THREE.Light.prototype.clone.call( this, light );
  5761. light.target = this.target.clone();
  5762. light.intensity = this.intensity;
  5763. light.castShadow = this.castShadow;
  5764. light.onlyShadow = this.onlyShadow;
  5765. return light;
  5766. };
  5767. /**
  5768. * @author alteredq / http://alteredqualia.com/
  5769. */
  5770. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5771. THREE.Light.call( this, skyColorHex );
  5772. this.position.set( 0, 100, 0 );
  5773. this.groundColor = new THREE.Color( groundColorHex );
  5774. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5775. };
  5776. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5777. THREE.HemisphereLight.prototype.clone = function () {
  5778. var light = new THREE.PointLight();
  5779. THREE.Light.prototype.clone.call( this, light );
  5780. light.groundColor.copy( this.groundColor );
  5781. light.intensity = this.intensity;
  5782. return light;
  5783. };
  5784. /**
  5785. * @author mrdoob / http://mrdoob.com/
  5786. */
  5787. THREE.PointLight = function ( hex, intensity, distance ) {
  5788. THREE.Light.call( this, hex );
  5789. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5790. this.distance = ( distance !== undefined ) ? distance : 0;
  5791. };
  5792. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5793. THREE.PointLight.prototype.clone = function () {
  5794. var light = new THREE.PointLight();
  5795. THREE.Light.prototype.clone.call( this, light );
  5796. light.intensity = this.intensity;
  5797. light.distance = this.distance;
  5798. return light;
  5799. };
  5800. /**
  5801. * @author alteredq / http://alteredqualia.com/
  5802. */
  5803. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5804. THREE.Light.call( this, hex );
  5805. this.position.set( 0, 1, 0 );
  5806. this.target = new THREE.Object3D();
  5807. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5808. this.distance = ( distance !== undefined ) ? distance : 0;
  5809. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  5810. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5811. this.castShadow = false;
  5812. this.onlyShadow = false;
  5813. //
  5814. this.shadowCameraNear = 50;
  5815. this.shadowCameraFar = 5000;
  5816. this.shadowCameraFov = 50;
  5817. this.shadowCameraVisible = false;
  5818. this.shadowBias = 0;
  5819. this.shadowDarkness = 0.5;
  5820. this.shadowMapWidth = 512;
  5821. this.shadowMapHeight = 512;
  5822. //
  5823. this.shadowMap = null;
  5824. this.shadowMapSize = null;
  5825. this.shadowCamera = null;
  5826. this.shadowMatrix = null;
  5827. };
  5828. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  5829. THREE.SpotLight.prototype.clone = function () {
  5830. var light = new THREE.SpotLight();
  5831. THREE.Light.prototype.clone.call( this, light );
  5832. light.target = this.target.clone();
  5833. light.intensity = this.intensity;
  5834. light.distance = this.distance;
  5835. light.angle = this.angle;
  5836. light.exponent = this.exponent;
  5837. light.castShadow = this.castShadow;
  5838. light.onlyShadow = this.onlyShadow;
  5839. return light;
  5840. };
  5841. /**
  5842. * @author alteredq / http://alteredqualia.com/
  5843. */
  5844. THREE.Loader = function ( showStatus ) {
  5845. this.showStatus = showStatus;
  5846. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  5847. this.onLoadStart = function () {};
  5848. this.onLoadProgress = function () {};
  5849. this.onLoadComplete = function () {};
  5850. };
  5851. THREE.Loader.prototype = {
  5852. constructor: THREE.Loader,
  5853. crossOrigin: 'anonymous',
  5854. addStatusElement: function () {
  5855. var e = document.createElement( "div" );
  5856. e.style.position = "absolute";
  5857. e.style.right = "0px";
  5858. e.style.top = "0px";
  5859. e.style.fontSize = "0.8em";
  5860. e.style.textAlign = "left";
  5861. e.style.background = "rgba(0,0,0,0.25)";
  5862. e.style.color = "#fff";
  5863. e.style.width = "120px";
  5864. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  5865. e.style.zIndex = 1000;
  5866. e.innerHTML = "Loading ...";
  5867. return e;
  5868. },
  5869. updateProgress: function ( progress ) {
  5870. var message = "Loaded ";
  5871. if ( progress.total ) {
  5872. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  5873. } else {
  5874. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  5875. }
  5876. this.statusDomElement.innerHTML = message;
  5877. },
  5878. extractUrlBase: function ( url ) {
  5879. var parts = url.split( '/' );
  5880. parts.pop();
  5881. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  5882. },
  5883. initMaterials: function ( materials, texturePath ) {
  5884. var array = [];
  5885. for ( var i = 0; i < materials.length; ++ i ) {
  5886. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  5887. }
  5888. return array;
  5889. },
  5890. needsTangents: function ( materials ) {
  5891. for( var i = 0, il = materials.length; i < il; i ++ ) {
  5892. var m = materials[ i ];
  5893. if ( m instanceof THREE.ShaderMaterial ) return true;
  5894. }
  5895. return false;
  5896. },
  5897. createMaterial: function ( m, texturePath ) {
  5898. var _this = this;
  5899. function is_pow2( n ) {
  5900. var l = Math.log( n ) / Math.LN2;
  5901. return Math.floor( l ) == l;
  5902. }
  5903. function nearest_pow2( n ) {
  5904. var l = Math.log( n ) / Math.LN2;
  5905. return Math.pow( 2, Math.round( l ) );
  5906. }
  5907. function load_image( where, url ) {
  5908. var image = new Image();
  5909. image.onload = function () {
  5910. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  5911. var width = nearest_pow2( this.width );
  5912. var height = nearest_pow2( this.height );
  5913. where.image.width = width;
  5914. where.image.height = height;
  5915. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  5916. } else {
  5917. where.image = this;
  5918. }
  5919. where.needsUpdate = true;
  5920. };
  5921. image.crossOrigin = _this.crossOrigin;
  5922. image.src = url;
  5923. }
  5924. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  5925. var isCompressed = /\.dds$/i.test( sourceFile );
  5926. var fullPath = texturePath + "/" + sourceFile;
  5927. if ( isCompressed ) {
  5928. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  5929. where[ name ] = texture;
  5930. } else {
  5931. var texture = document.createElement( 'canvas' );
  5932. where[ name ] = new THREE.Texture( texture );
  5933. }
  5934. where[ name ].sourceFile = sourceFile;
  5935. if( repeat ) {
  5936. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5937. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5938. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5939. }
  5940. if ( offset ) {
  5941. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5942. }
  5943. if ( wrap ) {
  5944. var wrapMap = {
  5945. "repeat": THREE.RepeatWrapping,
  5946. "mirror": THREE.MirroredRepeatWrapping
  5947. }
  5948. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5949. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5950. }
  5951. if ( anisotropy ) {
  5952. where[ name ].anisotropy = anisotropy;
  5953. }
  5954. if ( ! isCompressed ) {
  5955. load_image( where[ name ], fullPath );
  5956. }
  5957. }
  5958. function rgb2hex( rgb ) {
  5959. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5960. }
  5961. // defaults
  5962. var mtype = "MeshLambertMaterial";
  5963. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5964. // parameters from model file
  5965. if ( m.shading ) {
  5966. var shading = m.shading.toLowerCase();
  5967. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5968. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5969. }
  5970. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5971. mpars.blending = THREE[ m.blending ];
  5972. }
  5973. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5974. mpars.transparent = m.transparent;
  5975. }
  5976. if ( m.depthTest !== undefined ) {
  5977. mpars.depthTest = m.depthTest;
  5978. }
  5979. if ( m.depthWrite !== undefined ) {
  5980. mpars.depthWrite = m.depthWrite;
  5981. }
  5982. if ( m.visible !== undefined ) {
  5983. mpars.visible = m.visible;
  5984. }
  5985. if ( m.flipSided !== undefined ) {
  5986. mpars.side = THREE.BackSide;
  5987. }
  5988. if ( m.doubleSided !== undefined ) {
  5989. mpars.side = THREE.DoubleSide;
  5990. }
  5991. if ( m.wireframe !== undefined ) {
  5992. mpars.wireframe = m.wireframe;
  5993. }
  5994. if ( m.vertexColors !== undefined ) {
  5995. if ( m.vertexColors === "face" ) {
  5996. mpars.vertexColors = THREE.FaceColors;
  5997. } else if ( m.vertexColors ) {
  5998. mpars.vertexColors = THREE.VertexColors;
  5999. }
  6000. }
  6001. // colors
  6002. if ( m.colorDiffuse ) {
  6003. mpars.color = rgb2hex( m.colorDiffuse );
  6004. } else if ( m.DbgColor ) {
  6005. mpars.color = m.DbgColor;
  6006. }
  6007. if ( m.colorSpecular ) {
  6008. mpars.specular = rgb2hex( m.colorSpecular );
  6009. }
  6010. if ( m.colorAmbient ) {
  6011. mpars.ambient = rgb2hex( m.colorAmbient );
  6012. }
  6013. // modifiers
  6014. if ( m.transparency ) {
  6015. mpars.opacity = m.transparency;
  6016. }
  6017. if ( m.specularCoef ) {
  6018. mpars.shininess = m.specularCoef;
  6019. }
  6020. // textures
  6021. if ( m.mapDiffuse && texturePath ) {
  6022. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  6023. }
  6024. if ( m.mapLight && texturePath ) {
  6025. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  6026. }
  6027. if ( m.mapBump && texturePath ) {
  6028. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  6029. }
  6030. if ( m.mapNormal && texturePath ) {
  6031. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  6032. }
  6033. if ( m.mapSpecular && texturePath ) {
  6034. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  6035. }
  6036. //
  6037. if ( m.mapBumpScale ) {
  6038. mpars.bumpScale = m.mapBumpScale;
  6039. }
  6040. // special case for normal mapped material
  6041. if ( m.mapNormal ) {
  6042. var shader = THREE.ShaderLib[ "normalmap" ];
  6043. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6044. uniforms[ "tNormal" ].value = mpars.normalMap;
  6045. if ( m.mapNormalFactor ) {
  6046. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  6047. }
  6048. if ( mpars.map ) {
  6049. uniforms[ "tDiffuse" ].value = mpars.map;
  6050. uniforms[ "enableDiffuse" ].value = true;
  6051. }
  6052. if ( mpars.specularMap ) {
  6053. uniforms[ "tSpecular" ].value = mpars.specularMap;
  6054. uniforms[ "enableSpecular" ].value = true;
  6055. }
  6056. if ( mpars.lightMap ) {
  6057. uniforms[ "tAO" ].value = mpars.lightMap;
  6058. uniforms[ "enableAO" ].value = true;
  6059. }
  6060. // for the moment don't handle displacement texture
  6061. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  6062. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  6063. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  6064. uniforms[ "uShininess" ].value = mpars.shininess;
  6065. if ( mpars.opacity !== undefined ) {
  6066. uniforms[ "uOpacity" ].value = mpars.opacity;
  6067. }
  6068. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6069. var material = new THREE.ShaderMaterial( parameters );
  6070. if ( mpars.transparent ) {
  6071. material.transparent = true;
  6072. }
  6073. } else {
  6074. var material = new THREE[ mtype ]( mpars );
  6075. }
  6076. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6077. return material;
  6078. }
  6079. };
  6080. /**
  6081. * @author mrdoob / http://mrdoob.com/
  6082. */
  6083. THREE.XHRLoader = function ( manager ) {
  6084. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6085. };
  6086. THREE.XHRLoader.prototype = {
  6087. constructor: THREE.XHRLoader,
  6088. load: function ( url, onLoad, onProgress, onError ) {
  6089. var scope = this;
  6090. var request = new XMLHttpRequest();
  6091. if ( onLoad !== undefined ) {
  6092. request.addEventListener( 'load', function ( event ) {
  6093. onLoad( event.target.responseText );
  6094. scope.manager.itemEnd( url );
  6095. }, false );
  6096. }
  6097. if ( onProgress !== undefined ) {
  6098. request.addEventListener( 'progress', function ( event ) {
  6099. onProgress( event );
  6100. }, false );
  6101. }
  6102. if ( onError !== undefined ) {
  6103. request.addEventListener( 'error', function ( event ) {
  6104. onError( event );
  6105. }, false );
  6106. }
  6107. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6108. request.open( 'GET', url, true );
  6109. request.send( null );
  6110. scope.manager.itemStart( url );
  6111. },
  6112. setCrossOrigin: function ( value ) {
  6113. this.crossOrigin = value;
  6114. }
  6115. };
  6116. /**
  6117. * @author mrdoob / http://mrdoob.com/
  6118. */
  6119. THREE.ImageLoader = function ( manager ) {
  6120. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6121. };
  6122. THREE.ImageLoader.prototype = {
  6123. constructor: THREE.ImageLoader,
  6124. load: function ( url, onLoad, onProgress, onError ) {
  6125. var scope = this;
  6126. var image = document.createElement( 'img' );
  6127. if ( onLoad !== undefined ) {
  6128. image.addEventListener( 'load', function ( event ) {
  6129. scope.manager.itemEnd( url );
  6130. onLoad( this );
  6131. }, false );
  6132. }
  6133. if ( onProgress !== undefined ) {
  6134. image.addEventListener( 'progress', function ( event ) {
  6135. onProgress( event );
  6136. }, false );
  6137. }
  6138. if ( onError !== undefined ) {
  6139. image.addEventListener( 'error', function ( event ) {
  6140. onError( event );
  6141. }, false );
  6142. }
  6143. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  6144. image.src = url;
  6145. scope.manager.itemStart( url );
  6146. },
  6147. setCrossOrigin: function ( value ) {
  6148. this.crossOrigin = value;
  6149. }
  6150. }
  6151. /**
  6152. * @author mrdoob / http://mrdoob.com/
  6153. * @author alteredq / http://alteredqualia.com/
  6154. */
  6155. THREE.JSONLoader = function ( showStatus ) {
  6156. THREE.Loader.call( this, showStatus );
  6157. this.withCredentials = false;
  6158. };
  6159. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  6160. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  6161. var scope = this;
  6162. // todo: unify load API to for easier SceneLoader use
  6163. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  6164. this.onLoadStart();
  6165. this.loadAjaxJSON( this, url, callback, texturePath );
  6166. };
  6167. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  6168. var xhr = new XMLHttpRequest();
  6169. var length = 0;
  6170. xhr.onreadystatechange = function () {
  6171. if ( xhr.readyState === xhr.DONE ) {
  6172. if ( xhr.status === 200 || xhr.status === 0 ) {
  6173. if ( xhr.responseText ) {
  6174. var json = JSON.parse( xhr.responseText );
  6175. var result = context.parse( json, texturePath );
  6176. callback( result.geometry, result.materials );
  6177. } else {
  6178. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  6179. }
  6180. // in context of more complex asset initialization
  6181. // do not block on single failed file
  6182. // maybe should go even one more level up
  6183. context.onLoadComplete();
  6184. } else {
  6185. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  6186. }
  6187. } else if ( xhr.readyState === xhr.LOADING ) {
  6188. if ( callbackProgress ) {
  6189. if ( length === 0 ) {
  6190. length = xhr.getResponseHeader( "Content-Length" );
  6191. }
  6192. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  6193. }
  6194. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  6195. if ( callbackProgress !== undefined ) {
  6196. length = xhr.getResponseHeader( "Content-Length" );
  6197. }
  6198. }
  6199. };
  6200. xhr.open( "GET", url, true );
  6201. xhr.withCredentials = this.withCredentials;
  6202. xhr.send( null );
  6203. };
  6204. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  6205. var scope = this,
  6206. geometry = new THREE.Geometry(),
  6207. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  6208. parseModel( scale );
  6209. parseSkin();
  6210. parseMorphing( scale );
  6211. geometry.computeCentroids();
  6212. geometry.computeFaceNormals();
  6213. geometry.computeBoundingSphere();
  6214. function parseModel( scale ) {
  6215. function isBitSet( value, position ) {
  6216. return value & ( 1 << position );
  6217. }
  6218. var i, j, fi,
  6219. offset, zLength,
  6220. colorIndex, normalIndex, uvIndex, materialIndex,
  6221. type,
  6222. isQuad,
  6223. hasMaterial,
  6224. hasFaceVertexUv,
  6225. hasFaceNormal, hasFaceVertexNormal,
  6226. hasFaceColor, hasFaceVertexColor,
  6227. vertex, face, faceA, faceB, color, hex, normal,
  6228. uvLayer, uv, u, v,
  6229. faces = json.faces,
  6230. vertices = json.vertices,
  6231. normals = json.normals,
  6232. colors = json.colors,
  6233. nUvLayers = 0;
  6234. if ( json.uvs !== undefined ) {
  6235. // disregard empty arrays
  6236. for ( i = 0; i < json.uvs.length; i++ ) {
  6237. if ( json.uvs[ i ].length ) nUvLayers ++;
  6238. }
  6239. for ( i = 0; i < nUvLayers; i++ ) {
  6240. geometry.faceVertexUvs[ i ] = [];
  6241. }
  6242. }
  6243. offset = 0;
  6244. zLength = vertices.length;
  6245. while ( offset < zLength ) {
  6246. vertex = new THREE.Vector3();
  6247. vertex.x = vertices[ offset ++ ] * scale;
  6248. vertex.y = vertices[ offset ++ ] * scale;
  6249. vertex.z = vertices[ offset ++ ] * scale;
  6250. geometry.vertices.push( vertex );
  6251. }
  6252. offset = 0;
  6253. zLength = faces.length;
  6254. while ( offset < zLength ) {
  6255. type = faces[ offset ++ ];
  6256. isQuad = isBitSet( type, 0 );
  6257. hasMaterial = isBitSet( type, 1 );
  6258. hasFaceVertexUv = isBitSet( type, 3 );
  6259. hasFaceNormal = isBitSet( type, 4 );
  6260. hasFaceVertexNormal = isBitSet( type, 5 );
  6261. hasFaceColor = isBitSet( type, 6 );
  6262. hasFaceVertexColor = isBitSet( type, 7 );
  6263. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  6264. if ( isQuad ) {
  6265. faceA = new THREE.Face3();
  6266. faceA.a = faces[ offset ];
  6267. faceA.b = faces[ offset + 1 ];
  6268. faceA.c = faces[ offset + 3 ];
  6269. faceB = new THREE.Face3();
  6270. faceB.a = faces[ offset + 1 ];
  6271. faceB.b = faces[ offset + 2 ];
  6272. faceB.c = faces[ offset + 3 ];
  6273. offset += 4;
  6274. if ( hasMaterial ) {
  6275. materialIndex = faces[ offset ++ ];
  6276. faceA.materialIndex = materialIndex;
  6277. faceB.materialIndex = materialIndex;
  6278. }
  6279. // to get face <=> uv index correspondence
  6280. fi = geometry.faces.length;
  6281. if ( hasFaceVertexUv ) {
  6282. for ( i = 0; i < nUvLayers; i++ ) {
  6283. uvLayer = json.uvs[ i ];
  6284. geometry.faceVertexUvs[ i ][ fi ] = [];
  6285. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  6286. for ( j = 0; j < 4; j ++ ) {
  6287. uvIndex = faces[ offset ++ ];
  6288. u = uvLayer[ uvIndex * 2 ];
  6289. v = uvLayer[ uvIndex * 2 + 1 ];
  6290. uv = new THREE.Vector2( u, v );
  6291. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  6292. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  6293. }
  6294. }
  6295. }
  6296. if ( hasFaceNormal ) {
  6297. normalIndex = faces[ offset ++ ] * 3;
  6298. faceA.normal.set(
  6299. normals[ normalIndex ++ ],
  6300. normals[ normalIndex ++ ],
  6301. normals[ normalIndex ]
  6302. );
  6303. faceB.normal.copy( faceA.normal );
  6304. }
  6305. if ( hasFaceVertexNormal ) {
  6306. for ( i = 0; i < 4; i++ ) {
  6307. normalIndex = faces[ offset ++ ] * 3;
  6308. normal = new THREE.Vector3(
  6309. normals[ normalIndex ++ ],
  6310. normals[ normalIndex ++ ],
  6311. normals[ normalIndex ]
  6312. );
  6313. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  6314. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  6315. }
  6316. }
  6317. if ( hasFaceColor ) {
  6318. colorIndex = faces[ offset ++ ];
  6319. hex = colors[ colorIndex ];
  6320. faceA.color.setHex( hex );
  6321. faceB.color.setHex( hex );
  6322. }
  6323. if ( hasFaceVertexColor ) {
  6324. for ( i = 0; i < 4; i++ ) {
  6325. colorIndex = faces[ offset ++ ];
  6326. hex = colors[ colorIndex ];
  6327. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  6328. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  6329. }
  6330. }
  6331. geometry.faces.push( faceA );
  6332. geometry.faces.push( faceB );
  6333. } else {
  6334. face = new THREE.Face3();
  6335. face.a = faces[ offset ++ ];
  6336. face.b = faces[ offset ++ ];
  6337. face.c = faces[ offset ++ ];
  6338. if ( hasMaterial ) {
  6339. materialIndex = faces[ offset ++ ];
  6340. face.materialIndex = materialIndex;
  6341. }
  6342. // to get face <=> uv index correspondence
  6343. fi = geometry.faces.length;
  6344. if ( hasFaceVertexUv ) {
  6345. for ( i = 0; i < nUvLayers; i++ ) {
  6346. uvLayer = json.uvs[ i ];
  6347. geometry.faceVertexUvs[ i ][ fi ] = [];
  6348. for ( j = 0; j < 3; j ++ ) {
  6349. uvIndex = faces[ offset ++ ];
  6350. u = uvLayer[ uvIndex * 2 ];
  6351. v = uvLayer[ uvIndex * 2 + 1 ];
  6352. uv = new THREE.Vector2( u, v );
  6353. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  6354. }
  6355. }
  6356. }
  6357. if ( hasFaceNormal ) {
  6358. normalIndex = faces[ offset ++ ] * 3;
  6359. face.normal.set(
  6360. normals[ normalIndex ++ ],
  6361. normals[ normalIndex ++ ],
  6362. normals[ normalIndex ]
  6363. );
  6364. }
  6365. if ( hasFaceVertexNormal ) {
  6366. for ( i = 0; i < 3; i++ ) {
  6367. normalIndex = faces[ offset ++ ] * 3;
  6368. normal = new THREE.Vector3(
  6369. normals[ normalIndex ++ ],
  6370. normals[ normalIndex ++ ],
  6371. normals[ normalIndex ]
  6372. );
  6373. face.vertexNormals.push( normal );
  6374. }
  6375. }
  6376. if ( hasFaceColor ) {
  6377. colorIndex = faces[ offset ++ ];
  6378. face.color.setHex( colors[ colorIndex ] );
  6379. }
  6380. if ( hasFaceVertexColor ) {
  6381. for ( i = 0; i < 3; i++ ) {
  6382. colorIndex = faces[ offset ++ ];
  6383. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  6384. }
  6385. }
  6386. geometry.faces.push( face );
  6387. }
  6388. }
  6389. };
  6390. function parseSkin() {
  6391. var i, l, x, y, z, w, a, b, c, d;
  6392. if ( json.skinWeights ) {
  6393. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  6394. x = json.skinWeights[ i ];
  6395. y = json.skinWeights[ i + 1 ];
  6396. z = 0;
  6397. w = 0;
  6398. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  6399. }
  6400. }
  6401. if ( json.skinIndices ) {
  6402. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  6403. a = json.skinIndices[ i ];
  6404. b = json.skinIndices[ i + 1 ];
  6405. c = 0;
  6406. d = 0;
  6407. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  6408. }
  6409. }
  6410. geometry.bones = json.bones;
  6411. geometry.animation = json.animation;
  6412. };
  6413. function parseMorphing( scale ) {
  6414. if ( json.morphTargets !== undefined ) {
  6415. var i, l, v, vl, dstVertices, srcVertices;
  6416. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  6417. geometry.morphTargets[ i ] = {};
  6418. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  6419. geometry.morphTargets[ i ].vertices = [];
  6420. dstVertices = geometry.morphTargets[ i ].vertices;
  6421. srcVertices = json.morphTargets [ i ].vertices;
  6422. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  6423. var vertex = new THREE.Vector3();
  6424. vertex.x = srcVertices[ v ] * scale;
  6425. vertex.y = srcVertices[ v + 1 ] * scale;
  6426. vertex.z = srcVertices[ v + 2 ] * scale;
  6427. dstVertices.push( vertex );
  6428. }
  6429. }
  6430. }
  6431. if ( json.morphColors !== undefined ) {
  6432. var i, l, c, cl, dstColors, srcColors, color;
  6433. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  6434. geometry.morphColors[ i ] = {};
  6435. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  6436. geometry.morphColors[ i ].colors = [];
  6437. dstColors = geometry.morphColors[ i ].colors;
  6438. srcColors = json.morphColors [ i ].colors;
  6439. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  6440. color = new THREE.Color( 0xffaa00 );
  6441. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  6442. dstColors.push( color );
  6443. }
  6444. }
  6445. }
  6446. };
  6447. if ( json.materials === undefined ) {
  6448. return { geometry: geometry };
  6449. } else {
  6450. var materials = this.initMaterials( json.materials, texturePath );
  6451. if ( this.needsTangents( materials ) ) {
  6452. geometry.computeTangents();
  6453. }
  6454. return { geometry: geometry, materials: materials };
  6455. }
  6456. };
  6457. /**
  6458. * @author mrdoob / http://mrdoob.com/
  6459. */
  6460. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  6461. var scope = this;
  6462. var loaded = 0, total = 0;
  6463. this.onLoad = onLoad;
  6464. this.onProgress = onProgress;
  6465. this.onError = onError;
  6466. this.itemStart = function ( url ) {
  6467. total ++;
  6468. };
  6469. this.itemEnd = function ( url ) {
  6470. loaded ++;
  6471. if ( scope.onProgress !== undefined ) {
  6472. scope.onProgress( url, loaded, total );
  6473. }
  6474. if ( loaded === total && scope.onLoad !== undefined ) {
  6475. scope.onLoad();
  6476. }
  6477. };
  6478. };
  6479. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  6480. /**
  6481. * @author mrdoob / http://mrdoob.com/
  6482. */
  6483. THREE.BufferGeometryLoader = function ( manager ) {
  6484. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6485. };
  6486. THREE.BufferGeometryLoader.prototype = {
  6487. constructor: THREE.BufferGeometryLoader,
  6488. load: function ( url, onLoad, onProgress, onError ) {
  6489. var scope = this;
  6490. var loader = new THREE.XHRLoader();
  6491. loader.setCrossOrigin( this.crossOrigin );
  6492. loader.load( url, function ( text ) {
  6493. onLoad( scope.parse( JSON.parse( text ) ) );
  6494. } );
  6495. },
  6496. setCrossOrigin: function ( value ) {
  6497. this.crossOrigin = value;
  6498. },
  6499. parse: function ( json ) {
  6500. var geometry = new THREE.BufferGeometry();
  6501. var attributes = json.attributes;
  6502. var offsets = json.offsets;
  6503. var boundingSphere = json.boundingSphere;
  6504. for ( var key in attributes ) {
  6505. var attribute = attributes[ key ];
  6506. geometry.attributes[ key ] = {
  6507. itemSize: attribute.itemSize,
  6508. array: new self[ attribute.type ]( attribute.array )
  6509. }
  6510. }
  6511. if ( offsets !== undefined ) {
  6512. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  6513. }
  6514. if ( boundingSphere !== undefined ) {
  6515. geometry.boundingSphere = new THREE.Sphere( undefined, boundingSphere.radius );
  6516. }
  6517. return geometry;
  6518. }
  6519. };
  6520. /**
  6521. * @author mrdoob / http://mrdoob.com/
  6522. */
  6523. THREE.GeometryLoader = function ( manager ) {
  6524. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6525. };
  6526. THREE.GeometryLoader.prototype = {
  6527. constructor: THREE.GeometryLoader,
  6528. load: function ( url, onLoad, onProgress, onError ) {
  6529. var scope = this;
  6530. var loader = new THREE.XHRLoader();
  6531. loader.setCrossOrigin( this.crossOrigin );
  6532. loader.load( url, function ( text ) {
  6533. onLoad( scope.parse( JSON.parse( text ) ) );
  6534. } );
  6535. },
  6536. setCrossOrigin: function ( value ) {
  6537. this.crossOrigin = value;
  6538. },
  6539. parse: function ( json ) {
  6540. }
  6541. };
  6542. /**
  6543. * @author mrdoob / http://mrdoob.com/
  6544. */
  6545. THREE.MaterialLoader = function ( manager ) {
  6546. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6547. };
  6548. THREE.MaterialLoader.prototype = {
  6549. constructor: THREE.MaterialLoader,
  6550. load: function ( url, onLoad, onProgress, onError ) {
  6551. var scope = this;
  6552. var loader = new THREE.XHRLoader();
  6553. loader.setCrossOrigin( this.crossOrigin );
  6554. loader.load( url, function ( text ) {
  6555. onLoad( scope.parse( JSON.parse( text ) ) );
  6556. } );
  6557. },
  6558. setCrossOrigin: function ( value ) {
  6559. this.crossOrigin = value;
  6560. },
  6561. parse: function ( json ) {
  6562. var material = new THREE[ json.type ];
  6563. if ( json.color !== undefined ) material.color.setHex( json.color );
  6564. if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient );
  6565. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  6566. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  6567. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  6568. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  6569. if ( json.blending !== undefined ) material.blending = json.blending;
  6570. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  6571. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  6572. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  6573. if ( json.materials !== undefined ) {
  6574. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  6575. material.materials.push( this.parse( json.materials[ i ] ) );
  6576. }
  6577. }
  6578. return material;
  6579. }
  6580. };
  6581. /**
  6582. * @author mrdoob / http://mrdoob.com/
  6583. */
  6584. THREE.ObjectLoader = function ( manager ) {
  6585. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6586. };
  6587. THREE.ObjectLoader.prototype = {
  6588. constructor: THREE.ObjectLoader,
  6589. load: function ( url, onLoad, onProgress, onError ) {
  6590. var scope = this;
  6591. var loader = new THREE.XHRLoader( scope.manager );
  6592. loader.setCrossOrigin( this.crossOrigin );
  6593. loader.load( url, function ( text ) {
  6594. onLoad( scope.parse( JSON.parse( text ) ) );
  6595. } );
  6596. },
  6597. setCrossOrigin: function ( value ) {
  6598. this.crossOrigin = value;
  6599. },
  6600. parse: function ( json ) {
  6601. var geometries = this.parseGeometries( json.geometries );
  6602. var materials = this.parseMaterials( json.materials );
  6603. var object = this.parseObject( json.object, geometries, materials );
  6604. return object;
  6605. },
  6606. parseGeometries: function ( json ) {
  6607. var geometries = {};
  6608. if ( json !== undefined ) {
  6609. var geometryLoader = new THREE.JSONLoader();
  6610. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  6611. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6612. var geometry;
  6613. var data = json[ i ];
  6614. switch ( data.type ) {
  6615. case 'PlaneGeometry':
  6616. geometry = new THREE.PlaneGeometry(
  6617. data.width,
  6618. data.height,
  6619. data.widthSegments,
  6620. data.heightSegments
  6621. );
  6622. break;
  6623. case 'CubeGeometry':
  6624. geometry = new THREE.CubeGeometry(
  6625. data.width,
  6626. data.height,
  6627. data.depth,
  6628. data.widthSegments,
  6629. data.heightSegments,
  6630. data.depthSegments
  6631. );
  6632. break;
  6633. case 'CylinderGeometry':
  6634. geometry = new THREE.CylinderGeometry(
  6635. data.radiusTop,
  6636. data.radiusBottom,
  6637. data.height,
  6638. data.radiusSegments,
  6639. data.heightSegments,
  6640. data.openEnded
  6641. );
  6642. break;
  6643. case 'SphereGeometry':
  6644. geometry = new THREE.SphereGeometry(
  6645. data.radius,
  6646. data.widthSegments,
  6647. data.heightSegments,
  6648. data.phiStart,
  6649. data.phiLength,
  6650. data.thetaStart,
  6651. data.thetaLength
  6652. );
  6653. break;
  6654. case 'IcosahedronGeometry':
  6655. geometry = new THREE.IcosahedronGeometry(
  6656. data.radius,
  6657. data.detail
  6658. );
  6659. break;
  6660. case 'TorusGeometry':
  6661. geometry = new THREE.TorusGeometry(
  6662. data.radius,
  6663. data.tube,
  6664. data.radialSegments,
  6665. data.tubularSegments,
  6666. data.arc
  6667. );
  6668. break;
  6669. case 'TorusKnotGeometry':
  6670. geometry = new THREE.TorusKnotGeometry(
  6671. data.radius,
  6672. data.tube,
  6673. data.radialSegments,
  6674. data.tubularSegments,
  6675. data.p,
  6676. data.q,
  6677. data.heightScale
  6678. );
  6679. break;
  6680. case 'BufferGeometry':
  6681. geometry = bufferGeometryLoader.parse( data.data );
  6682. break;
  6683. case 'Geometry':
  6684. geometry = geometryLoader.parse( data.data ).geometry;
  6685. break;
  6686. }
  6687. geometry.uuid = data.uuid;
  6688. if ( data.name !== undefined ) geometry.name = data.name;
  6689. geometries[ data.uuid ] = geometry;
  6690. }
  6691. }
  6692. return geometries;
  6693. },
  6694. parseMaterials: function ( json ) {
  6695. var materials = {};
  6696. if ( json !== undefined ) {
  6697. var loader = new THREE.MaterialLoader();
  6698. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6699. var data = json[ i ];
  6700. var material = loader.parse( data );
  6701. material.uuid = data.uuid;
  6702. if ( data.name !== undefined ) material.name = data.name;
  6703. materials[ data.uuid ] = material;
  6704. }
  6705. }
  6706. return materials;
  6707. },
  6708. parseObject: function () {
  6709. var matrix = new THREE.Matrix4();
  6710. return function ( data, geometries, materials ) {
  6711. var object;
  6712. switch ( data.type ) {
  6713. case 'Scene':
  6714. object = new THREE.Scene();
  6715. break;
  6716. case 'PerspectiveCamera':
  6717. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  6718. break;
  6719. case 'OrthographicCamera':
  6720. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  6721. break;
  6722. case 'AmbientLight':
  6723. object = new THREE.AmbientLight( data.color );
  6724. break;
  6725. case 'DirectionalLight':
  6726. object = new THREE.DirectionalLight( data.color, data.intensity );
  6727. break;
  6728. case 'PointLight':
  6729. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  6730. break;
  6731. case 'SpotLight':
  6732. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  6733. break;
  6734. case 'HemisphereLight':
  6735. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  6736. break;
  6737. case 'Mesh':
  6738. var geometry = geometries[ data.geometry ];
  6739. var material = materials[ data.material ];
  6740. if ( geometry === undefined ) {
  6741. console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry );
  6742. }
  6743. if ( material === undefined ) {
  6744. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  6745. }
  6746. object = new THREE.Mesh( geometry, material );
  6747. break;
  6748. default:
  6749. object = new THREE.Object3D();
  6750. }
  6751. object.uuid = data.uuid;
  6752. if ( data.name !== undefined ) object.name = data.name;
  6753. if ( data.matrix !== undefined ) {
  6754. matrix.fromArray( data.matrix );
  6755. matrix.decompose( object.position, object.quaternion, object.scale );
  6756. } else {
  6757. if ( data.position !== undefined ) object.position.fromArray( data.position );
  6758. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  6759. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  6760. }
  6761. if ( data.visible !== undefined ) object.visible = data.visible;
  6762. if ( data.userData !== undefined ) object.userData = data.userData;
  6763. if ( data.children !== undefined ) {
  6764. for ( var child in data.children ) {
  6765. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  6766. }
  6767. }
  6768. return object;
  6769. }
  6770. }()
  6771. };
  6772. /**
  6773. * @author alteredq / http://alteredqualia.com/
  6774. */
  6775. THREE.SceneLoader = function () {
  6776. this.onLoadStart = function () {};
  6777. this.onLoadProgress = function() {};
  6778. this.onLoadComplete = function () {};
  6779. this.callbackSync = function () {};
  6780. this.callbackProgress = function () {};
  6781. this.geometryHandlers = {};
  6782. this.hierarchyHandlers = {};
  6783. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  6784. };
  6785. THREE.SceneLoader.prototype = {
  6786. constructor: THREE.SceneLoader,
  6787. load: function ( url, onLoad, onProgress, onError ) {
  6788. var scope = this;
  6789. var loader = new THREE.XHRLoader( scope.manager );
  6790. loader.setCrossOrigin( this.crossOrigin );
  6791. loader.load( url, function ( text ) {
  6792. scope.parse( JSON.parse( text ), onLoad, url );
  6793. } );
  6794. },
  6795. setCrossOrigin: function ( value ) {
  6796. this.crossOrigin = value;
  6797. },
  6798. addGeometryHandler: function ( typeID, loaderClass ) {
  6799. this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass };
  6800. },
  6801. addHierarchyHandler: function ( typeID, loaderClass ) {
  6802. this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass };
  6803. },
  6804. parse: function ( json, callbackFinished, url ) {
  6805. var scope = this;
  6806. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  6807. var geometry, material, camera, fog,
  6808. texture, images, color,
  6809. light, hex, intensity,
  6810. counter_models, counter_textures,
  6811. total_models, total_textures,
  6812. result;
  6813. var target_array = [];
  6814. var data = json;
  6815. // async geometry loaders
  6816. for ( var typeID in this.geometryHandlers ) {
  6817. var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ];
  6818. this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  6819. }
  6820. // async hierachy loaders
  6821. for ( var typeID in this.hierarchyHandlers ) {
  6822. var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ];
  6823. this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  6824. }
  6825. counter_models = 0;
  6826. counter_textures = 0;
  6827. result = {
  6828. scene: new THREE.Scene(),
  6829. geometries: {},
  6830. face_materials: {},
  6831. materials: {},
  6832. textures: {},
  6833. objects: {},
  6834. cameras: {},
  6835. lights: {},
  6836. fogs: {},
  6837. empties: {},
  6838. groups: {}
  6839. };
  6840. if ( data.transform ) {
  6841. var position = data.transform.position,
  6842. rotation = data.transform.rotation,
  6843. scale = data.transform.scale;
  6844. if ( position ) {
  6845. result.scene.position.fromArray( position );
  6846. }
  6847. if ( rotation ) {
  6848. result.scene.rotation.fromArray( rotation );
  6849. }
  6850. if ( scale ) {
  6851. result.scene.scale.fromArray( scale );
  6852. }
  6853. if ( position || rotation || scale ) {
  6854. result.scene.updateMatrix();
  6855. result.scene.updateMatrixWorld();
  6856. }
  6857. }
  6858. function get_url( source_url, url_type ) {
  6859. if ( url_type == "relativeToHTML" ) {
  6860. return source_url;
  6861. } else {
  6862. return urlBase + "/" + source_url;
  6863. }
  6864. };
  6865. // toplevel loader function, delegates to handle_children
  6866. function handle_objects() {
  6867. handle_children( result.scene, data.objects );
  6868. }
  6869. // handle all the children from the loaded json and attach them to given parent
  6870. function handle_children( parent, children ) {
  6871. var mat, dst, pos, rot, scl, quat;
  6872. for ( var objID in children ) {
  6873. // check by id if child has already been handled,
  6874. // if not, create new object
  6875. var object = result.objects[ objID ];
  6876. var objJSON = children[ objID ];
  6877. if ( object === undefined ) {
  6878. // meshes
  6879. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  6880. if ( objJSON.loading === undefined ) {
  6881. var reservedTypes = {
  6882. "type": 1, "url": 1, "material": 1,
  6883. "position": 1, "rotation": 1, "scale" : 1,
  6884. "visible": 1, "children": 1, "userData": 1,
  6885. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
  6886. };
  6887. var loaderParameters = {};
  6888. for ( var parType in objJSON ) {
  6889. if ( ! ( parType in reservedTypes ) ) {
  6890. loaderParameters[ parType ] = objJSON[ parType ];
  6891. }
  6892. }
  6893. material = result.materials[ objJSON.material ];
  6894. objJSON.loading = true;
  6895. var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
  6896. // ColladaLoader
  6897. if ( loader.options ) {
  6898. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  6899. // UTF8Loader
  6900. // OBJLoader
  6901. } else {
  6902. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  6903. }
  6904. }
  6905. } else if ( objJSON.geometry !== undefined ) {
  6906. geometry = result.geometries[ objJSON.geometry ];
  6907. // geometry already loaded
  6908. if ( geometry ) {
  6909. var needsTangents = false;
  6910. material = result.materials[ objJSON.material ];
  6911. needsTangents = material instanceof THREE.ShaderMaterial;
  6912. pos = objJSON.position;
  6913. rot = objJSON.rotation;
  6914. scl = objJSON.scale;
  6915. mat = objJSON.matrix;
  6916. quat = objJSON.quaternion;
  6917. // use materials from the model file
  6918. // if there is no material specified in the object
  6919. if ( ! objJSON.material ) {
  6920. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6921. }
  6922. // use materials from the model file
  6923. // if there is just empty face material
  6924. // (must create new material as each model has its own face material)
  6925. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  6926. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6927. }
  6928. if ( material instanceof THREE.MeshFaceMaterial ) {
  6929. for ( var i = 0; i < material.materials.length; i ++ ) {
  6930. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  6931. }
  6932. }
  6933. if ( needsTangents ) {
  6934. geometry.computeTangents();
  6935. }
  6936. if ( objJSON.skin ) {
  6937. object = new THREE.SkinnedMesh( geometry, material );
  6938. } else if ( objJSON.morph ) {
  6939. object = new THREE.MorphAnimMesh( geometry, material );
  6940. if ( objJSON.duration !== undefined ) {
  6941. object.duration = objJSON.duration;
  6942. }
  6943. if ( objJSON.time !== undefined ) {
  6944. object.time = objJSON.time;
  6945. }
  6946. if ( objJSON.mirroredLoop !== undefined ) {
  6947. object.mirroredLoop = objJSON.mirroredLoop;
  6948. }
  6949. if ( material.morphNormals ) {
  6950. geometry.computeMorphNormals();
  6951. }
  6952. } else {
  6953. object = new THREE.Mesh( geometry, material );
  6954. }
  6955. object.name = objID;
  6956. if ( mat ) {
  6957. object.matrixAutoUpdate = false;
  6958. object.matrix.set(
  6959. mat[0], mat[1], mat[2], mat[3],
  6960. mat[4], mat[5], mat[6], mat[7],
  6961. mat[8], mat[9], mat[10], mat[11],
  6962. mat[12], mat[13], mat[14], mat[15]
  6963. );
  6964. } else {
  6965. object.position.fromArray( pos );
  6966. if ( quat ) {
  6967. object.quaternion.fromArray( quat );
  6968. } else {
  6969. object.rotation.fromArray( rot );
  6970. }
  6971. object.scale.fromArray( scl );
  6972. }
  6973. object.visible = objJSON.visible;
  6974. object.castShadow = objJSON.castShadow;
  6975. object.receiveShadow = objJSON.receiveShadow;
  6976. parent.add( object );
  6977. result.objects[ objID ] = object;
  6978. }
  6979. // lights
  6980. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  6981. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  6982. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  6983. if ( objJSON.type === "DirectionalLight" ) {
  6984. pos = objJSON.direction;
  6985. light = new THREE.DirectionalLight( hex, intensity );
  6986. light.position.fromArray( pos );
  6987. if ( objJSON.target ) {
  6988. target_array.push( { "object": light, "targetName" : objJSON.target } );
  6989. // kill existing default target
  6990. // otherwise it gets added to scene when parent gets added
  6991. light.target = null;
  6992. }
  6993. } else if ( objJSON.type === "PointLight" ) {
  6994. pos = objJSON.position;
  6995. dst = objJSON.distance;
  6996. light = new THREE.PointLight( hex, intensity, dst );
  6997. light.position.fromArray( pos );
  6998. } else if ( objJSON.type === "AmbientLight" ) {
  6999. light = new THREE.AmbientLight( hex );
  7000. }
  7001. parent.add( light );
  7002. light.name = objID;
  7003. result.lights[ objID ] = light;
  7004. result.objects[ objID ] = light;
  7005. // cameras
  7006. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  7007. pos = objJSON.position;
  7008. rot = objJSON.rotation;
  7009. quat = objJSON.quaternion;
  7010. if ( objJSON.type === "PerspectiveCamera" ) {
  7011. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  7012. } else if ( objJSON.type === "OrthographicCamera" ) {
  7013. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  7014. }
  7015. camera.name = objID;
  7016. camera.position.fromArray( pos );
  7017. if ( quat !== undefined ) {
  7018. camera.quaternion.fromArray( quat );
  7019. } else if ( rot !== undefined ) {
  7020. camera.rotation.fromArray( rot );
  7021. }
  7022. parent.add( camera );
  7023. result.cameras[ objID ] = camera;
  7024. result.objects[ objID ] = camera;
  7025. // pure Object3D
  7026. } else {
  7027. pos = objJSON.position;
  7028. rot = objJSON.rotation;
  7029. scl = objJSON.scale;
  7030. quat = objJSON.quaternion;
  7031. object = new THREE.Object3D();
  7032. object.name = objID;
  7033. object.position.fromArray( pos );
  7034. if ( quat ) {
  7035. object.quaternion.fromArray( quat );
  7036. } else {
  7037. object.rotation.fromArray( rot );
  7038. }
  7039. object.scale.fromArray( scl );
  7040. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  7041. parent.add( object );
  7042. result.objects[ objID ] = object;
  7043. result.empties[ objID ] = object;
  7044. }
  7045. if ( object ) {
  7046. if ( objJSON.userData !== undefined ) {
  7047. for ( var key in objJSON.userData ) {
  7048. var value = objJSON.userData[ key ];
  7049. object.userData[ key ] = value;
  7050. }
  7051. }
  7052. if ( objJSON.groups !== undefined ) {
  7053. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  7054. var groupID = objJSON.groups[ i ];
  7055. if ( result.groups[ groupID ] === undefined ) {
  7056. result.groups[ groupID ] = [];
  7057. }
  7058. result.groups[ groupID ].push( objID );
  7059. }
  7060. }
  7061. }
  7062. }
  7063. if ( object !== undefined && objJSON.children !== undefined ) {
  7064. handle_children( object, objJSON.children );
  7065. }
  7066. }
  7067. };
  7068. function handle_mesh( geo, mat, id ) {
  7069. result.geometries[ id ] = geo;
  7070. result.face_materials[ id ] = mat;
  7071. handle_objects();
  7072. };
  7073. function handle_hierarchy( node, id, parent, material, obj ) {
  7074. var p = obj.position;
  7075. var r = obj.rotation;
  7076. var q = obj.quaternion;
  7077. var s = obj.scale;
  7078. node.position.fromArray( p );
  7079. if ( q ) {
  7080. node.quaternion.fromArray( q );
  7081. } else {
  7082. node.rotation.fromArray( r );
  7083. }
  7084. node.scale.fromArray( s );
  7085. // override children materials
  7086. // if object material was specified in JSON explicitly
  7087. if ( material ) {
  7088. node.traverse( function ( child ) {
  7089. child.material = material;
  7090. } );
  7091. }
  7092. // override children visibility
  7093. // with root node visibility as specified in JSON
  7094. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  7095. node.traverse( function ( child ) {
  7096. child.visible = visible;
  7097. } );
  7098. parent.add( node );
  7099. node.name = id;
  7100. result.objects[ id ] = node;
  7101. handle_objects();
  7102. };
  7103. function create_callback_geometry( id ) {
  7104. return function ( geo, mat ) {
  7105. geo.name = id;
  7106. handle_mesh( geo, mat, id );
  7107. counter_models -= 1;
  7108. scope.onLoadComplete();
  7109. async_callback_gate();
  7110. }
  7111. };
  7112. function create_callback_hierachy( id, parent, material, obj ) {
  7113. return function ( event ) {
  7114. var result;
  7115. // loaders which use EventDispatcher
  7116. if ( event.content ) {
  7117. result = event.content;
  7118. // ColladaLoader
  7119. } else if ( event.dae ) {
  7120. result = event.scene;
  7121. // UTF8Loader
  7122. } else {
  7123. result = event;
  7124. }
  7125. handle_hierarchy( result, id, parent, material, obj );
  7126. counter_models -= 1;
  7127. scope.onLoadComplete();
  7128. async_callback_gate();
  7129. }
  7130. };
  7131. function create_callback_embed( id ) {
  7132. return function ( geo, mat ) {
  7133. geo.name = id;
  7134. result.geometries[ id ] = geo;
  7135. result.face_materials[ id ] = mat;
  7136. }
  7137. };
  7138. function async_callback_gate() {
  7139. var progress = {
  7140. totalModels : total_models,
  7141. totalTextures : total_textures,
  7142. loadedModels : total_models - counter_models,
  7143. loadedTextures : total_textures - counter_textures
  7144. };
  7145. scope.callbackProgress( progress, result );
  7146. scope.onLoadProgress();
  7147. if ( counter_models === 0 && counter_textures === 0 ) {
  7148. finalize();
  7149. callbackFinished( result );
  7150. }
  7151. };
  7152. function finalize() {
  7153. // take care of targets which could be asynchronously loaded objects
  7154. for ( var i = 0; i < target_array.length; i ++ ) {
  7155. var ta = target_array[ i ];
  7156. var target = result.objects[ ta.targetName ];
  7157. if ( target ) {
  7158. ta.object.target = target;
  7159. } else {
  7160. // if there was error and target of specified name doesn't exist in the scene file
  7161. // create instead dummy target
  7162. // (target must be added to scene explicitly as parent is already added)
  7163. ta.object.target = new THREE.Object3D();
  7164. result.scene.add( ta.object.target );
  7165. }
  7166. ta.object.target.userData.targetInverse = ta.object;
  7167. }
  7168. };
  7169. var callbackTexture = function ( count ) {
  7170. counter_textures -= count;
  7171. async_callback_gate();
  7172. scope.onLoadComplete();
  7173. };
  7174. // must use this instead of just directly calling callbackTexture
  7175. // because of closure in the calling context loop
  7176. var generateTextureCallback = function ( count ) {
  7177. return function () {
  7178. callbackTexture( count );
  7179. };
  7180. };
  7181. function traverse_json_hierarchy( objJSON, callback ) {
  7182. callback( objJSON );
  7183. if ( objJSON.children !== undefined ) {
  7184. for ( var objChildID in objJSON.children ) {
  7185. traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
  7186. }
  7187. }
  7188. };
  7189. // first go synchronous elements
  7190. // fogs
  7191. var fogID, fogJSON;
  7192. for ( fogID in data.fogs ) {
  7193. fogJSON = data.fogs[ fogID ];
  7194. if ( fogJSON.type === "linear" ) {
  7195. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  7196. } else if ( fogJSON.type === "exp2" ) {
  7197. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  7198. }
  7199. color = fogJSON.color;
  7200. fog.color.setRGB( color[0], color[1], color[2] );
  7201. result.fogs[ fogID ] = fog;
  7202. }
  7203. // now come potentially asynchronous elements
  7204. // geometries
  7205. // count how many geometries will be loaded asynchronously
  7206. var geoID, geoJSON;
  7207. for ( geoID in data.geometries ) {
  7208. geoJSON = data.geometries[ geoID ];
  7209. if ( geoJSON.type in this.geometryHandlers ) {
  7210. counter_models += 1;
  7211. scope.onLoadStart();
  7212. }
  7213. }
  7214. // count how many hierarchies will be loaded asynchronously
  7215. for ( var objID in data.objects ) {
  7216. traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
  7217. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7218. counter_models += 1;
  7219. scope.onLoadStart();
  7220. }
  7221. });
  7222. }
  7223. total_models = counter_models;
  7224. for ( geoID in data.geometries ) {
  7225. geoJSON = data.geometries[ geoID ];
  7226. if ( geoJSON.type === "cube" ) {
  7227. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  7228. geometry.name = geoID;
  7229. result.geometries[ geoID ] = geometry;
  7230. } else if ( geoJSON.type === "plane" ) {
  7231. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  7232. geometry.name = geoID;
  7233. result.geometries[ geoID ] = geometry;
  7234. } else if ( geoJSON.type === "sphere" ) {
  7235. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  7236. geometry.name = geoID;
  7237. result.geometries[ geoID ] = geometry;
  7238. } else if ( geoJSON.type === "cylinder" ) {
  7239. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  7240. geometry.name = geoID;
  7241. result.geometries[ geoID ] = geometry;
  7242. } else if ( geoJSON.type === "torus" ) {
  7243. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  7244. geometry.name = geoID;
  7245. result.geometries[ geoID ] = geometry;
  7246. } else if ( geoJSON.type === "icosahedron" ) {
  7247. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  7248. geometry.name = geoID;
  7249. result.geometries[ geoID ] = geometry;
  7250. } else if ( geoJSON.type in this.geometryHandlers ) {
  7251. var loaderParameters = {};
  7252. for ( var parType in geoJSON ) {
  7253. if ( parType !== "type" && parType !== "url" ) {
  7254. loaderParameters[ parType ] = geoJSON[ parType ];
  7255. }
  7256. }
  7257. var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ];
  7258. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  7259. } else if ( geoJSON.type === "embedded" ) {
  7260. var modelJson = data.embeds[ geoJSON.id ],
  7261. texture_path = "";
  7262. // pass metadata along to jsonLoader so it knows the format version
  7263. modelJson.metadata = data.metadata;
  7264. if ( modelJson ) {
  7265. var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ];
  7266. var model = jsonLoader.parse( modelJson, texture_path );
  7267. create_callback_embed( geoID )( model.geometry, model.materials );
  7268. }
  7269. }
  7270. }
  7271. // textures
  7272. // count how many textures will be loaded asynchronously
  7273. var textureID, textureJSON;
  7274. for ( textureID in data.textures ) {
  7275. textureJSON = data.textures[ textureID ];
  7276. if ( textureJSON.url instanceof Array ) {
  7277. counter_textures += textureJSON.url.length;
  7278. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  7279. scope.onLoadStart();
  7280. }
  7281. } else {
  7282. counter_textures += 1;
  7283. scope.onLoadStart();
  7284. }
  7285. }
  7286. total_textures = counter_textures;
  7287. for ( textureID in data.textures ) {
  7288. textureJSON = data.textures[ textureID ];
  7289. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  7290. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  7291. }
  7292. if ( textureJSON.url instanceof Array ) {
  7293. var count = textureJSON.url.length;
  7294. var url_array = [];
  7295. for( var i = 0; i < count; i ++ ) {
  7296. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  7297. }
  7298. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  7299. if ( isCompressed ) {
  7300. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7301. } else {
  7302. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7303. }
  7304. } else {
  7305. var isCompressed = /\.dds$/i.test( textureJSON.url );
  7306. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  7307. var textureCallback = generateTextureCallback( 1 );
  7308. if ( isCompressed ) {
  7309. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  7310. } else {
  7311. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  7312. }
  7313. if ( THREE[ textureJSON.minFilter ] !== undefined )
  7314. texture.minFilter = THREE[ textureJSON.minFilter ];
  7315. if ( THREE[ textureJSON.magFilter ] !== undefined )
  7316. texture.magFilter = THREE[ textureJSON.magFilter ];
  7317. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  7318. if ( textureJSON.repeat ) {
  7319. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  7320. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  7321. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  7322. }
  7323. if ( textureJSON.offset ) {
  7324. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  7325. }
  7326. // handle wrap after repeat so that default repeat can be overriden
  7327. if ( textureJSON.wrap ) {
  7328. var wrapMap = {
  7329. "repeat": THREE.RepeatWrapping,
  7330. "mirror": THREE.MirroredRepeatWrapping
  7331. }
  7332. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  7333. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  7334. }
  7335. }
  7336. result.textures[ textureID ] = texture;
  7337. }
  7338. // materials
  7339. var matID, matJSON;
  7340. var parID;
  7341. for ( matID in data.materials ) {
  7342. matJSON = data.materials[ matID ];
  7343. for ( parID in matJSON.parameters ) {
  7344. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  7345. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  7346. } else if ( parID === "shading" ) {
  7347. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  7348. } else if ( parID === "side" ) {
  7349. if ( matJSON.parameters[ parID ] == "double" ) {
  7350. matJSON.parameters[ parID ] = THREE.DoubleSide;
  7351. } else if ( matJSON.parameters[ parID ] == "back" ) {
  7352. matJSON.parameters[ parID ] = THREE.BackSide;
  7353. } else {
  7354. matJSON.parameters[ parID ] = THREE.FrontSide;
  7355. }
  7356. } else if ( parID === "blending" ) {
  7357. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  7358. } else if ( parID === "combine" ) {
  7359. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  7360. } else if ( parID === "vertexColors" ) {
  7361. if ( matJSON.parameters[ parID ] == "face" ) {
  7362. matJSON.parameters[ parID ] = THREE.FaceColors;
  7363. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  7364. } else if ( matJSON.parameters[ parID ] ) {
  7365. matJSON.parameters[ parID ] = THREE.VertexColors;
  7366. }
  7367. } else if ( parID === "wrapRGB" ) {
  7368. var v3 = matJSON.parameters[ parID ];
  7369. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  7370. }
  7371. }
  7372. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  7373. matJSON.parameters.transparent = true;
  7374. }
  7375. if ( matJSON.parameters.normalMap ) {
  7376. var shader = THREE.ShaderLib[ "normalmap" ];
  7377. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  7378. var diffuse = matJSON.parameters.color;
  7379. var specular = matJSON.parameters.specular;
  7380. var ambient = matJSON.parameters.ambient;
  7381. var shininess = matJSON.parameters.shininess;
  7382. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  7383. if ( matJSON.parameters.normalScale ) {
  7384. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  7385. }
  7386. if ( matJSON.parameters.map ) {
  7387. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  7388. uniforms[ "enableDiffuse" ].value = true;
  7389. }
  7390. if ( matJSON.parameters.envMap ) {
  7391. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  7392. uniforms[ "enableReflection" ].value = true;
  7393. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  7394. }
  7395. if ( matJSON.parameters.lightMap ) {
  7396. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  7397. uniforms[ "enableAO" ].value = true;
  7398. }
  7399. if ( matJSON.parameters.specularMap ) {
  7400. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  7401. uniforms[ "enableSpecular" ].value = true;
  7402. }
  7403. if ( matJSON.parameters.displacementMap ) {
  7404. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  7405. uniforms[ "enableDisplacement" ].value = true;
  7406. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  7407. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  7408. }
  7409. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  7410. uniforms[ "uSpecularColor" ].value.setHex( specular );
  7411. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  7412. uniforms[ "uShininess" ].value = shininess;
  7413. if ( matJSON.parameters.opacity ) {
  7414. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  7415. }
  7416. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  7417. material = new THREE.ShaderMaterial( parameters );
  7418. } else {
  7419. material = new THREE[ matJSON.type ]( matJSON.parameters );
  7420. }
  7421. material.name = matID;
  7422. result.materials[ matID ] = material;
  7423. }
  7424. // second pass through all materials to initialize MeshFaceMaterials
  7425. // that could be referring to other materials out of order
  7426. for ( matID in data.materials ) {
  7427. matJSON = data.materials[ matID ];
  7428. if ( matJSON.parameters.materials ) {
  7429. var materialArray = [];
  7430. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  7431. var label = matJSON.parameters.materials[ i ];
  7432. materialArray.push( result.materials[ label ] );
  7433. }
  7434. result.materials[ matID ].materials = materialArray;
  7435. }
  7436. }
  7437. // objects ( synchronous init of procedural primitives )
  7438. handle_objects();
  7439. // defaults
  7440. if ( result.cameras && data.defaults.camera ) {
  7441. result.currentCamera = result.cameras[ data.defaults.camera ];
  7442. }
  7443. if ( result.fogs && data.defaults.fog ) {
  7444. result.scene.fog = result.fogs[ data.defaults.fog ];
  7445. }
  7446. // synchronous callback
  7447. scope.callbackSync( result );
  7448. // just in case there are no async elements
  7449. async_callback_gate();
  7450. }
  7451. }
  7452. /**
  7453. * @author mrdoob / http://mrdoob.com/
  7454. */
  7455. THREE.TextureLoader = function ( manager ) {
  7456. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7457. };
  7458. THREE.TextureLoader.prototype = {
  7459. constructor: THREE.TextureLoader,
  7460. load: function ( url, onLoad, onProgress, onError ) {
  7461. var scope = this;
  7462. var loader = new THREE.ImageLoader( scope.manager );
  7463. loader.setCrossOrigin( this.crossOrigin );
  7464. loader.load( url, function ( image ) {
  7465. var texture = new THREE.Texture( image );
  7466. texture.needsUpdate = true;
  7467. if ( onLoad !== undefined ) {
  7468. onLoad( texture );
  7469. }
  7470. } );
  7471. },
  7472. setCrossOrigin: function ( value ) {
  7473. this.crossOrigin = value;
  7474. }
  7475. };
  7476. /**
  7477. * @author mrdoob / http://mrdoob.com/
  7478. * @author alteredq / http://alteredqualia.com/
  7479. */
  7480. THREE.Material = function () {
  7481. this.id = THREE.MaterialIdCount ++;
  7482. this.uuid = THREE.Math.generateUUID();
  7483. this.name = '';
  7484. this.side = THREE.FrontSide;
  7485. this.opacity = 1;
  7486. this.transparent = false;
  7487. this.blending = THREE.NormalBlending;
  7488. this.blendSrc = THREE.SrcAlphaFactor;
  7489. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  7490. this.blendEquation = THREE.AddEquation;
  7491. this.depthTest = true;
  7492. this.depthWrite = true;
  7493. this.polygonOffset = false;
  7494. this.polygonOffsetFactor = 0;
  7495. this.polygonOffsetUnits = 0;
  7496. this.alphaTest = 0;
  7497. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  7498. this.visible = true;
  7499. this.needsUpdate = true;
  7500. };
  7501. THREE.Material.prototype = {
  7502. constructor: THREE.Material,
  7503. setValues: function ( values ) {
  7504. if ( values === undefined ) return;
  7505. for ( var key in values ) {
  7506. var newValue = values[ key ];
  7507. if ( newValue === undefined ) {
  7508. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  7509. continue;
  7510. }
  7511. if ( key in this ) {
  7512. var currentValue = this[ key ];
  7513. if ( currentValue instanceof THREE.Color ) {
  7514. currentValue.set( newValue );
  7515. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  7516. currentValue.copy( newValue );
  7517. } else if ( key == 'overdraw') {
  7518. // ensure overdraw is backwards-compatable with legacy boolean type
  7519. this[ key ] = Number(newValue);
  7520. } else {
  7521. this[ key ] = newValue;
  7522. }
  7523. }
  7524. }
  7525. },
  7526. clone: function ( material ) {
  7527. if ( material === undefined ) material = new THREE.Material();
  7528. material.name = this.name;
  7529. material.side = this.side;
  7530. material.opacity = this.opacity;
  7531. material.transparent = this.transparent;
  7532. material.blending = this.blending;
  7533. material.blendSrc = this.blendSrc;
  7534. material.blendDst = this.blendDst;
  7535. material.blendEquation = this.blendEquation;
  7536. material.depthTest = this.depthTest;
  7537. material.depthWrite = this.depthWrite;
  7538. material.polygonOffset = this.polygonOffset;
  7539. material.polygonOffsetFactor = this.polygonOffsetFactor;
  7540. material.polygonOffsetUnits = this.polygonOffsetUnits;
  7541. material.alphaTest = this.alphaTest;
  7542. material.overdraw = this.overdraw;
  7543. material.visible = this.visible;
  7544. return material;
  7545. },
  7546. dispose: function () {
  7547. this.dispatchEvent( { type: 'dispose' } );
  7548. }
  7549. };
  7550. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  7551. THREE.MaterialIdCount = 0;
  7552. /**
  7553. * @author mrdoob / http://mrdoob.com/
  7554. * @author alteredq / http://alteredqualia.com/
  7555. *
  7556. * parameters = {
  7557. * color: <hex>,
  7558. * opacity: <float>,
  7559. *
  7560. * blending: THREE.NormalBlending,
  7561. * depthTest: <bool>,
  7562. * depthWrite: <bool>,
  7563. *
  7564. * linewidth: <float>,
  7565. * linecap: "round",
  7566. * linejoin: "round",
  7567. *
  7568. * vertexColors: <bool>
  7569. *
  7570. * fog: <bool>
  7571. * }
  7572. */
  7573. THREE.LineBasicMaterial = function ( parameters ) {
  7574. THREE.Material.call( this );
  7575. this.color = new THREE.Color( 0xffffff );
  7576. this.linewidth = 1;
  7577. this.linecap = 'round';
  7578. this.linejoin = 'round';
  7579. this.vertexColors = false;
  7580. this.fog = true;
  7581. this.setValues( parameters );
  7582. };
  7583. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7584. THREE.LineBasicMaterial.prototype.clone = function () {
  7585. var material = new THREE.LineBasicMaterial();
  7586. THREE.Material.prototype.clone.call( this, material );
  7587. material.color.copy( this.color );
  7588. material.linewidth = this.linewidth;
  7589. material.linecap = this.linecap;
  7590. material.linejoin = this.linejoin;
  7591. material.vertexColors = this.vertexColors;
  7592. material.fog = this.fog;
  7593. return material;
  7594. };
  7595. /**
  7596. * @author alteredq / http://alteredqualia.com/
  7597. *
  7598. * parameters = {
  7599. * color: <hex>,
  7600. * opacity: <float>,
  7601. *
  7602. * blending: THREE.NormalBlending,
  7603. * depthTest: <bool>,
  7604. * depthWrite: <bool>,
  7605. *
  7606. * linewidth: <float>,
  7607. *
  7608. * scale: <float>,
  7609. * dashSize: <float>,
  7610. * gapSize: <float>,
  7611. *
  7612. * vertexColors: <bool>
  7613. *
  7614. * fog: <bool>
  7615. * }
  7616. */
  7617. THREE.LineDashedMaterial = function ( parameters ) {
  7618. THREE.Material.call( this );
  7619. this.color = new THREE.Color( 0xffffff );
  7620. this.linewidth = 1;
  7621. this.scale = 1;
  7622. this.dashSize = 3;
  7623. this.gapSize = 1;
  7624. this.vertexColors = false;
  7625. this.fog = true;
  7626. this.setValues( parameters );
  7627. };
  7628. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  7629. THREE.LineDashedMaterial.prototype.clone = function () {
  7630. var material = new THREE.LineDashedMaterial();
  7631. THREE.Material.prototype.clone.call( this, material );
  7632. material.color.copy( this.color );
  7633. material.linewidth = this.linewidth;
  7634. material.scale = this.scale;
  7635. material.dashSize = this.dashSize;
  7636. material.gapSize = this.gapSize;
  7637. material.vertexColors = this.vertexColors;
  7638. material.fog = this.fog;
  7639. return material;
  7640. };
  7641. /**
  7642. * @author mrdoob / http://mrdoob.com/
  7643. * @author alteredq / http://alteredqualia.com/
  7644. *
  7645. * parameters = {
  7646. * color: <hex>,
  7647. * opacity: <float>,
  7648. * map: new THREE.Texture( <Image> ),
  7649. *
  7650. * lightMap: new THREE.Texture( <Image> ),
  7651. *
  7652. * specularMap: new THREE.Texture( <Image> ),
  7653. *
  7654. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7655. * combine: THREE.Multiply,
  7656. * reflectivity: <float>,
  7657. * refractionRatio: <float>,
  7658. *
  7659. * shading: THREE.SmoothShading,
  7660. * blending: THREE.NormalBlending,
  7661. * depthTest: <bool>,
  7662. * depthWrite: <bool>,
  7663. *
  7664. * wireframe: <boolean>,
  7665. * wireframeLinewidth: <float>,
  7666. *
  7667. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7668. *
  7669. * skinning: <bool>,
  7670. * morphTargets: <bool>,
  7671. *
  7672. * fog: <bool>
  7673. * }
  7674. */
  7675. THREE.MeshBasicMaterial = function ( parameters ) {
  7676. THREE.Material.call( this );
  7677. this.color = new THREE.Color( 0xffffff ); // emissive
  7678. this.map = null;
  7679. this.lightMap = null;
  7680. this.specularMap = null;
  7681. this.envMap = null;
  7682. this.combine = THREE.MultiplyOperation;
  7683. this.reflectivity = 1;
  7684. this.refractionRatio = 0.98;
  7685. this.fog = true;
  7686. this.shading = THREE.SmoothShading;
  7687. this.wireframe = false;
  7688. this.wireframeLinewidth = 1;
  7689. this.wireframeLinecap = 'round';
  7690. this.wireframeLinejoin = 'round';
  7691. this.vertexColors = THREE.NoColors;
  7692. this.skinning = false;
  7693. this.morphTargets = false;
  7694. this.setValues( parameters );
  7695. };
  7696. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7697. THREE.MeshBasicMaterial.prototype.clone = function () {
  7698. var material = new THREE.MeshBasicMaterial();
  7699. THREE.Material.prototype.clone.call( this, material );
  7700. material.color.copy( this.color );
  7701. material.map = this.map;
  7702. material.lightMap = this.lightMap;
  7703. material.specularMap = this.specularMap;
  7704. material.envMap = this.envMap;
  7705. material.combine = this.combine;
  7706. material.reflectivity = this.reflectivity;
  7707. material.refractionRatio = this.refractionRatio;
  7708. material.fog = this.fog;
  7709. material.shading = this.shading;
  7710. material.wireframe = this.wireframe;
  7711. material.wireframeLinewidth = this.wireframeLinewidth;
  7712. material.wireframeLinecap = this.wireframeLinecap;
  7713. material.wireframeLinejoin = this.wireframeLinejoin;
  7714. material.vertexColors = this.vertexColors;
  7715. material.skinning = this.skinning;
  7716. material.morphTargets = this.morphTargets;
  7717. return material;
  7718. };
  7719. /**
  7720. * @author mrdoob / http://mrdoob.com/
  7721. * @author alteredq / http://alteredqualia.com/
  7722. *
  7723. * parameters = {
  7724. * color: <hex>,
  7725. * ambient: <hex>,
  7726. * emissive: <hex>,
  7727. * opacity: <float>,
  7728. *
  7729. * map: new THREE.Texture( <Image> ),
  7730. *
  7731. * lightMap: new THREE.Texture( <Image> ),
  7732. *
  7733. * specularMap: new THREE.Texture( <Image> ),
  7734. *
  7735. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7736. * combine: THREE.Multiply,
  7737. * reflectivity: <float>,
  7738. * refractionRatio: <float>,
  7739. *
  7740. * shading: THREE.SmoothShading,
  7741. * blending: THREE.NormalBlending,
  7742. * depthTest: <bool>,
  7743. * depthWrite: <bool>,
  7744. *
  7745. * wireframe: <boolean>,
  7746. * wireframeLinewidth: <float>,
  7747. *
  7748. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7749. *
  7750. * skinning: <bool>,
  7751. * morphTargets: <bool>,
  7752. * morphNormals: <bool>,
  7753. *
  7754. * fog: <bool>
  7755. * }
  7756. */
  7757. THREE.MeshLambertMaterial = function ( parameters ) {
  7758. THREE.Material.call( this );
  7759. this.color = new THREE.Color( 0xffffff ); // diffuse
  7760. this.ambient = new THREE.Color( 0xffffff );
  7761. this.emissive = new THREE.Color( 0x000000 );
  7762. this.wrapAround = false;
  7763. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7764. this.map = null;
  7765. this.lightMap = null;
  7766. this.specularMap = null;
  7767. this.envMap = null;
  7768. this.combine = THREE.MultiplyOperation;
  7769. this.reflectivity = 1;
  7770. this.refractionRatio = 0.98;
  7771. this.fog = true;
  7772. this.shading = THREE.SmoothShading;
  7773. this.wireframe = false;
  7774. this.wireframeLinewidth = 1;
  7775. this.wireframeLinecap = 'round';
  7776. this.wireframeLinejoin = 'round';
  7777. this.vertexColors = THREE.NoColors;
  7778. this.skinning = false;
  7779. this.morphTargets = false;
  7780. this.morphNormals = false;
  7781. this.setValues( parameters );
  7782. };
  7783. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  7784. THREE.MeshLambertMaterial.prototype.clone = function () {
  7785. var material = new THREE.MeshLambertMaterial();
  7786. THREE.Material.prototype.clone.call( this, material );
  7787. material.color.copy( this.color );
  7788. material.ambient.copy( this.ambient );
  7789. material.emissive.copy( this.emissive );
  7790. material.wrapAround = this.wrapAround;
  7791. material.wrapRGB.copy( this.wrapRGB );
  7792. material.map = this.map;
  7793. material.lightMap = this.lightMap;
  7794. material.specularMap = this.specularMap;
  7795. material.envMap = this.envMap;
  7796. material.combine = this.combine;
  7797. material.reflectivity = this.reflectivity;
  7798. material.refractionRatio = this.refractionRatio;
  7799. material.fog = this.fog;
  7800. material.shading = this.shading;
  7801. material.wireframe = this.wireframe;
  7802. material.wireframeLinewidth = this.wireframeLinewidth;
  7803. material.wireframeLinecap = this.wireframeLinecap;
  7804. material.wireframeLinejoin = this.wireframeLinejoin;
  7805. material.vertexColors = this.vertexColors;
  7806. material.skinning = this.skinning;
  7807. material.morphTargets = this.morphTargets;
  7808. material.morphNormals = this.morphNormals;
  7809. return material;
  7810. };
  7811. /**
  7812. * @author mrdoob / http://mrdoob.com/
  7813. * @author alteredq / http://alteredqualia.com/
  7814. *
  7815. * parameters = {
  7816. * color: <hex>,
  7817. * ambient: <hex>,
  7818. * emissive: <hex>,
  7819. * specular: <hex>,
  7820. * shininess: <float>,
  7821. * opacity: <float>,
  7822. *
  7823. * map: new THREE.Texture( <Image> ),
  7824. *
  7825. * lightMap: new THREE.Texture( <Image> ),
  7826. *
  7827. * bumpMap: new THREE.Texture( <Image> ),
  7828. * bumpScale: <float>,
  7829. *
  7830. * normalMap: new THREE.Texture( <Image> ),
  7831. * normalScale: <Vector2>,
  7832. *
  7833. * specularMap: new THREE.Texture( <Image> ),
  7834. *
  7835. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7836. * combine: THREE.Multiply,
  7837. * reflectivity: <float>,
  7838. * refractionRatio: <float>,
  7839. *
  7840. * shading: THREE.SmoothShading,
  7841. * blending: THREE.NormalBlending,
  7842. * depthTest: <bool>,
  7843. * depthWrite: <bool>,
  7844. *
  7845. * wireframe: <boolean>,
  7846. * wireframeLinewidth: <float>,
  7847. *
  7848. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7849. *
  7850. * skinning: <bool>,
  7851. * morphTargets: <bool>,
  7852. * morphNormals: <bool>,
  7853. *
  7854. * fog: <bool>
  7855. * }
  7856. */
  7857. THREE.MeshPhongMaterial = function ( parameters ) {
  7858. THREE.Material.call( this );
  7859. this.color = new THREE.Color( 0xffffff ); // diffuse
  7860. this.ambient = new THREE.Color( 0xffffff );
  7861. this.emissive = new THREE.Color( 0x000000 );
  7862. this.specular = new THREE.Color( 0x111111 );
  7863. this.shininess = 30;
  7864. this.metal = false;
  7865. this.perPixel = true;
  7866. this.wrapAround = false;
  7867. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7868. this.map = null;
  7869. this.lightMap = null;
  7870. this.bumpMap = null;
  7871. this.bumpScale = 1;
  7872. this.normalMap = null;
  7873. this.normalScale = new THREE.Vector2( 1, 1 );
  7874. this.specularMap = null;
  7875. this.envMap = null;
  7876. this.combine = THREE.MultiplyOperation;
  7877. this.reflectivity = 1;
  7878. this.refractionRatio = 0.98;
  7879. this.fog = true;
  7880. this.shading = THREE.SmoothShading;
  7881. this.wireframe = false;
  7882. this.wireframeLinewidth = 1;
  7883. this.wireframeLinecap = 'round';
  7884. this.wireframeLinejoin = 'round';
  7885. this.vertexColors = THREE.NoColors;
  7886. this.skinning = false;
  7887. this.morphTargets = false;
  7888. this.morphNormals = false;
  7889. this.setValues( parameters );
  7890. };
  7891. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  7892. THREE.MeshPhongMaterial.prototype.clone = function () {
  7893. var material = new THREE.MeshPhongMaterial();
  7894. THREE.Material.prototype.clone.call( this, material );
  7895. material.color.copy( this.color );
  7896. material.ambient.copy( this.ambient );
  7897. material.emissive.copy( this.emissive );
  7898. material.specular.copy( this.specular );
  7899. material.shininess = this.shininess;
  7900. material.metal = this.metal;
  7901. material.perPixel = this.perPixel;
  7902. material.wrapAround = this.wrapAround;
  7903. material.wrapRGB.copy( this.wrapRGB );
  7904. material.map = this.map;
  7905. material.lightMap = this.lightMap;
  7906. material.bumpMap = this.bumpMap;
  7907. material.bumpScale = this.bumpScale;
  7908. material.normalMap = this.normalMap;
  7909. material.normalScale.copy( this.normalScale );
  7910. material.specularMap = this.specularMap;
  7911. material.envMap = this.envMap;
  7912. material.combine = this.combine;
  7913. material.reflectivity = this.reflectivity;
  7914. material.refractionRatio = this.refractionRatio;
  7915. material.fog = this.fog;
  7916. material.shading = this.shading;
  7917. material.wireframe = this.wireframe;
  7918. material.wireframeLinewidth = this.wireframeLinewidth;
  7919. material.wireframeLinecap = this.wireframeLinecap;
  7920. material.wireframeLinejoin = this.wireframeLinejoin;
  7921. material.vertexColors = this.vertexColors;
  7922. material.skinning = this.skinning;
  7923. material.morphTargets = this.morphTargets;
  7924. material.morphNormals = this.morphNormals;
  7925. return material;
  7926. };
  7927. /**
  7928. * @author mrdoob / http://mrdoob.com/
  7929. * @author alteredq / http://alteredqualia.com/
  7930. *
  7931. * parameters = {
  7932. * opacity: <float>,
  7933. *
  7934. * blending: THREE.NormalBlending,
  7935. * depthTest: <bool>,
  7936. * depthWrite: <bool>,
  7937. *
  7938. * wireframe: <boolean>,
  7939. * wireframeLinewidth: <float>
  7940. * }
  7941. */
  7942. THREE.MeshDepthMaterial = function ( parameters ) {
  7943. THREE.Material.call( this );
  7944. this.wireframe = false;
  7945. this.wireframeLinewidth = 1;
  7946. this.setValues( parameters );
  7947. };
  7948. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  7949. THREE.MeshDepthMaterial.prototype.clone = function () {
  7950. var material = new THREE.MeshDepthMaterial();
  7951. THREE.Material.prototype.clone.call( this, material );
  7952. material.wireframe = this.wireframe;
  7953. material.wireframeLinewidth = this.wireframeLinewidth;
  7954. return material;
  7955. };
  7956. /**
  7957. * @author mrdoob / http://mrdoob.com/
  7958. *
  7959. * parameters = {
  7960. * opacity: <float>,
  7961. *
  7962. * shading: THREE.FlatShading,
  7963. * blending: THREE.NormalBlending,
  7964. * depthTest: <bool>,
  7965. * depthWrite: <bool>,
  7966. *
  7967. * wireframe: <boolean>,
  7968. * wireframeLinewidth: <float>
  7969. * }
  7970. */
  7971. THREE.MeshNormalMaterial = function ( parameters ) {
  7972. THREE.Material.call( this, parameters );
  7973. this.shading = THREE.FlatShading;
  7974. this.wireframe = false;
  7975. this.wireframeLinewidth = 1;
  7976. this.morphTargets = false;
  7977. this.setValues( parameters );
  7978. };
  7979. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  7980. THREE.MeshNormalMaterial.prototype.clone = function () {
  7981. var material = new THREE.MeshNormalMaterial();
  7982. THREE.Material.prototype.clone.call( this, material );
  7983. material.shading = this.shading;
  7984. material.wireframe = this.wireframe;
  7985. material.wireframeLinewidth = this.wireframeLinewidth;
  7986. return material;
  7987. };
  7988. /**
  7989. * @author mrdoob / http://mrdoob.com/
  7990. */
  7991. THREE.MeshFaceMaterial = function ( materials ) {
  7992. this.materials = materials instanceof Array ? materials : [];
  7993. };
  7994. THREE.MeshFaceMaterial.prototype.clone = function () {
  7995. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  7996. };
  7997. /**
  7998. * @author mrdoob / http://mrdoob.com/
  7999. * @author alteredq / http://alteredqualia.com/
  8000. *
  8001. * parameters = {
  8002. * color: <hex>,
  8003. * opacity: <float>,
  8004. * map: new THREE.Texture( <Image> ),
  8005. *
  8006. * size: <float>,
  8007. *
  8008. * blending: THREE.NormalBlending,
  8009. * depthTest: <bool>,
  8010. * depthWrite: <bool>,
  8011. *
  8012. * vertexColors: <bool>,
  8013. *
  8014. * fog: <bool>
  8015. * }
  8016. */
  8017. THREE.ParticleBasicMaterial = function ( parameters ) {
  8018. THREE.Material.call( this );
  8019. this.color = new THREE.Color( 0xffffff );
  8020. this.map = null;
  8021. this.size = 1;
  8022. this.sizeAttenuation = true;
  8023. this.vertexColors = false;
  8024. this.fog = true;
  8025. this.setValues( parameters );
  8026. };
  8027. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8028. THREE.ParticleBasicMaterial.prototype.clone = function () {
  8029. var material = new THREE.ParticleBasicMaterial();
  8030. THREE.Material.prototype.clone.call( this, material );
  8031. material.color.copy( this.color );
  8032. material.map = this.map;
  8033. material.size = this.size;
  8034. material.sizeAttenuation = this.sizeAttenuation;
  8035. material.vertexColors = this.vertexColors;
  8036. material.fog = this.fog;
  8037. return material;
  8038. };
  8039. /**
  8040. * @author mrdoob / http://mrdoob.com/
  8041. *
  8042. * parameters = {
  8043. * color: <hex>,
  8044. * program: <function>,
  8045. * opacity: <float>,
  8046. * blending: THREE.NormalBlending
  8047. * }
  8048. */
  8049. THREE.ParticleCanvasMaterial = function ( parameters ) {
  8050. THREE.Material.call( this );
  8051. this.color = new THREE.Color( 0xffffff );
  8052. this.program = function ( context, color ) {};
  8053. this.setValues( parameters );
  8054. };
  8055. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  8056. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  8057. var material = new THREE.ParticleCanvasMaterial();
  8058. THREE.Material.prototype.clone.call( this, material );
  8059. material.color.copy( this.color );
  8060. material.program = this.program;
  8061. return material;
  8062. };
  8063. /**
  8064. * @author alteredq / http://alteredqualia.com/
  8065. *
  8066. * parameters = {
  8067. * fragmentShader: <string>,
  8068. * vertexShader: <string>,
  8069. *
  8070. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  8071. *
  8072. * defines: { "label" : "value" },
  8073. *
  8074. * shading: THREE.SmoothShading,
  8075. * blending: THREE.NormalBlending,
  8076. * depthTest: <bool>,
  8077. * depthWrite: <bool>,
  8078. *
  8079. * wireframe: <boolean>,
  8080. * wireframeLinewidth: <float>,
  8081. *
  8082. * lights: <bool>,
  8083. *
  8084. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8085. *
  8086. * skinning: <bool>,
  8087. * morphTargets: <bool>,
  8088. * morphNormals: <bool>,
  8089. *
  8090. * fog: <bool>
  8091. * }
  8092. */
  8093. THREE.ShaderMaterial = function ( parameters ) {
  8094. THREE.Material.call( this );
  8095. this.fragmentShader = "void main() {}";
  8096. this.vertexShader = "void main() {}";
  8097. this.uniforms = {};
  8098. this.defines = {};
  8099. this.attributes = null;
  8100. this.shading = THREE.SmoothShading;
  8101. this.linewidth = 1;
  8102. this.wireframe = false;
  8103. this.wireframeLinewidth = 1;
  8104. this.fog = false; // set to use scene fog
  8105. this.lights = false; // set to use scene lights
  8106. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  8107. this.skinning = false; // set to use skinning attribute streams
  8108. this.morphTargets = false; // set to use morph targets
  8109. this.morphNormals = false; // set to use morph normals
  8110. // When rendered geometry doesn't include these attributes but the material does,
  8111. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8112. this.defaultAttributeValues = {
  8113. "color" : [ 1, 1, 1],
  8114. "uv" : [ 0, 0 ],
  8115. "uv2" : [ 0, 0 ]
  8116. };
  8117. // By default, bind position to attribute index 0. In WebGL, attribute 0
  8118. // should always be used to avoid potentially expensive emulation.
  8119. this.index0AttributeName = "position";
  8120. this.setValues( parameters );
  8121. };
  8122. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  8123. THREE.ShaderMaterial.prototype.clone = function () {
  8124. var material = new THREE.ShaderMaterial();
  8125. THREE.Material.prototype.clone.call( this, material );
  8126. material.fragmentShader = this.fragmentShader;
  8127. material.vertexShader = this.vertexShader;
  8128. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  8129. material.attributes = this.attributes;
  8130. material.defines = this.defines;
  8131. material.shading = this.shading;
  8132. material.wireframe = this.wireframe;
  8133. material.wireframeLinewidth = this.wireframeLinewidth;
  8134. material.fog = this.fog;
  8135. material.lights = this.lights;
  8136. material.vertexColors = this.vertexColors;
  8137. material.skinning = this.skinning;
  8138. material.morphTargets = this.morphTargets;
  8139. material.morphNormals = this.morphNormals;
  8140. return material;
  8141. };
  8142. /**
  8143. * @author alteredq / http://alteredqualia.com/
  8144. *
  8145. * parameters = {
  8146. * color: <hex>,
  8147. * opacity: <float>,
  8148. * map: new THREE.Texture( <Image> ),
  8149. *
  8150. * blending: THREE.NormalBlending,
  8151. * depthTest: <bool>,
  8152. * depthWrite: <bool>,
  8153. *
  8154. * useScreenCoordinates: <bool>,
  8155. * sizeAttenuation: <bool>,
  8156. * scaleByViewport: <bool>,
  8157. * alignment: THREE.SpriteAlignment.center,
  8158. *
  8159. * uvOffset: new THREE.Vector2(),
  8160. * uvScale: new THREE.Vector2(),
  8161. *
  8162. * fog: <bool>
  8163. * }
  8164. */
  8165. THREE.SpriteMaterial = function ( parameters ) {
  8166. THREE.Material.call( this );
  8167. // defaults
  8168. this.color = new THREE.Color( 0xffffff );
  8169. this.map = new THREE.Texture();
  8170. this.useScreenCoordinates = true;
  8171. this.depthTest = !this.useScreenCoordinates;
  8172. this.sizeAttenuation = !this.useScreenCoordinates;
  8173. this.scaleByViewport = !this.sizeAttenuation;
  8174. this.alignment = THREE.SpriteAlignment.center.clone();
  8175. this.fog = false;
  8176. this.uvOffset = new THREE.Vector2( 0, 0 );
  8177. this.uvScale = new THREE.Vector2( 1, 1 );
  8178. // set parameters
  8179. this.setValues( parameters );
  8180. // override coupled defaults if not specified explicitly by parameters
  8181. parameters = parameters || {};
  8182. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  8183. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  8184. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  8185. };
  8186. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8187. THREE.SpriteMaterial.prototype.clone = function () {
  8188. var material = new THREE.SpriteMaterial();
  8189. THREE.Material.prototype.clone.call( this, material );
  8190. material.color.copy( this.color );
  8191. material.map = this.map;
  8192. material.useScreenCoordinates = this.useScreenCoordinates;
  8193. material.sizeAttenuation = this.sizeAttenuation;
  8194. material.scaleByViewport = this.scaleByViewport;
  8195. material.alignment.copy( this.alignment );
  8196. material.uvOffset.copy( this.uvOffset );
  8197. material.uvScale.copy( this.uvScale );
  8198. material.fog = this.fog;
  8199. return material;
  8200. };
  8201. // Alignment enums
  8202. THREE.SpriteAlignment = {};
  8203. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  8204. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  8205. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  8206. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  8207. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  8208. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  8209. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  8210. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  8211. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  8212. /**
  8213. * @author mrdoob / http://mrdoob.com/
  8214. * @author alteredq / http://alteredqualia.com/
  8215. * @author szimek / https://github.com/szimek/
  8216. */
  8217. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8218. this.id = THREE.TextureIdCount ++;
  8219. this.uuid = THREE.Math.generateUUID();
  8220. this.name = '';
  8221. this.image = image;
  8222. this.mipmaps = [];
  8223. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  8224. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8225. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8226. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8227. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8228. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8229. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8230. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8231. this.offset = new THREE.Vector2( 0, 0 );
  8232. this.repeat = new THREE.Vector2( 1, 1 );
  8233. this.generateMipmaps = true;
  8234. this.premultiplyAlpha = false;
  8235. this.flipY = true;
  8236. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8237. this.needsUpdate = false;
  8238. this.onUpdate = null;
  8239. };
  8240. THREE.Texture.prototype = {
  8241. constructor: THREE.Texture,
  8242. clone: function ( texture ) {
  8243. if ( texture === undefined ) texture = new THREE.Texture();
  8244. texture.image = this.image;
  8245. texture.mipmaps = this.mipmaps.slice(0);
  8246. texture.mapping = this.mapping;
  8247. texture.wrapS = this.wrapS;
  8248. texture.wrapT = this.wrapT;
  8249. texture.magFilter = this.magFilter;
  8250. texture.minFilter = this.minFilter;
  8251. texture.anisotropy = this.anisotropy;
  8252. texture.format = this.format;
  8253. texture.type = this.type;
  8254. texture.offset.copy( this.offset );
  8255. texture.repeat.copy( this.repeat );
  8256. texture.generateMipmaps = this.generateMipmaps;
  8257. texture.premultiplyAlpha = this.premultiplyAlpha;
  8258. texture.flipY = this.flipY;
  8259. texture.unpackAlignment = this.unpackAlignment;
  8260. return texture;
  8261. },
  8262. dispose: function () {
  8263. this.dispatchEvent( { type: 'dispose' } );
  8264. }
  8265. };
  8266. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  8267. THREE.TextureIdCount = 0;
  8268. /**
  8269. * @author alteredq / http://alteredqualia.com/
  8270. */
  8271. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8272. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8273. this.image = { width: width, height: height };
  8274. this.mipmaps = mipmaps;
  8275. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  8276. };
  8277. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8278. THREE.CompressedTexture.prototype.clone = function () {
  8279. var texture = new THREE.CompressedTexture();
  8280. THREE.Texture.prototype.clone.call( this, texture );
  8281. return texture;
  8282. };
  8283. /**
  8284. * @author alteredq / http://alteredqualia.com/
  8285. */
  8286. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8287. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8288. this.image = { data: data, width: width, height: height };
  8289. };
  8290. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8291. THREE.DataTexture.prototype.clone = function () {
  8292. var texture = new THREE.DataTexture();
  8293. THREE.Texture.prototype.clone.call( this, texture );
  8294. return texture;
  8295. };
  8296. /**
  8297. * @author mrdoob / http://mrdoob.com/
  8298. */
  8299. THREE.Particle = function ( material ) {
  8300. THREE.Object3D.call( this );
  8301. this.material = material;
  8302. };
  8303. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  8304. THREE.Particle.prototype.clone = function ( object ) {
  8305. if ( object === undefined ) object = new THREE.Particle( this.material );
  8306. THREE.Object3D.prototype.clone.call( this, object );
  8307. return object;
  8308. };
  8309. /**
  8310. * @author alteredq / http://alteredqualia.com/
  8311. */
  8312. THREE.ParticleSystem = function ( geometry, material ) {
  8313. THREE.Object3D.call( this );
  8314. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8315. this.material = material !== undefined ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  8316. this.sortParticles = false;
  8317. this.frustumCulled = false;
  8318. };
  8319. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  8320. THREE.ParticleSystem.prototype.clone = function ( object ) {
  8321. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  8322. object.sortParticles = this.sortParticles;
  8323. THREE.Object3D.prototype.clone.call( this, object );
  8324. return object;
  8325. };
  8326. /**
  8327. * @author mrdoob / http://mrdoob.com/
  8328. */
  8329. THREE.Line = function ( geometry, material, type ) {
  8330. THREE.Object3D.call( this );
  8331. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8332. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  8333. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  8334. };
  8335. THREE.LineStrip = 0;
  8336. THREE.LinePieces = 1;
  8337. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  8338. THREE.Line.prototype.clone = function ( object ) {
  8339. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  8340. THREE.Object3D.prototype.clone.call( this, object );
  8341. return object;
  8342. };
  8343. /**
  8344. * @author mrdoob / http://mrdoob.com/
  8345. * @author alteredq / http://alteredqualia.com/
  8346. * @author mikael emtinger / http://gomo.se/
  8347. * @author jonobr1 / http://jonobr1.com/
  8348. */
  8349. THREE.Mesh = function ( geometry, material ) {
  8350. THREE.Object3D.call( this );
  8351. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8352. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  8353. this.updateMorphTargets();
  8354. };
  8355. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  8356. THREE.Mesh.prototype.updateMorphTargets = function () {
  8357. if ( this.geometry.morphTargets.length > 0 ) {
  8358. this.morphTargetBase = -1;
  8359. this.morphTargetForcedOrder = [];
  8360. this.morphTargetInfluences = [];
  8361. this.morphTargetDictionary = {};
  8362. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  8363. this.morphTargetInfluences.push( 0 );
  8364. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  8365. }
  8366. }
  8367. };
  8368. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  8369. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  8370. return this.morphTargetDictionary[ name ];
  8371. }
  8372. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  8373. return 0;
  8374. };
  8375. THREE.Mesh.prototype.clone = function ( object ) {
  8376. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  8377. THREE.Object3D.prototype.clone.call( this, object );
  8378. return object;
  8379. };
  8380. /**
  8381. * @author mikael emtinger / http://gomo.se/
  8382. * @author alteredq / http://alteredqualia.com/
  8383. */
  8384. THREE.Bone = function( belongsToSkin ) {
  8385. THREE.Object3D.call( this );
  8386. this.skin = belongsToSkin;
  8387. this.skinMatrix = new THREE.Matrix4();
  8388. };
  8389. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  8390. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  8391. // update local
  8392. if ( this.matrixAutoUpdate ) {
  8393. forceUpdate |= this.updateMatrix();
  8394. }
  8395. // update skin matrix
  8396. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  8397. if( parentSkinMatrix ) {
  8398. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  8399. } else {
  8400. this.skinMatrix.copy( this.matrix );
  8401. }
  8402. this.matrixWorldNeedsUpdate = false;
  8403. forceUpdate = true;
  8404. }
  8405. // update children
  8406. var child, i, l = this.children.length;
  8407. for ( i = 0; i < l; i ++ ) {
  8408. this.children[ i ].update( this.skinMatrix, forceUpdate );
  8409. }
  8410. };
  8411. /**
  8412. * @author mikael emtinger / http://gomo.se/
  8413. * @author alteredq / http://alteredqualia.com/
  8414. */
  8415. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  8416. THREE.Mesh.call( this, geometry, material );
  8417. //
  8418. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  8419. // init bones
  8420. this.identityMatrix = new THREE.Matrix4();
  8421. this.bones = [];
  8422. this.boneMatrices = [];
  8423. var b, bone, gbone, p, q, s;
  8424. if ( this.geometry && this.geometry.bones !== undefined ) {
  8425. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  8426. gbone = this.geometry.bones[ b ];
  8427. p = gbone.pos;
  8428. q = gbone.rotq;
  8429. s = gbone.scl;
  8430. bone = this.addBone();
  8431. bone.name = gbone.name;
  8432. bone.position.set( p[0], p[1], p[2] );
  8433. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  8434. if ( s !== undefined ) {
  8435. bone.scale.set( s[0], s[1], s[2] );
  8436. } else {
  8437. bone.scale.set( 1, 1, 1 );
  8438. }
  8439. }
  8440. for ( b = 0; b < this.bones.length; b ++ ) {
  8441. gbone = this.geometry.bones[ b ];
  8442. bone = this.bones[ b ];
  8443. if ( gbone.parent === -1 ) {
  8444. this.add( bone );
  8445. } else {
  8446. this.bones[ gbone.parent ].add( bone );
  8447. }
  8448. }
  8449. //
  8450. var nBones = this.bones.length;
  8451. if ( this.useVertexTexture ) {
  8452. // layout (1 matrix = 4 pixels)
  8453. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8454. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  8455. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  8456. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  8457. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  8458. var size;
  8459. if ( nBones > 256 )
  8460. size = 64;
  8461. else if ( nBones > 64 )
  8462. size = 32;
  8463. else if ( nBones > 16 )
  8464. size = 16;
  8465. else
  8466. size = 8;
  8467. this.boneTextureWidth = size;
  8468. this.boneTextureHeight = size;
  8469. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  8470. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  8471. this.boneTexture.minFilter = THREE.NearestFilter;
  8472. this.boneTexture.magFilter = THREE.NearestFilter;
  8473. this.boneTexture.generateMipmaps = false;
  8474. this.boneTexture.flipY = false;
  8475. } else {
  8476. this.boneMatrices = new Float32Array( 16 * nBones );
  8477. }
  8478. this.pose();
  8479. }
  8480. };
  8481. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  8482. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  8483. if ( bone === undefined ) {
  8484. bone = new THREE.Bone( this );
  8485. }
  8486. this.bones.push( bone );
  8487. return bone;
  8488. };
  8489. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  8490. var offsetMatrix = new THREE.Matrix4();
  8491. return function ( force ) {
  8492. this.matrixAutoUpdate && this.updateMatrix();
  8493. // update matrixWorld
  8494. if ( this.matrixWorldNeedsUpdate || force ) {
  8495. if ( this.parent ) {
  8496. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8497. } else {
  8498. this.matrixWorld.copy( this.matrix );
  8499. }
  8500. this.matrixWorldNeedsUpdate = false;
  8501. force = true;
  8502. }
  8503. // update children
  8504. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8505. var child = this.children[ i ];
  8506. if ( child instanceof THREE.Bone ) {
  8507. child.update( this.identityMatrix, false );
  8508. } else {
  8509. child.updateMatrixWorld( true );
  8510. }
  8511. }
  8512. // make a snapshot of the bones' rest position
  8513. if ( this.boneInverses == undefined ) {
  8514. this.boneInverses = [];
  8515. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8516. var inverse = new THREE.Matrix4();
  8517. inverse.getInverse( this.bones[ b ].skinMatrix );
  8518. this.boneInverses.push( inverse );
  8519. }
  8520. }
  8521. // flatten bone matrices to array
  8522. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8523. // compute the offset between the current and the original transform;
  8524. // TODO: we could get rid of this multiplication step if the skinMatrix
  8525. // was already representing the offset; however, this requires some
  8526. // major changes to the animation system
  8527. offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  8528. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  8529. }
  8530. if ( this.useVertexTexture ) {
  8531. this.boneTexture.needsUpdate = true;
  8532. }
  8533. };
  8534. }();
  8535. THREE.SkinnedMesh.prototype.pose = function () {
  8536. this.updateMatrixWorld( true );
  8537. this.normalizeSkinWeights();
  8538. };
  8539. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  8540. if ( this.geometry instanceof THREE.Geometry ) {
  8541. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  8542. var sw = this.geometry.skinWeights[ i ];
  8543. var scale = 1.0 / sw.lengthManhattan();
  8544. if ( scale !== Infinity ) {
  8545. sw.multiplyScalar( scale );
  8546. } else {
  8547. sw.set( 1 ); // this will be normalized by the shader anyway
  8548. }
  8549. }
  8550. } else {
  8551. // skinning weights assumed to be normalized for THREE.BufferGeometry
  8552. }
  8553. };
  8554. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  8555. if ( object === undefined ) {
  8556. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  8557. }
  8558. THREE.Mesh.prototype.clone.call( this, object );
  8559. return object;
  8560. };
  8561. /**
  8562. * @author alteredq / http://alteredqualia.com/
  8563. */
  8564. THREE.MorphAnimMesh = function ( geometry, material ) {
  8565. THREE.Mesh.call( this, geometry, material );
  8566. // API
  8567. this.duration = 1000; // milliseconds
  8568. this.mirroredLoop = false;
  8569. this.time = 0;
  8570. // internals
  8571. this.lastKeyframe = 0;
  8572. this.currentKeyframe = 0;
  8573. this.direction = 1;
  8574. this.directionBackwards = false;
  8575. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  8576. };
  8577. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  8578. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  8579. this.startKeyframe = start;
  8580. this.endKeyframe = end;
  8581. this.length = this.endKeyframe - this.startKeyframe + 1;
  8582. };
  8583. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  8584. this.direction = 1;
  8585. this.directionBackwards = false;
  8586. };
  8587. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  8588. this.direction = -1;
  8589. this.directionBackwards = true;
  8590. };
  8591. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  8592. var geometry = this.geometry;
  8593. if ( ! geometry.animations ) geometry.animations = {};
  8594. var firstAnimation, animations = geometry.animations;
  8595. var pattern = /([a-z]+)(\d+)/;
  8596. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  8597. var morph = geometry.morphTargets[ i ];
  8598. var parts = morph.name.match( pattern );
  8599. if ( parts && parts.length > 1 ) {
  8600. var label = parts[ 1 ];
  8601. var num = parts[ 2 ];
  8602. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  8603. var animation = animations[ label ];
  8604. if ( i < animation.start ) animation.start = i;
  8605. if ( i > animation.end ) animation.end = i;
  8606. if ( ! firstAnimation ) firstAnimation = label;
  8607. }
  8608. }
  8609. geometry.firstAnimation = firstAnimation;
  8610. };
  8611. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  8612. if ( ! this.geometry.animations ) this.geometry.animations = {};
  8613. this.geometry.animations[ label ] = { start: start, end: end };
  8614. };
  8615. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  8616. var animation = this.geometry.animations[ label ];
  8617. if ( animation ) {
  8618. this.setFrameRange( animation.start, animation.end );
  8619. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  8620. this.time = 0;
  8621. } else {
  8622. console.warn( "animation[" + label + "] undefined" );
  8623. }
  8624. };
  8625. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  8626. var frameTime = this.duration / this.length;
  8627. this.time += this.direction * delta;
  8628. if ( this.mirroredLoop ) {
  8629. if ( this.time > this.duration || this.time < 0 ) {
  8630. this.direction *= -1;
  8631. if ( this.time > this.duration ) {
  8632. this.time = this.duration;
  8633. this.directionBackwards = true;
  8634. }
  8635. if ( this.time < 0 ) {
  8636. this.time = 0;
  8637. this.directionBackwards = false;
  8638. }
  8639. }
  8640. } else {
  8641. this.time = this.time % this.duration;
  8642. if ( this.time < 0 ) this.time += this.duration;
  8643. }
  8644. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  8645. if ( keyframe !== this.currentKeyframe ) {
  8646. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  8647. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  8648. this.morphTargetInfluences[ keyframe ] = 0;
  8649. this.lastKeyframe = this.currentKeyframe;
  8650. this.currentKeyframe = keyframe;
  8651. }
  8652. var mix = ( this.time % frameTime ) / frameTime;
  8653. if ( this.directionBackwards ) {
  8654. mix = 1 - mix;
  8655. }
  8656. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  8657. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  8658. };
  8659. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  8660. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  8661. object.duration = this.duration;
  8662. object.mirroredLoop = this.mirroredLoop;
  8663. object.time = this.time;
  8664. object.lastKeyframe = this.lastKeyframe;
  8665. object.currentKeyframe = this.currentKeyframe;
  8666. object.direction = this.direction;
  8667. object.directionBackwards = this.directionBackwards;
  8668. THREE.Mesh.prototype.clone.call( this, object );
  8669. return object;
  8670. };
  8671. /**
  8672. * @author alteredq / http://alteredqualia.com/
  8673. */
  8674. THREE.Ribbon = function ( geometry, material ) {
  8675. THREE.Object3D.call( this );
  8676. this.geometry = geometry;
  8677. this.material = material;
  8678. };
  8679. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  8680. THREE.Ribbon.prototype.clone = function ( object ) {
  8681. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  8682. THREE.Object3D.prototype.clone.call( this, object );
  8683. return object;
  8684. };
  8685. /**
  8686. * @author mikael emtinger / http://gomo.se/
  8687. * @author alteredq / http://alteredqualia.com/
  8688. * @author mrdoob / http://mrdoob.com/
  8689. */
  8690. THREE.LOD = function () {
  8691. THREE.Object3D.call( this );
  8692. this.objects = [];
  8693. };
  8694. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  8695. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  8696. if ( distance === undefined ) distance = 0;
  8697. distance = Math.abs( distance );
  8698. for ( var l = 0; l < this.objects.length; l ++ ) {
  8699. if ( distance < this.objects[ l ].distance ) {
  8700. break;
  8701. }
  8702. }
  8703. this.objects.splice( l, 0, { distance: distance, object: object } );
  8704. this.add( object );
  8705. };
  8706. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  8707. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8708. if ( distance < this.objects[ i ].distance ) {
  8709. break;
  8710. }
  8711. }
  8712. return this.objects[ i - 1 ].object;
  8713. };
  8714. THREE.LOD.prototype.update = function () {
  8715. var v1 = new THREE.Vector3();
  8716. var v2 = new THREE.Vector3();
  8717. return function ( camera ) {
  8718. if ( this.objects.length > 1 ) {
  8719. v1.getPositionFromMatrix( camera.matrixWorld );
  8720. v2.getPositionFromMatrix( this.matrixWorld );
  8721. var distance = v1.distanceTo( v2 );
  8722. this.objects[ 0 ].object.visible = true;
  8723. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8724. if ( distance >= this.objects[ i ].distance ) {
  8725. this.objects[ i - 1 ].object.visible = false;
  8726. this.objects[ i ].object.visible = true;
  8727. } else {
  8728. break;
  8729. }
  8730. }
  8731. for( ; i < l; i ++ ) {
  8732. this.objects[ i ].object.visible = false;
  8733. }
  8734. }
  8735. };
  8736. }();
  8737. THREE.LOD.prototype.clone = function () {
  8738. // TODO
  8739. };
  8740. /**
  8741. * @author mikael emtinger / http://gomo.se/
  8742. * @author alteredq / http://alteredqualia.com/
  8743. */
  8744. THREE.Sprite = function ( material ) {
  8745. THREE.Object3D.call( this );
  8746. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  8747. this.rotation3d = this.rotation;
  8748. this.rotation = 0;
  8749. };
  8750. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  8751. /*
  8752. * Custom update matrix
  8753. */
  8754. THREE.Sprite.prototype.updateMatrix = function () {
  8755. this.rotation3d.set( 0, 0, this.rotation, this.rotation3d.order );
  8756. this.quaternion.setFromEuler( this.rotation3d );
  8757. this.matrix.compose( this.position, this.quaternion, this.scale );
  8758. this.matrixWorldNeedsUpdate = true;
  8759. };
  8760. THREE.Sprite.prototype.clone = function ( object ) {
  8761. if ( object === undefined ) object = new THREE.Sprite( this.material );
  8762. THREE.Object3D.prototype.clone.call( this, object );
  8763. return object;
  8764. };
  8765. /**
  8766. * @author mrdoob / http://mrdoob.com/
  8767. */
  8768. THREE.Scene = function () {
  8769. THREE.Object3D.call( this );
  8770. this.fog = null;
  8771. this.overrideMaterial = null;
  8772. this.autoUpdate = true; // checked by the renderer
  8773. this.matrixAutoUpdate = false;
  8774. this.__objects = [];
  8775. this.__lights = [];
  8776. this.__objectsAdded = [];
  8777. this.__objectsRemoved = [];
  8778. };
  8779. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  8780. THREE.Scene.prototype.__addObject = function ( object ) {
  8781. if ( object instanceof THREE.Light ) {
  8782. if ( this.__lights.indexOf( object ) === - 1 ) {
  8783. this.__lights.push( object );
  8784. }
  8785. if ( object.target && object.target.parent === undefined ) {
  8786. this.add( object.target );
  8787. }
  8788. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  8789. if ( this.__objects.indexOf( object ) === - 1 ) {
  8790. this.__objects.push( object );
  8791. this.__objectsAdded.push( object );
  8792. // check if previously removed
  8793. var i = this.__objectsRemoved.indexOf( object );
  8794. if ( i !== -1 ) {
  8795. this.__objectsRemoved.splice( i, 1 );
  8796. }
  8797. }
  8798. }
  8799. for ( var c = 0; c < object.children.length; c ++ ) {
  8800. this.__addObject( object.children[ c ] );
  8801. }
  8802. };
  8803. THREE.Scene.prototype.__removeObject = function ( object ) {
  8804. if ( object instanceof THREE.Light ) {
  8805. var i = this.__lights.indexOf( object );
  8806. if ( i !== -1 ) {
  8807. this.__lights.splice( i, 1 );
  8808. }
  8809. } else if ( !( object instanceof THREE.Camera ) ) {
  8810. var i = this.__objects.indexOf( object );
  8811. if( i !== -1 ) {
  8812. this.__objects.splice( i, 1 );
  8813. this.__objectsRemoved.push( object );
  8814. // check if previously added
  8815. var ai = this.__objectsAdded.indexOf( object );
  8816. if ( ai !== -1 ) {
  8817. this.__objectsAdded.splice( ai, 1 );
  8818. }
  8819. }
  8820. }
  8821. for ( var c = 0; c < object.children.length; c ++ ) {
  8822. this.__removeObject( object.children[ c ] );
  8823. }
  8824. };
  8825. THREE.Scene.prototype.clone = function ( object ) {
  8826. if ( object === undefined ) object = new THREE.Scene();
  8827. THREE.Object3D.prototype.clone.call(this, object);
  8828. if ( this.fog !== null ) object.fog = this.fog.clone();
  8829. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  8830. object.autoUpdate = this.autoUpdate;
  8831. object.matrixAutoUpdate = this.matrixAutoUpdate;
  8832. return object;
  8833. };
  8834. /**
  8835. * @author mrdoob / http://mrdoob.com/
  8836. * @author alteredq / http://alteredqualia.com/
  8837. */
  8838. THREE.Fog = function ( hex, near, far ) {
  8839. this.name = '';
  8840. this.color = new THREE.Color( hex );
  8841. this.near = ( near !== undefined ) ? near : 1;
  8842. this.far = ( far !== undefined ) ? far : 1000;
  8843. };
  8844. THREE.Fog.prototype.clone = function () {
  8845. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  8846. };
  8847. /**
  8848. * @author mrdoob / http://mrdoob.com/
  8849. * @author alteredq / http://alteredqualia.com/
  8850. */
  8851. THREE.FogExp2 = function ( hex, density ) {
  8852. this.name = '';
  8853. this.color = new THREE.Color( hex );
  8854. this.density = ( density !== undefined ) ? density : 0.00025;
  8855. };
  8856. THREE.FogExp2.prototype.clone = function () {
  8857. return new THREE.FogExp2( this.color.getHex(), this.density );
  8858. };
  8859. /**
  8860. * @author mrdoob / http://mrdoob.com/
  8861. */
  8862. THREE.CanvasRenderer = function ( parameters ) {
  8863. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  8864. var smoothstep = THREE.Math.smoothstep;
  8865. parameters = parameters || {};
  8866. var _this = this,
  8867. _renderData, _elements, _lights,
  8868. _projector = new THREE.Projector(),
  8869. _canvas = parameters.canvas !== undefined
  8870. ? parameters.canvas
  8871. : document.createElement( 'canvas' ),
  8872. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  8873. _context = _canvas.getContext( '2d' ),
  8874. _clearColor = new THREE.Color( 0x000000 ),
  8875. _clearAlpha = 0,
  8876. _contextGlobalAlpha = 1,
  8877. _contextGlobalCompositeOperation = 0,
  8878. _contextStrokeStyle = null,
  8879. _contextFillStyle = null,
  8880. _contextLineWidth = null,
  8881. _contextLineCap = null,
  8882. _contextLineJoin = null,
  8883. _contextDashSize = null,
  8884. _contextGapSize = 0,
  8885. _camera,
  8886. _v1, _v2, _v3, _v4,
  8887. _v5 = new THREE.RenderableVertex(),
  8888. _v6 = new THREE.RenderableVertex(),
  8889. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  8890. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  8891. _color = new THREE.Color(),
  8892. _color1 = new THREE.Color(),
  8893. _color2 = new THREE.Color(),
  8894. _color3 = new THREE.Color(),
  8895. _color4 = new THREE.Color(),
  8896. _diffuseColor = new THREE.Color(),
  8897. _emissiveColor = new THREE.Color(),
  8898. _lightColor = new THREE.Color(),
  8899. _patterns = {}, _imagedatas = {},
  8900. _near, _far,
  8901. _image, _uvs,
  8902. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  8903. _clipBox = new THREE.Box2(),
  8904. _clearBox = new THREE.Box2(),
  8905. _elemBox = new THREE.Box2(),
  8906. _ambientLight = new THREE.Color(),
  8907. _directionalLights = new THREE.Color(),
  8908. _pointLights = new THREE.Color(),
  8909. _vector3 = new THREE.Vector3(), // Needed for PointLight
  8910. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  8911. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  8912. _pixelMap = document.createElement( 'canvas' );
  8913. _pixelMap.width = _pixelMap.height = 2;
  8914. _pixelMapContext = _pixelMap.getContext( '2d' );
  8915. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  8916. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  8917. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  8918. _pixelMapData = _pixelMapImage.data;
  8919. _gradientMap = document.createElement( 'canvas' );
  8920. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  8921. _gradientMapContext = _gradientMap.getContext( '2d' );
  8922. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  8923. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  8924. _gradientMapQuality --; // Fix UVs
  8925. // dash+gap fallbacks for Firefox and everything else
  8926. if ( _context.setLineDash === undefined ) {
  8927. if ( _context.mozDash !== undefined ) {
  8928. _context.setLineDash = function ( values ) {
  8929. _context.mozDash = values[ 0 ] !== null ? values : null;
  8930. }
  8931. } else {
  8932. _context.setLineDash = function () {}
  8933. }
  8934. }
  8935. this.domElement = _canvas;
  8936. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  8937. ? parameters.devicePixelRatio
  8938. : window.devicePixelRatio !== undefined
  8939. ? window.devicePixelRatio
  8940. : 1;
  8941. this.autoClear = true;
  8942. this.sortObjects = true;
  8943. this.sortElements = true;
  8944. this.info = {
  8945. render: {
  8946. vertices: 0,
  8947. faces: 0
  8948. }
  8949. }
  8950. // WebGLRenderer compatibility
  8951. this.supportsVertexTextures = function () {};
  8952. this.setFaceCulling = function () {};
  8953. this.setSize = function ( width, height, updateStyle ) {
  8954. _canvasWidth = width * this.devicePixelRatio;
  8955. _canvasHeight = height * this.devicePixelRatio;
  8956. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  8957. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  8958. _canvas.width = _canvasWidth;
  8959. _canvas.height = _canvasHeight;
  8960. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  8961. _canvas.style.width = width + 'px';
  8962. _canvas.style.height = height + 'px';
  8963. }
  8964. _clipBox.set(
  8965. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8966. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8967. );
  8968. _clearBox.set(
  8969. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8970. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8971. );
  8972. _contextGlobalAlpha = 1;
  8973. _contextGlobalCompositeOperation = 0;
  8974. _contextStrokeStyle = null;
  8975. _contextFillStyle = null;
  8976. _contextLineWidth = null;
  8977. _contextLineCap = null;
  8978. _contextLineJoin = null;
  8979. };
  8980. this.setClearColor = function ( color, alpha ) {
  8981. _clearColor.set( color );
  8982. _clearAlpha = alpha !== undefined ? alpha : 1;
  8983. _clearBox.set(
  8984. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8985. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8986. );
  8987. };
  8988. this.setClearColorHex = function ( hex, alpha ) {
  8989. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  8990. this.setClearColor( hex, alpha );
  8991. };
  8992. this.getMaxAnisotropy = function () {
  8993. return 0;
  8994. };
  8995. this.clear = function () {
  8996. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8997. if ( _clearBox.empty() === false ) {
  8998. _clearBox.intersect( _clipBox );
  8999. _clearBox.expandByScalar( 2 );
  9000. if ( _clearAlpha < 1 ) {
  9001. _context.clearRect(
  9002. _clearBox.min.x | 0,
  9003. _clearBox.min.y | 0,
  9004. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9005. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9006. );
  9007. }
  9008. if ( _clearAlpha > 0 ) {
  9009. setBlending( THREE.NormalBlending );
  9010. setOpacity( 1 );
  9011. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  9012. _context.fillRect(
  9013. _clearBox.min.x | 0,
  9014. _clearBox.min.y | 0,
  9015. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9016. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9017. );
  9018. }
  9019. _clearBox.makeEmpty();
  9020. }
  9021. };
  9022. this.render = function ( scene, camera ) {
  9023. if ( camera instanceof THREE.Camera === false ) {
  9024. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  9025. return;
  9026. }
  9027. if ( this.autoClear === true ) this.clear();
  9028. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  9029. _this.info.render.vertices = 0;
  9030. _this.info.render.faces = 0;
  9031. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  9032. _elements = _renderData.elements;
  9033. _lights = _renderData.lights;
  9034. _camera = camera;
  9035. /* DEBUG
  9036. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  9037. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  9038. */
  9039. calculateLights();
  9040. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  9041. var element = _elements[ e ];
  9042. var material = element.material;
  9043. if ( material === undefined || material.visible === false ) continue;
  9044. _elemBox.makeEmpty();
  9045. if ( element instanceof THREE.RenderableParticle ) {
  9046. _v1 = element;
  9047. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  9048. renderParticle( _v1, element, material );
  9049. } else if ( element instanceof THREE.RenderableLine ) {
  9050. _v1 = element.v1; _v2 = element.v2;
  9051. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9052. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9053. _elemBox.setFromPoints( [
  9054. _v1.positionScreen,
  9055. _v2.positionScreen
  9056. ] );
  9057. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9058. renderLine( _v1, _v2, element, material );
  9059. }
  9060. } else if ( element instanceof THREE.RenderableFace3 ) {
  9061. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  9062. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  9063. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  9064. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  9065. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9066. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9067. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  9068. if ( material.overdraw > 0 ) {
  9069. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  9070. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  9071. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  9072. }
  9073. _elemBox.setFromPoints( [
  9074. _v1.positionScreen,
  9075. _v2.positionScreen,
  9076. _v3.positionScreen
  9077. ] );
  9078. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9079. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  9080. }
  9081. }
  9082. /* DEBUG
  9083. setLineWidth( 1 );
  9084. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  9085. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  9086. */
  9087. _clearBox.union( _elemBox );
  9088. }
  9089. /* DEBUG
  9090. setLineWidth( 1 );
  9091. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  9092. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  9093. */
  9094. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  9095. };
  9096. //
  9097. function calculateLights() {
  9098. _ambientLight.setRGB( 0, 0, 0 );
  9099. _directionalLights.setRGB( 0, 0, 0 );
  9100. _pointLights.setRGB( 0, 0, 0 );
  9101. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9102. var light = _lights[ l ];
  9103. var lightColor = light.color;
  9104. if ( light instanceof THREE.AmbientLight ) {
  9105. _ambientLight.add( lightColor );
  9106. } else if ( light instanceof THREE.DirectionalLight ) {
  9107. // for particles
  9108. _directionalLights.add( lightColor );
  9109. } else if ( light instanceof THREE.PointLight ) {
  9110. // for particles
  9111. _pointLights.add( lightColor );
  9112. }
  9113. }
  9114. }
  9115. function calculateLight( position, normal, color ) {
  9116. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9117. var light = _lights[ l ];
  9118. _lightColor.copy( light.color );
  9119. if ( light instanceof THREE.DirectionalLight ) {
  9120. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld ).normalize();
  9121. var amount = normal.dot( lightPosition );
  9122. if ( amount <= 0 ) continue;
  9123. amount *= light.intensity;
  9124. color.add( _lightColor.multiplyScalar( amount ) );
  9125. } else if ( light instanceof THREE.PointLight ) {
  9126. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld );
  9127. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  9128. if ( amount <= 0 ) continue;
  9129. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  9130. if ( amount == 0 ) continue;
  9131. amount *= light.intensity;
  9132. color.add( _lightColor.multiplyScalar( amount ) );
  9133. }
  9134. }
  9135. }
  9136. function renderParticle( v1, element, material ) {
  9137. setOpacity( material.opacity );
  9138. setBlending( material.blending );
  9139. var width, height, scaleX, scaleY,
  9140. bitmap, bitmapWidth, bitmapHeight;
  9141. if ( material instanceof THREE.ParticleBasicMaterial ) {
  9142. if ( material.map === null ) {
  9143. scaleX = element.object.scale.x;
  9144. scaleY = element.object.scale.y;
  9145. // TODO: Be able to disable this
  9146. scaleX *= element.scale.x * _canvasWidthHalf;
  9147. scaleY *= element.scale.y * _canvasHeightHalf;
  9148. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  9149. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  9150. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9151. _elemBox.makeEmpty();
  9152. return;
  9153. }
  9154. setFillStyle( material.color.getStyle() );
  9155. _context.save();
  9156. _context.translate( v1.x, v1.y );
  9157. _context.rotate( - element.rotation );
  9158. _context.scale( scaleX, scaleY );
  9159. _context.fillRect( -1, -1, 2, 2 );
  9160. _context.restore();
  9161. } else {
  9162. bitmap = material.map.image;
  9163. bitmapWidth = bitmap.width >> 1;
  9164. bitmapHeight = bitmap.height >> 1;
  9165. scaleX = element.scale.x * _canvasWidthHalf;
  9166. scaleY = element.scale.y * _canvasHeightHalf;
  9167. width = scaleX * bitmapWidth;
  9168. height = scaleY * bitmapHeight;
  9169. // TODO: Rotations break this...
  9170. _elemBox.min.set( v1.x - width, v1.y - height );
  9171. _elemBox.max.set( v1.x + width, v1.y + height );
  9172. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9173. _elemBox.makeEmpty();
  9174. return;
  9175. }
  9176. _context.save();
  9177. _context.translate( v1.x, v1.y );
  9178. _context.rotate( - element.rotation );
  9179. _context.scale( scaleX, - scaleY );
  9180. _context.translate( - bitmapWidth, - bitmapHeight );
  9181. _context.drawImage( bitmap, 0, 0 );
  9182. _context.restore();
  9183. }
  9184. /* DEBUG
  9185. setStrokeStyle( 'rgb(255,255,0)' );
  9186. _context.beginPath();
  9187. _context.moveTo( v1.x - 10, v1.y );
  9188. _context.lineTo( v1.x + 10, v1.y );
  9189. _context.moveTo( v1.x, v1.y - 10 );
  9190. _context.lineTo( v1.x, v1.y + 10 );
  9191. _context.stroke();
  9192. */
  9193. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  9194. width = element.scale.x * _canvasWidthHalf;
  9195. height = element.scale.y * _canvasHeightHalf;
  9196. _elemBox.min.set( v1.x - width, v1.y - height );
  9197. _elemBox.max.set( v1.x + width, v1.y + height );
  9198. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9199. _elemBox.makeEmpty();
  9200. return;
  9201. }
  9202. setStrokeStyle( material.color.getStyle() );
  9203. setFillStyle( material.color.getStyle() );
  9204. _context.save();
  9205. _context.translate( v1.x, v1.y );
  9206. _context.rotate( - element.rotation );
  9207. _context.scale( width, height );
  9208. material.program( _context );
  9209. _context.restore();
  9210. }
  9211. }
  9212. function renderLine( v1, v2, element, material ) {
  9213. setOpacity( material.opacity );
  9214. setBlending( material.blending );
  9215. _context.beginPath();
  9216. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  9217. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  9218. if ( material instanceof THREE.LineBasicMaterial ) {
  9219. setLineWidth( material.linewidth );
  9220. setLineCap( material.linecap );
  9221. setLineJoin( material.linejoin );
  9222. if ( material.vertexColors !== THREE.VertexColors ) {
  9223. setStrokeStyle( material.color.getStyle() );
  9224. } else {
  9225. var colorStyle1 = element.vertexColors[0].getStyle();
  9226. var colorStyle2 = element.vertexColors[1].getStyle();
  9227. if ( colorStyle1 === colorStyle2 ) {
  9228. setStrokeStyle( colorStyle1 );
  9229. } else {
  9230. try {
  9231. var grad = _context.createLinearGradient(
  9232. v1.positionScreen.x,
  9233. v1.positionScreen.y,
  9234. v2.positionScreen.x,
  9235. v2.positionScreen.y
  9236. );
  9237. grad.addColorStop( 0, colorStyle1 );
  9238. grad.addColorStop( 1, colorStyle2 );
  9239. } catch ( exception ) {
  9240. grad = colorStyle1;
  9241. }
  9242. setStrokeStyle( grad );
  9243. }
  9244. }
  9245. _context.stroke();
  9246. _elemBox.expandByScalar( material.linewidth * 2 );
  9247. } else if ( material instanceof THREE.LineDashedMaterial ) {
  9248. setLineWidth( material.linewidth );
  9249. setLineCap( material.linecap );
  9250. setLineJoin( material.linejoin );
  9251. setStrokeStyle( material.color.getStyle() );
  9252. setDashAndGap( material.dashSize, material.gapSize );
  9253. _context.stroke();
  9254. _elemBox.expandByScalar( material.linewidth * 2 );
  9255. setDashAndGap( null, null );
  9256. }
  9257. }
  9258. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  9259. _this.info.render.vertices += 3;
  9260. _this.info.render.faces ++;
  9261. setOpacity( material.opacity );
  9262. setBlending( material.blending );
  9263. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9264. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9265. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9266. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  9267. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  9268. _diffuseColor.copy( material.color );
  9269. _emissiveColor.copy( material.emissive );
  9270. if ( material.vertexColors === THREE.FaceColors ) {
  9271. _diffuseColor.multiply( element.color );
  9272. }
  9273. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  9274. _color1.copy( _ambientLight );
  9275. _color2.copy( _ambientLight );
  9276. _color3.copy( _ambientLight );
  9277. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  9278. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  9279. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  9280. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  9281. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  9282. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  9283. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9284. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9285. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9286. } else {
  9287. _color.copy( _ambientLight );
  9288. calculateLight( element.centroidModel, element.normalModel, _color );
  9289. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9290. material.wireframe === true
  9291. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9292. : fillPath( _color );
  9293. }
  9294. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9295. if ( material.map !== null ) {
  9296. if ( material.map.mapping instanceof THREE.UVMapping ) {
  9297. _uvs = element.uvs[ 0 ];
  9298. 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 );
  9299. }
  9300. } else if ( material.envMap !== null ) {
  9301. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  9302. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  9303. _uv1x = 0.5 * _vector3.x + 0.5;
  9304. _uv1y = 0.5 * _vector3.y + 0.5;
  9305. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  9306. _uv2x = 0.5 * _vector3.x + 0.5;
  9307. _uv2y = 0.5 * _vector3.y + 0.5;
  9308. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  9309. _uv3x = 0.5 * _vector3.x + 0.5;
  9310. _uv3y = 0.5 * _vector3.y + 0.5;
  9311. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9312. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  9313. }*/
  9314. } else {
  9315. _color.copy( material.color );
  9316. if ( material.vertexColors === THREE.FaceColors ) {
  9317. _color.multiply( element.color );
  9318. }
  9319. material.wireframe === true
  9320. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9321. : fillPath( _color );
  9322. }
  9323. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9324. _near = _camera.near;
  9325. _far = _camera.far;
  9326. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  9327. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  9328. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  9329. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9330. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9331. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9332. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9333. var normal;
  9334. if ( material.shading == THREE.FlatShading ) {
  9335. normal = element.normalModelView;
  9336. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9337. material.wireframe === true
  9338. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9339. : fillPath( _color );
  9340. } else if ( material.shading == THREE.SmoothShading ) {
  9341. normal = element.vertexNormalsModelView[ uv1 ];
  9342. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9343. normal = element.vertexNormalsModelView[ uv2 ];
  9344. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9345. normal = element.vertexNormalsModelView[ uv3 ];
  9346. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9347. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9348. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9349. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9350. }
  9351. }
  9352. }
  9353. //
  9354. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  9355. _context.beginPath();
  9356. _context.moveTo( x0, y0 );
  9357. _context.lineTo( x1, y1 );
  9358. _context.lineTo( x2, y2 );
  9359. _context.closePath();
  9360. }
  9361. function strokePath( color, linewidth, linecap, linejoin ) {
  9362. setLineWidth( linewidth );
  9363. setLineCap( linecap );
  9364. setLineJoin( linejoin );
  9365. setStrokeStyle( color.getStyle() );
  9366. _context.stroke();
  9367. _elemBox.expandByScalar( linewidth * 2 );
  9368. }
  9369. function fillPath( color ) {
  9370. setFillStyle( color.getStyle() );
  9371. _context.fill();
  9372. }
  9373. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  9374. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  9375. if ( texture.needsUpdate === true ) {
  9376. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  9377. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  9378. _patterns[ texture.id ] = _context.createPattern(
  9379. texture.image, repeatX === true && repeatY === true
  9380. ? 'repeat'
  9381. : repeatX === true && repeatY === false
  9382. ? 'repeat-x'
  9383. : repeatX === false && repeatY === true
  9384. ? 'repeat-y'
  9385. : 'no-repeat'
  9386. );
  9387. texture.needsUpdate = false;
  9388. }
  9389. _patterns[ texture.id ] === undefined
  9390. ? setFillStyle( 'rgba(0,0,0,1)' )
  9391. : setFillStyle( _patterns[ texture.id ] );
  9392. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9393. var a, b, c, d, e, f, det, idet,
  9394. offsetX = texture.offset.x / texture.repeat.x,
  9395. offsetY = texture.offset.y / texture.repeat.y,
  9396. width = texture.image.width * texture.repeat.x,
  9397. height = texture.image.height * texture.repeat.y;
  9398. u0 = ( u0 + offsetX ) * width;
  9399. v0 = ( 1.0 - v0 + offsetY ) * height;
  9400. u1 = ( u1 + offsetX ) * width;
  9401. v1 = ( 1.0 - v1 + offsetY ) * height;
  9402. u2 = ( u2 + offsetX ) * width;
  9403. v2 = ( 1.0 - v2 + offsetY ) * height;
  9404. x1 -= x0; y1 -= y0;
  9405. x2 -= x0; y2 -= y0;
  9406. u1 -= u0; v1 -= v0;
  9407. u2 -= u0; v2 -= v0;
  9408. det = u1 * v2 - u2 * v1;
  9409. if ( det === 0 ) {
  9410. if ( _imagedatas[ texture.id ] === undefined ) {
  9411. var canvas = document.createElement( 'canvas' )
  9412. canvas.width = texture.image.width;
  9413. canvas.height = texture.image.height;
  9414. var context = canvas.getContext( '2d' );
  9415. context.drawImage( texture.image, 0, 0 );
  9416. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  9417. }
  9418. var data = _imagedatas[ texture.id ];
  9419. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  9420. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  9421. fillPath( _color );
  9422. return;
  9423. }
  9424. idet = 1 / det;
  9425. a = ( v2 * x1 - v1 * x2 ) * idet;
  9426. b = ( v2 * y1 - v1 * y2 ) * idet;
  9427. c = ( u1 * x2 - u2 * x1 ) * idet;
  9428. d = ( u1 * y2 - u2 * y1 ) * idet;
  9429. e = x0 - a * u0 - c * v0;
  9430. f = y0 - b * u0 - d * v0;
  9431. _context.save();
  9432. _context.transform( a, b, c, d, e, f );
  9433. _context.fill();
  9434. _context.restore();
  9435. }
  9436. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  9437. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9438. var a, b, c, d, e, f, det, idet,
  9439. width = image.width - 1,
  9440. height = image.height - 1;
  9441. u0 *= width; v0 *= height;
  9442. u1 *= width; v1 *= height;
  9443. u2 *= width; v2 *= height;
  9444. x1 -= x0; y1 -= y0;
  9445. x2 -= x0; y2 -= y0;
  9446. u1 -= u0; v1 -= v0;
  9447. u2 -= u0; v2 -= v0;
  9448. det = u1 * v2 - u2 * v1;
  9449. idet = 1 / det;
  9450. a = ( v2 * x1 - v1 * x2 ) * idet;
  9451. b = ( v2 * y1 - v1 * y2 ) * idet;
  9452. c = ( u1 * x2 - u2 * x1 ) * idet;
  9453. d = ( u1 * y2 - u2 * y1 ) * idet;
  9454. e = x0 - a * u0 - c * v0;
  9455. f = y0 - b * u0 - d * v0;
  9456. _context.save();
  9457. _context.transform( a, b, c, d, e, f );
  9458. _context.clip();
  9459. _context.drawImage( image, 0, 0 );
  9460. _context.restore();
  9461. }
  9462. function getGradientTexture( color1, color2, color3, color4 ) {
  9463. // http://mrdoob.com/blog/post/710
  9464. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  9465. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  9466. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  9467. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  9468. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  9469. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  9470. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  9471. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  9472. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  9473. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  9474. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  9475. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  9476. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  9477. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  9478. return _gradientMap;
  9479. }
  9480. // Hide anti-alias gaps
  9481. function expand( v1, v2, pixels ) {
  9482. var x = v2.x - v1.x, y = v2.y - v1.y,
  9483. det = x * x + y * y, idet;
  9484. if ( det === 0 ) return;
  9485. idet = pixels / Math.sqrt( det );
  9486. x *= idet; y *= idet;
  9487. v2.x += x; v2.y += y;
  9488. v1.x -= x; v1.y -= y;
  9489. }
  9490. // Context cached methods.
  9491. function setOpacity( value ) {
  9492. if ( _contextGlobalAlpha !== value ) {
  9493. _context.globalAlpha = value;
  9494. _contextGlobalAlpha = value;
  9495. }
  9496. }
  9497. function setBlending( value ) {
  9498. if ( _contextGlobalCompositeOperation !== value ) {
  9499. if ( value === THREE.NormalBlending ) {
  9500. _context.globalCompositeOperation = 'source-over';
  9501. } else if ( value === THREE.AdditiveBlending ) {
  9502. _context.globalCompositeOperation = 'lighter';
  9503. } else if ( value === THREE.SubtractiveBlending ) {
  9504. _context.globalCompositeOperation = 'darker';
  9505. }
  9506. _contextGlobalCompositeOperation = value;
  9507. }
  9508. }
  9509. function setLineWidth( value ) {
  9510. if ( _contextLineWidth !== value ) {
  9511. _context.lineWidth = value;
  9512. _contextLineWidth = value;
  9513. }
  9514. }
  9515. function setLineCap( value ) {
  9516. // "butt", "round", "square"
  9517. if ( _contextLineCap !== value ) {
  9518. _context.lineCap = value;
  9519. _contextLineCap = value;
  9520. }
  9521. }
  9522. function setLineJoin( value ) {
  9523. // "round", "bevel", "miter"
  9524. if ( _contextLineJoin !== value ) {
  9525. _context.lineJoin = value;
  9526. _contextLineJoin = value;
  9527. }
  9528. }
  9529. function setStrokeStyle( value ) {
  9530. if ( _contextStrokeStyle !== value ) {
  9531. _context.strokeStyle = value;
  9532. _contextStrokeStyle = value;
  9533. }
  9534. }
  9535. function setFillStyle( value ) {
  9536. if ( _contextFillStyle !== value ) {
  9537. _context.fillStyle = value;
  9538. _contextFillStyle = value;
  9539. }
  9540. }
  9541. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  9542. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  9543. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  9544. _contextDashSize = dashSizeValue;
  9545. _contextGapSize = gapSizeValue;
  9546. }
  9547. }
  9548. };
  9549. /**
  9550. * @author alteredq / http://alteredqualia.com/
  9551. * @author mrdoob / http://mrdoob.com/
  9552. * @author mikael emtinger / http://gomo.se/
  9553. */
  9554. THREE.ShaderChunk = {
  9555. // FOG
  9556. fog_pars_fragment: [
  9557. "#ifdef USE_FOG",
  9558. "uniform vec3 fogColor;",
  9559. "#ifdef FOG_EXP2",
  9560. "uniform float fogDensity;",
  9561. "#else",
  9562. "uniform float fogNear;",
  9563. "uniform float fogFar;",
  9564. "#endif",
  9565. "#endif"
  9566. ].join("\n"),
  9567. fog_fragment: [
  9568. "#ifdef USE_FOG",
  9569. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9570. "#ifdef FOG_EXP2",
  9571. "const float LOG2 = 1.442695;",
  9572. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  9573. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  9574. "#else",
  9575. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  9576. "#endif",
  9577. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  9578. "#endif"
  9579. ].join("\n"),
  9580. // ENVIRONMENT MAP
  9581. envmap_pars_fragment: [
  9582. "#ifdef USE_ENVMAP",
  9583. "uniform float reflectivity;",
  9584. "uniform samplerCube envMap;",
  9585. "uniform float flipEnvMap;",
  9586. "uniform int combine;",
  9587. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9588. "uniform bool useRefract;",
  9589. "uniform float refractionRatio;",
  9590. "#else",
  9591. "varying vec3 vReflect;",
  9592. "#endif",
  9593. "#endif"
  9594. ].join("\n"),
  9595. envmap_fragment: [
  9596. "#ifdef USE_ENVMAP",
  9597. "vec3 reflectVec;",
  9598. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9599. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  9600. "if ( useRefract ) {",
  9601. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  9602. "} else { ",
  9603. "reflectVec = reflect( cameraToVertex, normal );",
  9604. "}",
  9605. "#else",
  9606. "reflectVec = vReflect;",
  9607. "#endif",
  9608. "#ifdef DOUBLE_SIDED",
  9609. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9610. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9611. "#else",
  9612. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9613. "#endif",
  9614. "#ifdef GAMMA_INPUT",
  9615. "cubeColor.xyz *= cubeColor.xyz;",
  9616. "#endif",
  9617. "if ( combine == 1 ) {",
  9618. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  9619. "} else if ( combine == 2 ) {",
  9620. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  9621. "} else {",
  9622. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  9623. "}",
  9624. "#endif"
  9625. ].join("\n"),
  9626. envmap_pars_vertex: [
  9627. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9628. "varying vec3 vReflect;",
  9629. "uniform float refractionRatio;",
  9630. "uniform bool useRefract;",
  9631. "#endif"
  9632. ].join("\n"),
  9633. worldpos_vertex : [
  9634. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  9635. "#ifdef USE_SKINNING",
  9636. "vec4 worldPosition = modelMatrix * skinned;",
  9637. "#endif",
  9638. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9639. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  9640. "#endif",
  9641. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9642. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  9643. "#endif",
  9644. "#endif"
  9645. ].join("\n"),
  9646. envmap_vertex : [
  9647. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9648. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  9649. "worldNormal = normalize( worldNormal );",
  9650. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  9651. "if ( useRefract ) {",
  9652. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  9653. "} else {",
  9654. "vReflect = reflect( cameraToVertex, worldNormal );",
  9655. "}",
  9656. "#endif"
  9657. ].join("\n"),
  9658. // COLOR MAP (particles)
  9659. map_particle_pars_fragment: [
  9660. "#ifdef USE_MAP",
  9661. "uniform sampler2D map;",
  9662. "#endif"
  9663. ].join("\n"),
  9664. map_particle_fragment: [
  9665. "#ifdef USE_MAP",
  9666. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  9667. "#endif"
  9668. ].join("\n"),
  9669. // COLOR MAP (triangles)
  9670. map_pars_vertex: [
  9671. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9672. "varying vec2 vUv;",
  9673. "uniform vec4 offsetRepeat;",
  9674. "#endif"
  9675. ].join("\n"),
  9676. map_pars_fragment: [
  9677. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9678. "varying vec2 vUv;",
  9679. "#endif",
  9680. "#ifdef USE_MAP",
  9681. "uniform sampler2D map;",
  9682. "#endif"
  9683. ].join("\n"),
  9684. map_vertex: [
  9685. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9686. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  9687. "#endif"
  9688. ].join("\n"),
  9689. map_fragment: [
  9690. "#ifdef USE_MAP",
  9691. "vec4 texelColor = texture2D( map, vUv );",
  9692. "#ifdef GAMMA_INPUT",
  9693. "texelColor.xyz *= texelColor.xyz;",
  9694. "#endif",
  9695. "gl_FragColor = gl_FragColor * texelColor;",
  9696. "#endif"
  9697. ].join("\n"),
  9698. // LIGHT MAP
  9699. lightmap_pars_fragment: [
  9700. "#ifdef USE_LIGHTMAP",
  9701. "varying vec2 vUv2;",
  9702. "uniform sampler2D lightMap;",
  9703. "#endif"
  9704. ].join("\n"),
  9705. lightmap_pars_vertex: [
  9706. "#ifdef USE_LIGHTMAP",
  9707. "varying vec2 vUv2;",
  9708. "#endif"
  9709. ].join("\n"),
  9710. lightmap_fragment: [
  9711. "#ifdef USE_LIGHTMAP",
  9712. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  9713. "#endif"
  9714. ].join("\n"),
  9715. lightmap_vertex: [
  9716. "#ifdef USE_LIGHTMAP",
  9717. "vUv2 = uv2;",
  9718. "#endif"
  9719. ].join("\n"),
  9720. // BUMP MAP
  9721. bumpmap_pars_fragment: [
  9722. "#ifdef USE_BUMPMAP",
  9723. "uniform sampler2D bumpMap;",
  9724. "uniform float bumpScale;",
  9725. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  9726. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  9727. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9728. "vec2 dHdxy_fwd() {",
  9729. "vec2 dSTdx = dFdx( vUv );",
  9730. "vec2 dSTdy = dFdy( vUv );",
  9731. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  9732. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  9733. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  9734. "return vec2( dBx, dBy );",
  9735. "}",
  9736. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  9737. "vec3 vSigmaX = dFdx( surf_pos );",
  9738. "vec3 vSigmaY = dFdy( surf_pos );",
  9739. "vec3 vN = surf_norm;", // normalized
  9740. "vec3 R1 = cross( vSigmaY, vN );",
  9741. "vec3 R2 = cross( vN, vSigmaX );",
  9742. "float fDet = dot( vSigmaX, R1 );",
  9743. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  9744. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  9745. "}",
  9746. "#endif"
  9747. ].join("\n"),
  9748. // NORMAL MAP
  9749. normalmap_pars_fragment: [
  9750. "#ifdef USE_NORMALMAP",
  9751. "uniform sampler2D normalMap;",
  9752. "uniform vec2 normalScale;",
  9753. // Per-Pixel Tangent Space Normal Mapping
  9754. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  9755. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  9756. "vec3 q0 = dFdx( eye_pos.xyz );",
  9757. "vec3 q1 = dFdy( eye_pos.xyz );",
  9758. "vec2 st0 = dFdx( vUv.st );",
  9759. "vec2 st1 = dFdy( vUv.st );",
  9760. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  9761. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  9762. "vec3 N = normalize( surf_norm );",
  9763. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  9764. "mapN.xy = normalScale * mapN.xy;",
  9765. "mat3 tsn = mat3( S, T, N );",
  9766. "return normalize( tsn * mapN );",
  9767. "}",
  9768. "#endif"
  9769. ].join("\n"),
  9770. // SPECULAR MAP
  9771. specularmap_pars_fragment: [
  9772. "#ifdef USE_SPECULARMAP",
  9773. "uniform sampler2D specularMap;",
  9774. "#endif"
  9775. ].join("\n"),
  9776. specularmap_fragment: [
  9777. "float specularStrength;",
  9778. "#ifdef USE_SPECULARMAP",
  9779. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  9780. "specularStrength = texelSpecular.r;",
  9781. "#else",
  9782. "specularStrength = 1.0;",
  9783. "#endif"
  9784. ].join("\n"),
  9785. // LIGHTS LAMBERT
  9786. lights_lambert_pars_vertex: [
  9787. "uniform vec3 ambient;",
  9788. "uniform vec3 diffuse;",
  9789. "uniform vec3 emissive;",
  9790. "uniform vec3 ambientLightColor;",
  9791. "#if MAX_DIR_LIGHTS > 0",
  9792. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9793. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9794. "#endif",
  9795. "#if MAX_HEMI_LIGHTS > 0",
  9796. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9797. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9798. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9799. "#endif",
  9800. "#if MAX_POINT_LIGHTS > 0",
  9801. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9802. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9803. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9804. "#endif",
  9805. "#if MAX_SPOT_LIGHTS > 0",
  9806. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9807. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9808. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9809. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9810. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9811. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9812. "#endif",
  9813. "#ifdef WRAP_AROUND",
  9814. "uniform vec3 wrapRGB;",
  9815. "#endif"
  9816. ].join("\n"),
  9817. lights_lambert_vertex: [
  9818. "vLightFront = vec3( 0.0 );",
  9819. "#ifdef DOUBLE_SIDED",
  9820. "vLightBack = vec3( 0.0 );",
  9821. "#endif",
  9822. "transformedNormal = normalize( transformedNormal );",
  9823. "#if MAX_DIR_LIGHTS > 0",
  9824. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9825. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9826. "vec3 dirVector = normalize( lDirection.xyz );",
  9827. "float dotProduct = dot( transformedNormal, dirVector );",
  9828. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9829. "#ifdef DOUBLE_SIDED",
  9830. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9831. "#ifdef WRAP_AROUND",
  9832. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9833. "#endif",
  9834. "#endif",
  9835. "#ifdef WRAP_AROUND",
  9836. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9837. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  9838. "#ifdef DOUBLE_SIDED",
  9839. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  9840. "#endif",
  9841. "#endif",
  9842. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  9843. "#ifdef DOUBLE_SIDED",
  9844. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  9845. "#endif",
  9846. "}",
  9847. "#endif",
  9848. "#if MAX_POINT_LIGHTS > 0",
  9849. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9850. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9851. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9852. "float lDistance = 1.0;",
  9853. "if ( pointLightDistance[ i ] > 0.0 )",
  9854. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9855. "lVector = normalize( lVector );",
  9856. "float dotProduct = dot( transformedNormal, lVector );",
  9857. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9858. "#ifdef DOUBLE_SIDED",
  9859. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9860. "#ifdef WRAP_AROUND",
  9861. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9862. "#endif",
  9863. "#endif",
  9864. "#ifdef WRAP_AROUND",
  9865. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9866. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  9867. "#ifdef DOUBLE_SIDED",
  9868. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  9869. "#endif",
  9870. "#endif",
  9871. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  9872. "#ifdef DOUBLE_SIDED",
  9873. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  9874. "#endif",
  9875. "}",
  9876. "#endif",
  9877. "#if MAX_SPOT_LIGHTS > 0",
  9878. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9879. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9880. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9881. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  9882. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9883. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9884. "float lDistance = 1.0;",
  9885. "if ( spotLightDistance[ i ] > 0.0 )",
  9886. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9887. "lVector = normalize( lVector );",
  9888. "float dotProduct = dot( transformedNormal, lVector );",
  9889. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9890. "#ifdef DOUBLE_SIDED",
  9891. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9892. "#ifdef WRAP_AROUND",
  9893. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9894. "#endif",
  9895. "#endif",
  9896. "#ifdef WRAP_AROUND",
  9897. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9898. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  9899. "#ifdef DOUBLE_SIDED",
  9900. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  9901. "#endif",
  9902. "#endif",
  9903. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  9904. "#ifdef DOUBLE_SIDED",
  9905. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  9906. "#endif",
  9907. "}",
  9908. "}",
  9909. "#endif",
  9910. "#if MAX_HEMI_LIGHTS > 0",
  9911. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9912. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9913. "vec3 lVector = normalize( lDirection.xyz );",
  9914. "float dotProduct = dot( transformedNormal, lVector );",
  9915. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9916. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  9917. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9918. "#ifdef DOUBLE_SIDED",
  9919. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  9920. "#endif",
  9921. "}",
  9922. "#endif",
  9923. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  9924. "#ifdef DOUBLE_SIDED",
  9925. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  9926. "#endif"
  9927. ].join("\n"),
  9928. // LIGHTS PHONG
  9929. lights_phong_pars_vertex: [
  9930. "#ifndef PHONG_PER_PIXEL",
  9931. "#if MAX_POINT_LIGHTS > 0",
  9932. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9933. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9934. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9935. "#endif",
  9936. "#if MAX_SPOT_LIGHTS > 0",
  9937. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9938. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9939. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9940. "#endif",
  9941. "#endif",
  9942. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9943. "varying vec3 vWorldPosition;",
  9944. "#endif"
  9945. ].join("\n"),
  9946. lights_phong_vertex: [
  9947. "#ifndef PHONG_PER_PIXEL",
  9948. "#if MAX_POINT_LIGHTS > 0",
  9949. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9950. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9951. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9952. "float lDistance = 1.0;",
  9953. "if ( pointLightDistance[ i ] > 0.0 )",
  9954. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9955. "vPointLight[ i ] = vec4( lVector, lDistance );",
  9956. "}",
  9957. "#endif",
  9958. "#if MAX_SPOT_LIGHTS > 0",
  9959. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9960. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9961. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9962. "float lDistance = 1.0;",
  9963. "if ( spotLightDistance[ i ] > 0.0 )",
  9964. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9965. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  9966. "}",
  9967. "#endif",
  9968. "#endif",
  9969. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9970. "vWorldPosition = worldPosition.xyz;",
  9971. "#endif"
  9972. ].join("\n"),
  9973. lights_phong_pars_fragment: [
  9974. "uniform vec3 ambientLightColor;",
  9975. "#if MAX_DIR_LIGHTS > 0",
  9976. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9977. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9978. "#endif",
  9979. "#if MAX_HEMI_LIGHTS > 0",
  9980. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9981. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9982. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9983. "#endif",
  9984. "#if MAX_POINT_LIGHTS > 0",
  9985. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9986. "#ifdef PHONG_PER_PIXEL",
  9987. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9988. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9989. "#else",
  9990. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9991. "#endif",
  9992. "#endif",
  9993. "#if MAX_SPOT_LIGHTS > 0",
  9994. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9995. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9996. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9997. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9998. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9999. "#ifdef PHONG_PER_PIXEL",
  10000. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10001. "#else",
  10002. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  10003. "#endif",
  10004. "#endif",
  10005. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10006. "varying vec3 vWorldPosition;",
  10007. "#endif",
  10008. "#ifdef WRAP_AROUND",
  10009. "uniform vec3 wrapRGB;",
  10010. "#endif",
  10011. "varying vec3 vViewPosition;",
  10012. "varying vec3 vNormal;"
  10013. ].join("\n"),
  10014. lights_phong_fragment: [
  10015. "vec3 normal = normalize( vNormal );",
  10016. "vec3 viewPosition = normalize( vViewPosition );",
  10017. "#ifdef DOUBLE_SIDED",
  10018. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10019. "#endif",
  10020. "#ifdef USE_NORMALMAP",
  10021. "normal = perturbNormal2Arb( -vViewPosition, normal );",
  10022. "#elif defined( USE_BUMPMAP )",
  10023. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  10024. "#endif",
  10025. "#if MAX_POINT_LIGHTS > 0",
  10026. "vec3 pointDiffuse = vec3( 0.0 );",
  10027. "vec3 pointSpecular = vec3( 0.0 );",
  10028. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10029. "#ifdef PHONG_PER_PIXEL",
  10030. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10031. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10032. "float lDistance = 1.0;",
  10033. "if ( pointLightDistance[ i ] > 0.0 )",
  10034. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10035. "lVector = normalize( lVector );",
  10036. "#else",
  10037. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  10038. "float lDistance = vPointLight[ i ].w;",
  10039. "#endif",
  10040. // diffuse
  10041. "float dotProduct = dot( normal, lVector );",
  10042. "#ifdef WRAP_AROUND",
  10043. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  10044. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10045. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10046. "#else",
  10047. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  10048. "#endif",
  10049. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  10050. // specular
  10051. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  10052. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10053. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  10054. "#ifdef PHYSICALLY_BASED_SHADING",
  10055. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10056. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10057. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  10058. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  10059. "#else",
  10060. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  10061. "#endif",
  10062. "}",
  10063. "#endif",
  10064. "#if MAX_SPOT_LIGHTS > 0",
  10065. "vec3 spotDiffuse = vec3( 0.0 );",
  10066. "vec3 spotSpecular = vec3( 0.0 );",
  10067. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10068. "#ifdef PHONG_PER_PIXEL",
  10069. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10070. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10071. "float lDistance = 1.0;",
  10072. "if ( spotLightDistance[ i ] > 0.0 )",
  10073. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10074. "lVector = normalize( lVector );",
  10075. "#else",
  10076. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  10077. "float lDistance = vSpotLight[ i ].w;",
  10078. "#endif",
  10079. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10080. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10081. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10082. // diffuse
  10083. "float dotProduct = dot( normal, lVector );",
  10084. "#ifdef WRAP_AROUND",
  10085. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  10086. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10087. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10088. "#else",
  10089. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  10090. "#endif",
  10091. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  10092. // specular
  10093. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  10094. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10095. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  10096. "#ifdef PHYSICALLY_BASED_SHADING",
  10097. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10098. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10099. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  10100. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  10101. "#else",
  10102. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  10103. "#endif",
  10104. "}",
  10105. "}",
  10106. "#endif",
  10107. "#if MAX_DIR_LIGHTS > 0",
  10108. "vec3 dirDiffuse = vec3( 0.0 );",
  10109. "vec3 dirSpecular = vec3( 0.0 );" ,
  10110. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10111. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10112. "vec3 dirVector = normalize( lDirection.xyz );",
  10113. // diffuse
  10114. "float dotProduct = dot( normal, dirVector );",
  10115. "#ifdef WRAP_AROUND",
  10116. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  10117. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10118. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  10119. "#else",
  10120. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  10121. "#endif",
  10122. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  10123. // specular
  10124. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10125. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10126. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  10127. "#ifdef PHYSICALLY_BASED_SHADING",
  10128. /*
  10129. // fresnel term from skin shader
  10130. "const float F0 = 0.128;",
  10131. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  10132. "float exponential = pow( base, 5.0 );",
  10133. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  10134. */
  10135. /*
  10136. // fresnel term from fresnel shader
  10137. "const float mFresnelBias = 0.08;",
  10138. "const float mFresnelScale = 0.3;",
  10139. "const float mFresnelPower = 5.0;",
  10140. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  10141. */
  10142. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10143. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10144. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  10145. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10146. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10147. "#else",
  10148. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  10149. "#endif",
  10150. "}",
  10151. "#endif",
  10152. "#if MAX_HEMI_LIGHTS > 0",
  10153. "vec3 hemiDiffuse = vec3( 0.0 );",
  10154. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10155. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10156. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10157. "vec3 lVector = normalize( lDirection.xyz );",
  10158. // diffuse
  10159. "float dotProduct = dot( normal, lVector );",
  10160. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10161. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10162. "hemiDiffuse += diffuse * hemiColor;",
  10163. // specular (sky light)
  10164. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10165. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10166. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  10167. // specular (ground light)
  10168. "vec3 lVectorGround = -lVector;",
  10169. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10170. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10171. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  10172. "#ifdef PHYSICALLY_BASED_SHADING",
  10173. "float dotProductGround = dot( normal, lVectorGround );",
  10174. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10175. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10176. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10177. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10178. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10179. "#else",
  10180. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  10181. "#endif",
  10182. "}",
  10183. "#endif",
  10184. "vec3 totalDiffuse = vec3( 0.0 );",
  10185. "vec3 totalSpecular = vec3( 0.0 );",
  10186. "#if MAX_DIR_LIGHTS > 0",
  10187. "totalDiffuse += dirDiffuse;",
  10188. "totalSpecular += dirSpecular;",
  10189. "#endif",
  10190. "#if MAX_HEMI_LIGHTS > 0",
  10191. "totalDiffuse += hemiDiffuse;",
  10192. "totalSpecular += hemiSpecular;",
  10193. "#endif",
  10194. "#if MAX_POINT_LIGHTS > 0",
  10195. "totalDiffuse += pointDiffuse;",
  10196. "totalSpecular += pointSpecular;",
  10197. "#endif",
  10198. "#if MAX_SPOT_LIGHTS > 0",
  10199. "totalDiffuse += spotDiffuse;",
  10200. "totalSpecular += spotSpecular;",
  10201. "#endif",
  10202. "#ifdef METAL",
  10203. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  10204. "#else",
  10205. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  10206. "#endif"
  10207. ].join("\n"),
  10208. // VERTEX COLORS
  10209. color_pars_fragment: [
  10210. "#ifdef USE_COLOR",
  10211. "varying vec3 vColor;",
  10212. "#endif"
  10213. ].join("\n"),
  10214. color_fragment: [
  10215. "#ifdef USE_COLOR",
  10216. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  10217. "#endif"
  10218. ].join("\n"),
  10219. color_pars_vertex: [
  10220. "#ifdef USE_COLOR",
  10221. "varying vec3 vColor;",
  10222. "#endif"
  10223. ].join("\n"),
  10224. color_vertex: [
  10225. "#ifdef USE_COLOR",
  10226. "#ifdef GAMMA_INPUT",
  10227. "vColor = color * color;",
  10228. "#else",
  10229. "vColor = color;",
  10230. "#endif",
  10231. "#endif"
  10232. ].join("\n"),
  10233. // SKINNING
  10234. skinning_pars_vertex: [
  10235. "#ifdef USE_SKINNING",
  10236. "#ifdef BONE_TEXTURE",
  10237. "uniform sampler2D boneTexture;",
  10238. "mat4 getBoneMatrix( const in float i ) {",
  10239. "float j = i * 4.0;",
  10240. "float x = mod( j, N_BONE_PIXEL_X );",
  10241. "float y = floor( j / N_BONE_PIXEL_X );",
  10242. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  10243. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  10244. "y = dy * ( y + 0.5 );",
  10245. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  10246. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  10247. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  10248. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  10249. "mat4 bone = mat4( v1, v2, v3, v4 );",
  10250. "return bone;",
  10251. "}",
  10252. "#else",
  10253. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  10254. "mat4 getBoneMatrix( const in float i ) {",
  10255. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  10256. "return bone;",
  10257. "}",
  10258. "#endif",
  10259. "#endif"
  10260. ].join("\n"),
  10261. skinbase_vertex: [
  10262. "#ifdef USE_SKINNING",
  10263. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  10264. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  10265. "#endif"
  10266. ].join("\n"),
  10267. skinning_vertex: [
  10268. "#ifdef USE_SKINNING",
  10269. "#ifdef USE_MORPHTARGETS",
  10270. "vec4 skinVertex = vec4( morphed, 1.0 );",
  10271. "#else",
  10272. "vec4 skinVertex = vec4( position, 1.0 );",
  10273. "#endif",
  10274. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10275. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10276. "#endif"
  10277. ].join("\n"),
  10278. // MORPHING
  10279. morphtarget_pars_vertex: [
  10280. "#ifdef USE_MORPHTARGETS",
  10281. "#ifndef USE_MORPHNORMALS",
  10282. "uniform float morphTargetInfluences[ 8 ];",
  10283. "#else",
  10284. "uniform float morphTargetInfluences[ 4 ];",
  10285. "#endif",
  10286. "#endif"
  10287. ].join("\n"),
  10288. morphtarget_vertex: [
  10289. "#ifdef USE_MORPHTARGETS",
  10290. "vec3 morphed = vec3( 0.0 );",
  10291. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  10292. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  10293. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  10294. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  10295. "#ifndef USE_MORPHNORMALS",
  10296. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  10297. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  10298. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  10299. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  10300. "#endif",
  10301. "morphed += position;",
  10302. "#endif"
  10303. ].join("\n"),
  10304. default_vertex : [
  10305. "vec4 mvPosition;",
  10306. "#ifdef USE_SKINNING",
  10307. "mvPosition = modelViewMatrix * skinned;",
  10308. "#endif",
  10309. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  10310. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  10311. "#endif",
  10312. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  10313. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10314. "#endif",
  10315. "gl_Position = projectionMatrix * mvPosition;"
  10316. ].join("\n"),
  10317. morphnormal_vertex: [
  10318. "#ifdef USE_MORPHNORMALS",
  10319. "vec3 morphedNormal = vec3( 0.0 );",
  10320. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  10321. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  10322. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  10323. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  10324. "morphedNormal += normal;",
  10325. "#endif"
  10326. ].join("\n"),
  10327. skinnormal_vertex: [
  10328. "#ifdef USE_SKINNING",
  10329. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  10330. "skinMatrix += skinWeight.y * boneMatY;",
  10331. "#ifdef USE_MORPHNORMALS",
  10332. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  10333. "#else",
  10334. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  10335. "#endif",
  10336. "#endif"
  10337. ].join("\n"),
  10338. defaultnormal_vertex: [
  10339. "vec3 objectNormal;",
  10340. "#ifdef USE_SKINNING",
  10341. "objectNormal = skinnedNormal.xyz;",
  10342. "#endif",
  10343. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  10344. "objectNormal = morphedNormal;",
  10345. "#endif",
  10346. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  10347. "objectNormal = normal;",
  10348. "#endif",
  10349. "#ifdef FLIP_SIDED",
  10350. "objectNormal = -objectNormal;",
  10351. "#endif",
  10352. "vec3 transformedNormal = normalMatrix * objectNormal;"
  10353. ].join("\n"),
  10354. // SHADOW MAP
  10355. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  10356. // http://spidergl.org/example.php?id=6
  10357. // http://fabiensanglard.net/shadowmapping
  10358. shadowmap_pars_fragment: [
  10359. "#ifdef USE_SHADOWMAP",
  10360. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  10361. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  10362. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  10363. "uniform float shadowBias[ MAX_SHADOWS ];",
  10364. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10365. "float unpackDepth( const in vec4 rgba_depth ) {",
  10366. "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 );",
  10367. "float depth = dot( rgba_depth, bit_shift );",
  10368. "return depth;",
  10369. "}",
  10370. "#endif"
  10371. ].join("\n"),
  10372. shadowmap_fragment: [
  10373. "#ifdef USE_SHADOWMAP",
  10374. "#ifdef SHADOWMAP_DEBUG",
  10375. "vec3 frustumColors[3];",
  10376. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  10377. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  10378. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  10379. "#endif",
  10380. "#ifdef SHADOWMAP_CASCADE",
  10381. "int inFrustumCount = 0;",
  10382. "#endif",
  10383. "float fDepth;",
  10384. "vec3 shadowColor = vec3( 1.0 );",
  10385. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10386. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  10387. // "if ( something && something )" breaks ATI OpenGL shader compiler
  10388. // "if ( all( something, something ) )" using this instead
  10389. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  10390. "bool inFrustum = all( inFrustumVec );",
  10391. // don't shadow pixels outside of light frustum
  10392. // use just first frustum (for cascades)
  10393. // don't shadow pixels behind far plane of light frustum
  10394. "#ifdef SHADOWMAP_CASCADE",
  10395. "inFrustumCount += int( inFrustum );",
  10396. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  10397. "#else",
  10398. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  10399. "#endif",
  10400. "bool frustumTest = all( frustumTestVec );",
  10401. "if ( frustumTest ) {",
  10402. "shadowCoord.z += shadowBias[ i ];",
  10403. "#if defined( SHADOWMAP_TYPE_PCF )",
  10404. // Percentage-close filtering
  10405. // (9 pixel kernel)
  10406. // http://fabiensanglard.net/shadowmappingPCF/
  10407. "float shadow = 0.0;",
  10408. /*
  10409. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  10410. // must enroll loop manually
  10411. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  10412. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  10413. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  10414. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  10415. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  10416. "float fDepth = unpackDepth( rgbaDepth );",
  10417. "if ( fDepth < shadowCoord.z )",
  10418. "shadow += 1.0;",
  10419. "}",
  10420. "shadow /= 9.0;",
  10421. */
  10422. "const float shadowDelta = 1.0 / 9.0;",
  10423. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10424. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10425. "float dx0 = -1.25 * xPixelOffset;",
  10426. "float dy0 = -1.25 * yPixelOffset;",
  10427. "float dx1 = 1.25 * xPixelOffset;",
  10428. "float dy1 = 1.25 * yPixelOffset;",
  10429. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10430. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10431. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10432. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10433. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10434. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10435. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10436. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10437. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10438. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10439. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10440. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10441. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10442. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10443. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10444. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10445. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10446. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10447. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10448. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  10449. // Percentage-close filtering
  10450. // (9 pixel kernel)
  10451. // http://fabiensanglard.net/shadowmappingPCF/
  10452. "float shadow = 0.0;",
  10453. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10454. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10455. "float dx0 = -1.0 * xPixelOffset;",
  10456. "float dy0 = -1.0 * yPixelOffset;",
  10457. "float dx1 = 1.0 * xPixelOffset;",
  10458. "float dy1 = 1.0 * yPixelOffset;",
  10459. "mat3 shadowKernel;",
  10460. "mat3 depthKernel;",
  10461. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10462. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10463. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10464. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10465. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10466. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10467. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10468. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10469. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10470. "vec3 shadowZ = vec3( shadowCoord.z );",
  10471. "shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  10472. "shadowKernel[0] *= vec3(0.25);",
  10473. "shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  10474. "shadowKernel[1] *= vec3(0.25);",
  10475. "shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  10476. "shadowKernel[2] *= vec3(0.25);",
  10477. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  10478. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  10479. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  10480. "vec4 shadowValues;",
  10481. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  10482. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  10483. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  10484. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  10485. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  10486. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10487. "#else",
  10488. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  10489. "float fDepth = unpackDepth( rgbaDepth );",
  10490. "if ( fDepth < shadowCoord.z )",
  10491. // spot with multiple shadows is darker
  10492. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  10493. // spot with multiple shadows has the same color as single shadow spot
  10494. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  10495. "#endif",
  10496. "}",
  10497. "#ifdef SHADOWMAP_DEBUG",
  10498. "#ifdef SHADOWMAP_CASCADE",
  10499. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  10500. "#else",
  10501. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  10502. "#endif",
  10503. "#endif",
  10504. "}",
  10505. "#ifdef GAMMA_OUTPUT",
  10506. "shadowColor *= shadowColor;",
  10507. "#endif",
  10508. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  10509. "#endif"
  10510. ].join("\n"),
  10511. shadowmap_pars_vertex: [
  10512. "#ifdef USE_SHADOWMAP",
  10513. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10514. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  10515. "#endif"
  10516. ].join("\n"),
  10517. shadowmap_vertex: [
  10518. "#ifdef USE_SHADOWMAP",
  10519. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10520. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10521. "}",
  10522. "#endif"
  10523. ].join("\n"),
  10524. // ALPHATEST
  10525. alphatest_fragment: [
  10526. "#ifdef ALPHATEST",
  10527. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  10528. "#endif"
  10529. ].join("\n"),
  10530. // LINEAR SPACE
  10531. linear_to_gamma_fragment: [
  10532. "#ifdef GAMMA_OUTPUT",
  10533. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  10534. "#endif"
  10535. ].join("\n")
  10536. };
  10537. THREE.UniformsUtils = {
  10538. merge: function ( uniforms ) {
  10539. var u, p, tmp, merged = {};
  10540. for ( u = 0; u < uniforms.length; u ++ ) {
  10541. tmp = this.clone( uniforms[ u ] );
  10542. for ( p in tmp ) {
  10543. merged[ p ] = tmp[ p ];
  10544. }
  10545. }
  10546. return merged;
  10547. },
  10548. clone: function ( uniforms_src ) {
  10549. var u, p, parameter, parameter_src, uniforms_dst = {};
  10550. for ( u in uniforms_src ) {
  10551. uniforms_dst[ u ] = {};
  10552. for ( p in uniforms_src[ u ] ) {
  10553. parameter_src = uniforms_src[ u ][ p ];
  10554. if ( parameter_src instanceof THREE.Color ||
  10555. parameter_src instanceof THREE.Vector2 ||
  10556. parameter_src instanceof THREE.Vector3 ||
  10557. parameter_src instanceof THREE.Vector4 ||
  10558. parameter_src instanceof THREE.Matrix4 ||
  10559. parameter_src instanceof THREE.Texture ) {
  10560. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10561. } else if ( parameter_src instanceof Array ) {
  10562. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10563. } else {
  10564. uniforms_dst[ u ][ p ] = parameter_src;
  10565. }
  10566. }
  10567. }
  10568. return uniforms_dst;
  10569. }
  10570. };
  10571. THREE.UniformsLib = {
  10572. common: {
  10573. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10574. "opacity" : { type: "f", value: 1.0 },
  10575. "map" : { type: "t", value: null },
  10576. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10577. "lightMap" : { type: "t", value: null },
  10578. "specularMap" : { type: "t", value: null },
  10579. "envMap" : { type: "t", value: null },
  10580. "flipEnvMap" : { type: "f", value: -1 },
  10581. "useRefract" : { type: "i", value: 0 },
  10582. "reflectivity" : { type: "f", value: 1.0 },
  10583. "refractionRatio" : { type: "f", value: 0.98 },
  10584. "combine" : { type: "i", value: 0 },
  10585. "morphTargetInfluences" : { type: "f", value: 0 }
  10586. },
  10587. bump: {
  10588. "bumpMap" : { type: "t", value: null },
  10589. "bumpScale" : { type: "f", value: 1 }
  10590. },
  10591. normalmap: {
  10592. "normalMap" : { type: "t", value: null },
  10593. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10594. },
  10595. fog : {
  10596. "fogDensity" : { type: "f", value: 0.00025 },
  10597. "fogNear" : { type: "f", value: 1 },
  10598. "fogFar" : { type: "f", value: 2000 },
  10599. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10600. },
  10601. lights: {
  10602. "ambientLightColor" : { type: "fv", value: [] },
  10603. "directionalLightDirection" : { type: "fv", value: [] },
  10604. "directionalLightColor" : { type: "fv", value: [] },
  10605. "hemisphereLightDirection" : { type: "fv", value: [] },
  10606. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10607. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10608. "pointLightColor" : { type: "fv", value: [] },
  10609. "pointLightPosition" : { type: "fv", value: [] },
  10610. "pointLightDistance" : { type: "fv1", value: [] },
  10611. "spotLightColor" : { type: "fv", value: [] },
  10612. "spotLightPosition" : { type: "fv", value: [] },
  10613. "spotLightDirection" : { type: "fv", value: [] },
  10614. "spotLightDistance" : { type: "fv1", value: [] },
  10615. "spotLightAngleCos" : { type: "fv1", value: [] },
  10616. "spotLightExponent" : { type: "fv1", value: [] }
  10617. },
  10618. particle: {
  10619. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10620. "opacity" : { type: "f", value: 1.0 },
  10621. "size" : { type: "f", value: 1.0 },
  10622. "scale" : { type: "f", value: 1.0 },
  10623. "map" : { type: "t", value: null },
  10624. "fogDensity" : { type: "f", value: 0.00025 },
  10625. "fogNear" : { type: "f", value: 1 },
  10626. "fogFar" : { type: "f", value: 2000 },
  10627. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10628. },
  10629. shadowmap: {
  10630. "shadowMap": { type: "tv", value: [] },
  10631. "shadowMapSize": { type: "v2v", value: [] },
  10632. "shadowBias" : { type: "fv1", value: [] },
  10633. "shadowDarkness": { type: "fv1", value: [] },
  10634. "shadowMatrix" : { type: "m4v", value: [] }
  10635. }
  10636. };
  10637. THREE.ShaderLib = {
  10638. 'basic': {
  10639. uniforms: THREE.UniformsUtils.merge( [
  10640. THREE.UniformsLib[ "common" ],
  10641. THREE.UniformsLib[ "fog" ],
  10642. THREE.UniformsLib[ "shadowmap" ]
  10643. ] ),
  10644. vertexShader: [
  10645. THREE.ShaderChunk[ "map_pars_vertex" ],
  10646. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10647. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10648. THREE.ShaderChunk[ "color_pars_vertex" ],
  10649. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10650. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10651. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10652. "void main() {",
  10653. THREE.ShaderChunk[ "map_vertex" ],
  10654. THREE.ShaderChunk[ "lightmap_vertex" ],
  10655. THREE.ShaderChunk[ "color_vertex" ],
  10656. THREE.ShaderChunk[ "skinbase_vertex" ],
  10657. "#ifdef USE_ENVMAP",
  10658. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10659. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10660. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10661. "#endif",
  10662. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10663. THREE.ShaderChunk[ "skinning_vertex" ],
  10664. THREE.ShaderChunk[ "default_vertex" ],
  10665. THREE.ShaderChunk[ "worldpos_vertex" ],
  10666. THREE.ShaderChunk[ "envmap_vertex" ],
  10667. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10668. "}"
  10669. ].join("\n"),
  10670. fragmentShader: [
  10671. "uniform vec3 diffuse;",
  10672. "uniform float opacity;",
  10673. THREE.ShaderChunk[ "color_pars_fragment" ],
  10674. THREE.ShaderChunk[ "map_pars_fragment" ],
  10675. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10676. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10677. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10678. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10679. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10680. "void main() {",
  10681. "gl_FragColor = vec4( diffuse, opacity );",
  10682. THREE.ShaderChunk[ "map_fragment" ],
  10683. THREE.ShaderChunk[ "alphatest_fragment" ],
  10684. THREE.ShaderChunk[ "specularmap_fragment" ],
  10685. THREE.ShaderChunk[ "lightmap_fragment" ],
  10686. THREE.ShaderChunk[ "color_fragment" ],
  10687. THREE.ShaderChunk[ "envmap_fragment" ],
  10688. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10689. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10690. THREE.ShaderChunk[ "fog_fragment" ],
  10691. "}"
  10692. ].join("\n")
  10693. },
  10694. 'lambert': {
  10695. uniforms: THREE.UniformsUtils.merge( [
  10696. THREE.UniformsLib[ "common" ],
  10697. THREE.UniformsLib[ "fog" ],
  10698. THREE.UniformsLib[ "lights" ],
  10699. THREE.UniformsLib[ "shadowmap" ],
  10700. {
  10701. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10702. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10703. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10704. }
  10705. ] ),
  10706. vertexShader: [
  10707. "#define LAMBERT",
  10708. "varying vec3 vLightFront;",
  10709. "#ifdef DOUBLE_SIDED",
  10710. "varying vec3 vLightBack;",
  10711. "#endif",
  10712. THREE.ShaderChunk[ "map_pars_vertex" ],
  10713. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10714. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10715. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10716. THREE.ShaderChunk[ "color_pars_vertex" ],
  10717. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10718. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10719. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10720. "void main() {",
  10721. THREE.ShaderChunk[ "map_vertex" ],
  10722. THREE.ShaderChunk[ "lightmap_vertex" ],
  10723. THREE.ShaderChunk[ "color_vertex" ],
  10724. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10725. THREE.ShaderChunk[ "skinbase_vertex" ],
  10726. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10727. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10728. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10729. THREE.ShaderChunk[ "skinning_vertex" ],
  10730. THREE.ShaderChunk[ "default_vertex" ],
  10731. THREE.ShaderChunk[ "worldpos_vertex" ],
  10732. THREE.ShaderChunk[ "envmap_vertex" ],
  10733. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10734. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10735. "}"
  10736. ].join("\n"),
  10737. fragmentShader: [
  10738. "uniform float opacity;",
  10739. "varying vec3 vLightFront;",
  10740. "#ifdef DOUBLE_SIDED",
  10741. "varying vec3 vLightBack;",
  10742. "#endif",
  10743. THREE.ShaderChunk[ "color_pars_fragment" ],
  10744. THREE.ShaderChunk[ "map_pars_fragment" ],
  10745. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10746. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10747. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10748. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10749. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10750. "void main() {",
  10751. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10752. THREE.ShaderChunk[ "map_fragment" ],
  10753. THREE.ShaderChunk[ "alphatest_fragment" ],
  10754. THREE.ShaderChunk[ "specularmap_fragment" ],
  10755. "#ifdef DOUBLE_SIDED",
  10756. //"float isFront = float( gl_FrontFacing );",
  10757. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10758. "if ( gl_FrontFacing )",
  10759. "gl_FragColor.xyz *= vLightFront;",
  10760. "else",
  10761. "gl_FragColor.xyz *= vLightBack;",
  10762. "#else",
  10763. "gl_FragColor.xyz *= vLightFront;",
  10764. "#endif",
  10765. THREE.ShaderChunk[ "lightmap_fragment" ],
  10766. THREE.ShaderChunk[ "color_fragment" ],
  10767. THREE.ShaderChunk[ "envmap_fragment" ],
  10768. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10769. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10770. THREE.ShaderChunk[ "fog_fragment" ],
  10771. "}"
  10772. ].join("\n")
  10773. },
  10774. 'phong': {
  10775. uniforms: THREE.UniformsUtils.merge( [
  10776. THREE.UniformsLib[ "common" ],
  10777. THREE.UniformsLib[ "bump" ],
  10778. THREE.UniformsLib[ "normalmap" ],
  10779. THREE.UniformsLib[ "fog" ],
  10780. THREE.UniformsLib[ "lights" ],
  10781. THREE.UniformsLib[ "shadowmap" ],
  10782. {
  10783. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10784. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10785. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10786. "shininess": { type: "f", value: 30 },
  10787. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10788. }
  10789. ] ),
  10790. vertexShader: [
  10791. "#define PHONG",
  10792. "varying vec3 vViewPosition;",
  10793. "varying vec3 vNormal;",
  10794. THREE.ShaderChunk[ "map_pars_vertex" ],
  10795. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10796. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10797. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10798. THREE.ShaderChunk[ "color_pars_vertex" ],
  10799. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10800. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10801. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10802. "void main() {",
  10803. THREE.ShaderChunk[ "map_vertex" ],
  10804. THREE.ShaderChunk[ "lightmap_vertex" ],
  10805. THREE.ShaderChunk[ "color_vertex" ],
  10806. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10807. THREE.ShaderChunk[ "skinbase_vertex" ],
  10808. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10809. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10810. "vNormal = normalize( transformedNormal );",
  10811. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10812. THREE.ShaderChunk[ "skinning_vertex" ],
  10813. THREE.ShaderChunk[ "default_vertex" ],
  10814. "vViewPosition = -mvPosition.xyz;",
  10815. THREE.ShaderChunk[ "worldpos_vertex" ],
  10816. THREE.ShaderChunk[ "envmap_vertex" ],
  10817. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10818. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10819. "}"
  10820. ].join("\n"),
  10821. fragmentShader: [
  10822. "uniform vec3 diffuse;",
  10823. "uniform float opacity;",
  10824. "uniform vec3 ambient;",
  10825. "uniform vec3 emissive;",
  10826. "uniform vec3 specular;",
  10827. "uniform float shininess;",
  10828. THREE.ShaderChunk[ "color_pars_fragment" ],
  10829. THREE.ShaderChunk[ "map_pars_fragment" ],
  10830. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10831. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10832. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10833. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10834. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10835. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10836. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10837. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10838. "void main() {",
  10839. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10840. THREE.ShaderChunk[ "map_fragment" ],
  10841. THREE.ShaderChunk[ "alphatest_fragment" ],
  10842. THREE.ShaderChunk[ "specularmap_fragment" ],
  10843. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10844. THREE.ShaderChunk[ "lightmap_fragment" ],
  10845. THREE.ShaderChunk[ "color_fragment" ],
  10846. THREE.ShaderChunk[ "envmap_fragment" ],
  10847. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10848. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10849. THREE.ShaderChunk[ "fog_fragment" ],
  10850. "}"
  10851. ].join("\n")
  10852. },
  10853. 'particle_basic': {
  10854. uniforms: THREE.UniformsUtils.merge( [
  10855. THREE.UniformsLib[ "particle" ],
  10856. THREE.UniformsLib[ "shadowmap" ]
  10857. ] ),
  10858. vertexShader: [
  10859. "uniform float size;",
  10860. "uniform float scale;",
  10861. THREE.ShaderChunk[ "color_pars_vertex" ],
  10862. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10863. "void main() {",
  10864. THREE.ShaderChunk[ "color_vertex" ],
  10865. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10866. "#ifdef USE_SIZEATTENUATION",
  10867. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10868. "#else",
  10869. "gl_PointSize = size;",
  10870. "#endif",
  10871. "gl_Position = projectionMatrix * mvPosition;",
  10872. THREE.ShaderChunk[ "worldpos_vertex" ],
  10873. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10874. "}"
  10875. ].join("\n"),
  10876. fragmentShader: [
  10877. "uniform vec3 psColor;",
  10878. "uniform float opacity;",
  10879. THREE.ShaderChunk[ "color_pars_fragment" ],
  10880. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10881. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10882. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10883. "void main() {",
  10884. "gl_FragColor = vec4( psColor, opacity );",
  10885. THREE.ShaderChunk[ "map_particle_fragment" ],
  10886. THREE.ShaderChunk[ "alphatest_fragment" ],
  10887. THREE.ShaderChunk[ "color_fragment" ],
  10888. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10889. THREE.ShaderChunk[ "fog_fragment" ],
  10890. "}"
  10891. ].join("\n")
  10892. },
  10893. 'dashed': {
  10894. uniforms: THREE.UniformsUtils.merge( [
  10895. THREE.UniformsLib[ "common" ],
  10896. THREE.UniformsLib[ "fog" ],
  10897. {
  10898. "scale": { type: "f", value: 1 },
  10899. "dashSize": { type: "f", value: 1 },
  10900. "totalSize": { type: "f", value: 2 }
  10901. }
  10902. ] ),
  10903. vertexShader: [
  10904. "uniform float scale;",
  10905. "attribute float lineDistance;",
  10906. "varying float vLineDistance;",
  10907. THREE.ShaderChunk[ "color_pars_vertex" ],
  10908. "void main() {",
  10909. THREE.ShaderChunk[ "color_vertex" ],
  10910. "vLineDistance = scale * lineDistance;",
  10911. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10912. "gl_Position = projectionMatrix * mvPosition;",
  10913. "}"
  10914. ].join("\n"),
  10915. fragmentShader: [
  10916. "uniform vec3 diffuse;",
  10917. "uniform float opacity;",
  10918. "uniform float dashSize;",
  10919. "uniform float totalSize;",
  10920. "varying float vLineDistance;",
  10921. THREE.ShaderChunk[ "color_pars_fragment" ],
  10922. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10923. "void main() {",
  10924. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10925. "discard;",
  10926. "}",
  10927. "gl_FragColor = vec4( diffuse, opacity );",
  10928. THREE.ShaderChunk[ "color_fragment" ],
  10929. THREE.ShaderChunk[ "fog_fragment" ],
  10930. "}"
  10931. ].join("\n")
  10932. },
  10933. 'depth': {
  10934. uniforms: {
  10935. "mNear": { type: "f", value: 1.0 },
  10936. "mFar" : { type: "f", value: 2000.0 },
  10937. "opacity" : { type: "f", value: 1.0 }
  10938. },
  10939. vertexShader: [
  10940. "void main() {",
  10941. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10942. "}"
  10943. ].join("\n"),
  10944. fragmentShader: [
  10945. "uniform float mNear;",
  10946. "uniform float mFar;",
  10947. "uniform float opacity;",
  10948. "void main() {",
  10949. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10950. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  10951. "gl_FragColor = vec4( vec3( color ), opacity );",
  10952. "}"
  10953. ].join("\n")
  10954. },
  10955. 'normal': {
  10956. uniforms: {
  10957. "opacity" : { type: "f", value: 1.0 }
  10958. },
  10959. vertexShader: [
  10960. "varying vec3 vNormal;",
  10961. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10962. "void main() {",
  10963. "vNormal = normalize( normalMatrix * normal );",
  10964. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10965. THREE.ShaderChunk[ "default_vertex" ],
  10966. "}"
  10967. ].join("\n"),
  10968. fragmentShader: [
  10969. "uniform float opacity;",
  10970. "varying vec3 vNormal;",
  10971. "void main() {",
  10972. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  10973. "}"
  10974. ].join("\n")
  10975. },
  10976. /* -------------------------------------------------------------------------
  10977. // Normal map shader
  10978. // - Blinn-Phong
  10979. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  10980. // - point and directional lights (use with "lights: true" material option)
  10981. ------------------------------------------------------------------------- */
  10982. 'normalmap' : {
  10983. uniforms: THREE.UniformsUtils.merge( [
  10984. THREE.UniformsLib[ "fog" ],
  10985. THREE.UniformsLib[ "lights" ],
  10986. THREE.UniformsLib[ "shadowmap" ],
  10987. {
  10988. "enableAO" : { type: "i", value: 0 },
  10989. "enableDiffuse" : { type: "i", value: 0 },
  10990. "enableSpecular" : { type: "i", value: 0 },
  10991. "enableReflection": { type: "i", value: 0 },
  10992. "enableDisplacement": { type: "i", value: 0 },
  10993. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  10994. "tDiffuse" : { type: "t", value: null },
  10995. "tCube" : { type: "t", value: null },
  10996. "tNormal" : { type: "t", value: null },
  10997. "tSpecular" : { type: "t", value: null },
  10998. "tAO" : { type: "t", value: null },
  10999. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11000. "uDisplacementBias": { type: "f", value: 0.0 },
  11001. "uDisplacementScale": { type: "f", value: 1.0 },
  11002. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11003. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  11004. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11005. "uShininess": { type: "f", value: 30 },
  11006. "uOpacity": { type: "f", value: 1 },
  11007. "useRefract": { type: "i", value: 0 },
  11008. "uRefractionRatio": { type: "f", value: 0.98 },
  11009. "uReflectivity": { type: "f", value: 0.5 },
  11010. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11011. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11012. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11013. }
  11014. ] ),
  11015. fragmentShader: [
  11016. "uniform vec3 uAmbientColor;",
  11017. "uniform vec3 uDiffuseColor;",
  11018. "uniform vec3 uSpecularColor;",
  11019. "uniform float uShininess;",
  11020. "uniform float uOpacity;",
  11021. "uniform bool enableDiffuse;",
  11022. "uniform bool enableSpecular;",
  11023. "uniform bool enableAO;",
  11024. "uniform bool enableReflection;",
  11025. "uniform sampler2D tDiffuse;",
  11026. "uniform sampler2D tNormal;",
  11027. "uniform sampler2D tSpecular;",
  11028. "uniform sampler2D tAO;",
  11029. "uniform samplerCube tCube;",
  11030. "uniform vec2 uNormalScale;",
  11031. "uniform bool useRefract;",
  11032. "uniform float uRefractionRatio;",
  11033. "uniform float uReflectivity;",
  11034. "varying vec3 vTangent;",
  11035. "varying vec3 vBinormal;",
  11036. "varying vec3 vNormal;",
  11037. "varying vec2 vUv;",
  11038. "uniform vec3 ambientLightColor;",
  11039. "#if MAX_DIR_LIGHTS > 0",
  11040. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11041. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11042. "#endif",
  11043. "#if MAX_HEMI_LIGHTS > 0",
  11044. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11045. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11046. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11047. "#endif",
  11048. "#if MAX_POINT_LIGHTS > 0",
  11049. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11050. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11051. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11052. "#endif",
  11053. "#if MAX_SPOT_LIGHTS > 0",
  11054. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11055. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11056. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11057. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11058. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11059. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11060. "#endif",
  11061. "#ifdef WRAP_AROUND",
  11062. "uniform vec3 wrapRGB;",
  11063. "#endif",
  11064. "varying vec3 vWorldPosition;",
  11065. "varying vec3 vViewPosition;",
  11066. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11067. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11068. "void main() {",
  11069. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  11070. "vec3 specularTex = vec3( 1.0 );",
  11071. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11072. "normalTex.xy *= uNormalScale;",
  11073. "normalTex = normalize( normalTex );",
  11074. "if( enableDiffuse ) {",
  11075. "#ifdef GAMMA_INPUT",
  11076. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  11077. "texelColor.xyz *= texelColor.xyz;",
  11078. "gl_FragColor = gl_FragColor * texelColor;",
  11079. "#else",
  11080. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11081. "#endif",
  11082. "}",
  11083. "if( enableAO ) {",
  11084. "#ifdef GAMMA_INPUT",
  11085. "vec4 aoColor = texture2D( tAO, vUv );",
  11086. "aoColor.xyz *= aoColor.xyz;",
  11087. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11088. "#else",
  11089. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11090. "#endif",
  11091. "}",
  11092. "if( enableSpecular )",
  11093. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  11094. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11095. "vec3 finalNormal = tsb * normalTex;",
  11096. "#ifdef FLIP_SIDED",
  11097. "finalNormal = -finalNormal;",
  11098. "#endif",
  11099. "vec3 normal = normalize( finalNormal );",
  11100. "vec3 viewPosition = normalize( vViewPosition );",
  11101. // point lights
  11102. "#if MAX_POINT_LIGHTS > 0",
  11103. "vec3 pointDiffuse = vec3( 0.0 );",
  11104. "vec3 pointSpecular = vec3( 0.0 );",
  11105. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11106. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11107. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  11108. "float pointDistance = 1.0;",
  11109. "if ( pointLightDistance[ i ] > 0.0 )",
  11110. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  11111. "pointVector = normalize( pointVector );",
  11112. // diffuse
  11113. "#ifdef WRAP_AROUND",
  11114. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11115. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11116. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11117. "#else",
  11118. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11119. "#endif",
  11120. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  11121. // specular
  11122. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11123. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11124. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  11125. "#ifdef PHYSICALLY_BASED_SHADING",
  11126. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11127. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11128. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11129. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11130. "#else",
  11131. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  11132. "#endif",
  11133. "}",
  11134. "#endif",
  11135. // spot lights
  11136. "#if MAX_SPOT_LIGHTS > 0",
  11137. "vec3 spotDiffuse = vec3( 0.0 );",
  11138. "vec3 spotSpecular = vec3( 0.0 );",
  11139. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11140. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11141. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  11142. "float spotDistance = 1.0;",
  11143. "if ( spotLightDistance[ i ] > 0.0 )",
  11144. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  11145. "spotVector = normalize( spotVector );",
  11146. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11147. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11148. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11149. // diffuse
  11150. "#ifdef WRAP_AROUND",
  11151. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  11152. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  11153. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11154. "#else",
  11155. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  11156. "#endif",
  11157. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  11158. // specular
  11159. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  11160. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11161. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  11162. "#ifdef PHYSICALLY_BASED_SHADING",
  11163. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11164. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11165. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  11166. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  11167. "#else",
  11168. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  11169. "#endif",
  11170. "}",
  11171. "}",
  11172. "#endif",
  11173. // directional lights
  11174. "#if MAX_DIR_LIGHTS > 0",
  11175. "vec3 dirDiffuse = vec3( 0.0 );",
  11176. "vec3 dirSpecular = vec3( 0.0 );",
  11177. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11178. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11179. "vec3 dirVector = normalize( lDirection.xyz );",
  11180. // diffuse
  11181. "#ifdef WRAP_AROUND",
  11182. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11183. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11184. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11185. "#else",
  11186. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11187. "#endif",
  11188. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  11189. // specular
  11190. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11191. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11192. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  11193. "#ifdef PHYSICALLY_BASED_SHADING",
  11194. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11195. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11196. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11197. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11198. "#else",
  11199. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  11200. "#endif",
  11201. "}",
  11202. "#endif",
  11203. // hemisphere lights
  11204. "#if MAX_HEMI_LIGHTS > 0",
  11205. "vec3 hemiDiffuse = vec3( 0.0 );",
  11206. "vec3 hemiSpecular = vec3( 0.0 );" ,
  11207. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11208. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11209. "vec3 lVector = normalize( lDirection.xyz );",
  11210. // diffuse
  11211. "float dotProduct = dot( normal, lVector );",
  11212. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11213. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11214. "hemiDiffuse += uDiffuseColor * hemiColor;",
  11215. // specular (sky light)
  11216. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11217. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11218. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  11219. // specular (ground light)
  11220. "vec3 lVectorGround = -lVector;",
  11221. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11222. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11223. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  11224. "#ifdef PHYSICALLY_BASED_SHADING",
  11225. "float dotProductGround = dot( normal, lVectorGround );",
  11226. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11227. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11228. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  11229. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  11230. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11231. "#else",
  11232. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  11233. "#endif",
  11234. "}",
  11235. "#endif",
  11236. // all lights contribution summation
  11237. "vec3 totalDiffuse = vec3( 0.0 );",
  11238. "vec3 totalSpecular = vec3( 0.0 );",
  11239. "#if MAX_DIR_LIGHTS > 0",
  11240. "totalDiffuse += dirDiffuse;",
  11241. "totalSpecular += dirSpecular;",
  11242. "#endif",
  11243. "#if MAX_HEMI_LIGHTS > 0",
  11244. "totalDiffuse += hemiDiffuse;",
  11245. "totalSpecular += hemiSpecular;",
  11246. "#endif",
  11247. "#if MAX_POINT_LIGHTS > 0",
  11248. "totalDiffuse += pointDiffuse;",
  11249. "totalSpecular += pointSpecular;",
  11250. "#endif",
  11251. "#if MAX_SPOT_LIGHTS > 0",
  11252. "totalDiffuse += spotDiffuse;",
  11253. "totalSpecular += spotSpecular;",
  11254. "#endif",
  11255. "#ifdef METAL",
  11256. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  11257. "#else",
  11258. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  11259. "#endif",
  11260. "if ( enableReflection ) {",
  11261. "vec3 vReflect;",
  11262. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  11263. "if ( useRefract ) {",
  11264. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  11265. "} else {",
  11266. "vReflect = reflect( cameraToVertex, normal );",
  11267. "}",
  11268. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11269. "#ifdef GAMMA_INPUT",
  11270. "cubeColor.xyz *= cubeColor.xyz;",
  11271. "#endif",
  11272. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  11273. "}",
  11274. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11275. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11276. THREE.ShaderChunk[ "fog_fragment" ],
  11277. "}"
  11278. ].join("\n"),
  11279. vertexShader: [
  11280. "attribute vec4 tangent;",
  11281. "uniform vec2 uOffset;",
  11282. "uniform vec2 uRepeat;",
  11283. "uniform bool enableDisplacement;",
  11284. "#ifdef VERTEX_TEXTURES",
  11285. "uniform sampler2D tDisplacement;",
  11286. "uniform float uDisplacementScale;",
  11287. "uniform float uDisplacementBias;",
  11288. "#endif",
  11289. "varying vec3 vTangent;",
  11290. "varying vec3 vBinormal;",
  11291. "varying vec3 vNormal;",
  11292. "varying vec2 vUv;",
  11293. "varying vec3 vWorldPosition;",
  11294. "varying vec3 vViewPosition;",
  11295. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11296. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11297. "void main() {",
  11298. THREE.ShaderChunk[ "skinbase_vertex" ],
  11299. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11300. // normal, tangent and binormal vectors
  11301. "#ifdef USE_SKINNING",
  11302. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  11303. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  11304. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  11305. "#else",
  11306. "vNormal = normalize( normalMatrix * normal );",
  11307. "vTangent = normalize( normalMatrix * tangent.xyz );",
  11308. "#endif",
  11309. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  11310. "vUv = uv * uRepeat + uOffset;",
  11311. // displacement mapping
  11312. "vec3 displacedPosition;",
  11313. "#ifdef VERTEX_TEXTURES",
  11314. "if ( enableDisplacement ) {",
  11315. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11316. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11317. "displacedPosition = position + normalize( normal ) * df;",
  11318. "} else {",
  11319. "#ifdef USE_SKINNING",
  11320. "vec4 skinVertex = vec4( position, 1.0 );",
  11321. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11322. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11323. "displacedPosition = skinned.xyz;",
  11324. "#else",
  11325. "displacedPosition = position;",
  11326. "#endif",
  11327. "}",
  11328. "#else",
  11329. "#ifdef USE_SKINNING",
  11330. "vec4 skinVertex = vec4( position, 1.0 );",
  11331. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11332. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11333. "displacedPosition = skinned.xyz;",
  11334. "#else",
  11335. "displacedPosition = position;",
  11336. "#endif",
  11337. "#endif",
  11338. //
  11339. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  11340. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  11341. "gl_Position = projectionMatrix * mvPosition;",
  11342. //
  11343. "vWorldPosition = worldPosition.xyz;",
  11344. "vViewPosition = -mvPosition.xyz;",
  11345. // shadows
  11346. "#ifdef USE_SHADOWMAP",
  11347. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11348. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11349. "}",
  11350. "#endif",
  11351. "}"
  11352. ].join("\n")
  11353. },
  11354. /* -------------------------------------------------------------------------
  11355. // Cube map shader
  11356. ------------------------------------------------------------------------- */
  11357. 'cube': {
  11358. uniforms: { "tCube": { type: "t", value: null },
  11359. "tFlip": { type: "f", value: -1 } },
  11360. vertexShader: [
  11361. "varying vec3 vWorldPosition;",
  11362. "void main() {",
  11363. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  11364. "vWorldPosition = worldPosition.xyz;",
  11365. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11366. "}"
  11367. ].join("\n"),
  11368. fragmentShader: [
  11369. "uniform samplerCube tCube;",
  11370. "uniform float tFlip;",
  11371. "varying vec3 vWorldPosition;",
  11372. "void main() {",
  11373. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11374. "}"
  11375. ].join("\n")
  11376. },
  11377. // Depth encoding into RGBA texture
  11378. // based on SpiderGL shadow map example
  11379. // http://spidergl.org/example.php?id=6
  11380. // originally from
  11381. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11382. // see also here:
  11383. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11384. 'depthRGBA': {
  11385. uniforms: {},
  11386. vertexShader: [
  11387. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11388. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11389. "void main() {",
  11390. THREE.ShaderChunk[ "skinbase_vertex" ],
  11391. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11392. THREE.ShaderChunk[ "skinning_vertex" ],
  11393. THREE.ShaderChunk[ "default_vertex" ],
  11394. "}"
  11395. ].join("\n"),
  11396. fragmentShader: [
  11397. "vec4 pack_depth( const in float depth ) {",
  11398. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11399. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11400. "vec4 res = fract( depth * bit_shift );",
  11401. "res -= res.xxyz * bit_mask;",
  11402. "return res;",
  11403. "}",
  11404. "void main() {",
  11405. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  11406. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  11407. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  11408. //"gl_FragData[ 0 ] = pack_depth( z );",
  11409. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  11410. "}"
  11411. ].join("\n")
  11412. }
  11413. };
  11414. /**
  11415. * @author supereggbert / http://www.paulbrunt.co.uk/
  11416. * @author mrdoob / http://mrdoob.com/
  11417. * @author alteredq / http://alteredqualia.com/
  11418. * @author szimek / https://github.com/szimek/
  11419. */
  11420. THREE.WebGLRenderer = function ( parameters ) {
  11421. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  11422. parameters = parameters || {};
  11423. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11424. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  11425. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  11426. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11427. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11428. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11429. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  11430. _clearColor = new THREE.Color( 0x000000 ),
  11431. _clearAlpha = 0;
  11432. if ( parameters.clearColor !== undefined ) {
  11433. console.warn( 'DEPRECATED: clearColor in WebGLRenderer constructor parameters is being removed. Use .setClearColor() instead.' );
  11434. _clearColor.setHex( parameters.clearColor );
  11435. }
  11436. if ( parameters.clearAlpha !== undefined ) {
  11437. console.warn( 'DEPRECATED: clearAlpha in WebGLRenderer constructor parameters is being removed. Use .setClearColor() instead.' );
  11438. _clearAlpha = parameters.clearAlpha;
  11439. }
  11440. // public properties
  11441. this.domElement = _canvas;
  11442. this.context = null;
  11443. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  11444. ? parameters.devicePixelRatio
  11445. : window.devicePixelRatio !== undefined
  11446. ? window.devicePixelRatio
  11447. : 1;
  11448. // clearing
  11449. this.autoClear = true;
  11450. this.autoClearColor = true;
  11451. this.autoClearDepth = true;
  11452. this.autoClearStencil = true;
  11453. // scene graph
  11454. this.sortObjects = true;
  11455. this.autoUpdateObjects = true;
  11456. // physically based shading
  11457. this.gammaInput = false;
  11458. this.gammaOutput = false;
  11459. this.physicallyBasedShading = false;
  11460. // shadow map
  11461. this.shadowMapEnabled = false;
  11462. this.shadowMapAutoUpdate = true;
  11463. this.shadowMapType = THREE.PCFShadowMap;
  11464. this.shadowMapCullFace = THREE.CullFaceFront;
  11465. this.shadowMapDebug = false;
  11466. this.shadowMapCascade = false;
  11467. // morphs
  11468. this.maxMorphTargets = 8;
  11469. this.maxMorphNormals = 4;
  11470. // flags
  11471. this.autoScaleCubemaps = true;
  11472. // custom render plugins
  11473. this.renderPluginsPre = [];
  11474. this.renderPluginsPost = [];
  11475. // info
  11476. this.info = {
  11477. memory: {
  11478. programs: 0,
  11479. geometries: 0,
  11480. textures: 0
  11481. },
  11482. render: {
  11483. calls: 0,
  11484. vertices: 0,
  11485. faces: 0,
  11486. points: 0
  11487. }
  11488. };
  11489. // internal properties
  11490. var _this = this,
  11491. _programs = [],
  11492. _programs_counter = 0,
  11493. // internal state cache
  11494. _currentProgram = null,
  11495. _currentFramebuffer = null,
  11496. _currentMaterialId = -1,
  11497. _currentGeometryGroupHash = null,
  11498. _currentCamera = null,
  11499. _geometryGroupCounter = 0,
  11500. _usedTextureUnits = 0,
  11501. // GL state cache
  11502. _oldDoubleSided = -1,
  11503. _oldFlipSided = -1,
  11504. _oldBlending = -1,
  11505. _oldBlendEquation = -1,
  11506. _oldBlendSrc = -1,
  11507. _oldBlendDst = -1,
  11508. _oldDepthTest = -1,
  11509. _oldDepthWrite = -1,
  11510. _oldPolygonOffset = null,
  11511. _oldPolygonOffsetFactor = null,
  11512. _oldPolygonOffsetUnits = null,
  11513. _oldLineWidth = null,
  11514. _viewportX = 0,
  11515. _viewportY = 0,
  11516. _viewportWidth = 0,
  11517. _viewportHeight = 0,
  11518. _currentWidth = 0,
  11519. _currentHeight = 0,
  11520. _enabledAttributes = {},
  11521. // frustum
  11522. _frustum = new THREE.Frustum(),
  11523. // camera matrices cache
  11524. _projScreenMatrix = new THREE.Matrix4(),
  11525. _projScreenMatrixPS = new THREE.Matrix4(),
  11526. _vector3 = new THREE.Vector3(),
  11527. // light arrays cache
  11528. _direction = new THREE.Vector3(),
  11529. _lightsNeedUpdate = true,
  11530. _lights = {
  11531. ambient: [ 0, 0, 0 ],
  11532. directional: { length: 0, colors: new Array(), positions: new Array() },
  11533. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  11534. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  11535. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  11536. };
  11537. // initialize
  11538. var _gl;
  11539. var _glExtensionTextureFloat;
  11540. var _glExtensionTextureFloatLinear;
  11541. var _glExtensionStandardDerivatives;
  11542. var _glExtensionTextureFilterAnisotropic;
  11543. var _glExtensionCompressedTextureS3TC;
  11544. initGL();
  11545. setDefaultGLState();
  11546. this.context = _gl;
  11547. // GPU capabilities
  11548. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  11549. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11550. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  11551. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11552. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  11553. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  11554. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  11555. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  11556. //
  11557. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  11558. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  11559. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  11560. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  11561. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  11562. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  11563. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  11564. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  11565. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  11566. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  11567. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  11568. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  11569. // clamp precision to maximum available
  11570. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  11571. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  11572. if ( _precision === "highp" && ! highpAvailable ) {
  11573. if ( mediumpAvailable ) {
  11574. _precision = "mediump";
  11575. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  11576. } else {
  11577. _precision = "lowp";
  11578. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  11579. }
  11580. }
  11581. if ( _precision === "mediump" && ! mediumpAvailable ) {
  11582. _precision = "lowp";
  11583. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  11584. }
  11585. // API
  11586. this.getContext = function () {
  11587. return _gl;
  11588. };
  11589. this.supportsVertexTextures = function () {
  11590. return _supportsVertexTextures;
  11591. };
  11592. this.supportsFloatTextures = function () {
  11593. return _glExtensionTextureFloat;
  11594. };
  11595. this.supportsStandardDerivatives = function () {
  11596. return _glExtensionStandardDerivatives;
  11597. };
  11598. this.supportsCompressedTextureS3TC = function () {
  11599. return _glExtensionCompressedTextureS3TC;
  11600. };
  11601. this.getMaxAnisotropy = function () {
  11602. return _maxAnisotropy;
  11603. };
  11604. this.getPrecision = function () {
  11605. return _precision;
  11606. };
  11607. this.setSize = function ( width, height, updateStyle ) {
  11608. _canvas.width = width * this.devicePixelRatio;
  11609. _canvas.height = height * this.devicePixelRatio;
  11610. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  11611. _canvas.style.width = width + 'px';
  11612. _canvas.style.height = height + 'px';
  11613. }
  11614. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  11615. };
  11616. this.setViewport = function ( x, y, width, height ) {
  11617. _viewportX = x !== undefined ? x : 0;
  11618. _viewportY = y !== undefined ? y : 0;
  11619. _viewportWidth = width !== undefined ? width : _canvas.width;
  11620. _viewportHeight = height !== undefined ? height : _canvas.height;
  11621. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11622. };
  11623. this.setScissor = function ( x, y, width, height ) {
  11624. _gl.scissor( x, y, width, height );
  11625. };
  11626. this.enableScissorTest = function ( enable ) {
  11627. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  11628. };
  11629. // Clearing
  11630. this.setClearColor = function ( color, alpha ) {
  11631. _clearColor.set( color );
  11632. _clearAlpha = alpha !== undefined ? alpha : 1;
  11633. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11634. };
  11635. this.setClearColorHex = function ( hex, alpha ) {
  11636. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  11637. this.setClearColor( hex, alpha );
  11638. };
  11639. this.getClearColor = function () {
  11640. return _clearColor;
  11641. };
  11642. this.getClearAlpha = function () {
  11643. return _clearAlpha;
  11644. };
  11645. this.clear = function ( color, depth, stencil ) {
  11646. var bits = 0;
  11647. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11648. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11649. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11650. _gl.clear( bits );
  11651. };
  11652. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11653. this.setRenderTarget( renderTarget );
  11654. this.clear( color, depth, stencil );
  11655. };
  11656. // Plugins
  11657. this.addPostPlugin = function ( plugin ) {
  11658. plugin.init( this );
  11659. this.renderPluginsPost.push( plugin );
  11660. };
  11661. this.addPrePlugin = function ( plugin ) {
  11662. plugin.init( this );
  11663. this.renderPluginsPre.push( plugin );
  11664. };
  11665. // Rendering
  11666. this.updateShadowMap = function ( scene, camera ) {
  11667. _currentProgram = null;
  11668. _oldBlending = -1;
  11669. _oldDepthTest = -1;
  11670. _oldDepthWrite = -1;
  11671. _currentGeometryGroupHash = -1;
  11672. _currentMaterialId = -1;
  11673. _lightsNeedUpdate = true;
  11674. _oldDoubleSided = -1;
  11675. _oldFlipSided = -1;
  11676. this.shadowMapPlugin.update( scene, camera );
  11677. };
  11678. // Internal functions
  11679. // Buffer allocation
  11680. function createParticleBuffers ( geometry ) {
  11681. geometry.__webglVertexBuffer = _gl.createBuffer();
  11682. geometry.__webglColorBuffer = _gl.createBuffer();
  11683. _this.info.memory.geometries ++;
  11684. };
  11685. function createLineBuffers ( geometry ) {
  11686. geometry.__webglVertexBuffer = _gl.createBuffer();
  11687. geometry.__webglColorBuffer = _gl.createBuffer();
  11688. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  11689. _this.info.memory.geometries ++;
  11690. };
  11691. function createRibbonBuffers ( geometry ) {
  11692. geometry.__webglVertexBuffer = _gl.createBuffer();
  11693. geometry.__webglColorBuffer = _gl.createBuffer();
  11694. geometry.__webglNormalBuffer = _gl.createBuffer();
  11695. _this.info.memory.geometries ++;
  11696. };
  11697. function createMeshBuffers ( geometryGroup ) {
  11698. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  11699. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  11700. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  11701. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  11702. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  11703. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  11704. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  11705. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  11706. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  11707. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  11708. var m, ml;
  11709. if ( geometryGroup.numMorphTargets ) {
  11710. geometryGroup.__webglMorphTargetsBuffers = [];
  11711. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11712. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  11713. }
  11714. }
  11715. if ( geometryGroup.numMorphNormals ) {
  11716. geometryGroup.__webglMorphNormalsBuffers = [];
  11717. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11718. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  11719. }
  11720. }
  11721. _this.info.memory.geometries ++;
  11722. };
  11723. // Events
  11724. var onGeometryDispose = function ( event ) {
  11725. var geometry = event.target;
  11726. geometry.removeEventListener( 'dispose', onGeometryDispose );
  11727. deallocateGeometry( geometry );
  11728. };
  11729. var onTextureDispose = function ( event ) {
  11730. var texture = event.target;
  11731. texture.removeEventListener( 'dispose', onTextureDispose );
  11732. deallocateTexture( texture );
  11733. _this.info.memory.textures --;
  11734. };
  11735. var onRenderTargetDispose = function ( event ) {
  11736. var renderTarget = event.target;
  11737. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11738. deallocateRenderTarget( renderTarget );
  11739. _this.info.memory.textures --;
  11740. };
  11741. var onMaterialDispose = function ( event ) {
  11742. var material = event.target;
  11743. material.removeEventListener( 'dispose', onMaterialDispose );
  11744. deallocateMaterial( material );
  11745. };
  11746. // Buffer deallocation
  11747. var deleteBuffers = function ( geometry ) {
  11748. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11749. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  11750. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  11751. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  11752. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  11753. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  11754. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  11755. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  11756. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  11757. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  11758. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  11759. // custom attributes
  11760. if ( geometry.__webglCustomAttributesList !== undefined ) {
  11761. for ( var id in geometry.__webglCustomAttributesList ) {
  11762. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  11763. }
  11764. }
  11765. _this.info.memory.geometries --;
  11766. };
  11767. var deallocateGeometry = function ( geometry ) {
  11768. geometry.__webglInit = undefined;
  11769. if ( geometry instanceof THREE.BufferGeometry ) {
  11770. var attributes = geometry.attributes;
  11771. for ( var key in attributes ) {
  11772. if ( attributes[ key ].buffer !== undefined ) {
  11773. _gl.deleteBuffer( attributes[ key ].buffer );
  11774. }
  11775. }
  11776. _this.info.memory.geometries --;
  11777. } else {
  11778. if ( geometry.geometryGroups !== undefined ) {
  11779. for ( var g in geometry.geometryGroups ) {
  11780. var geometryGroup = geometry.geometryGroups[ g ];
  11781. if ( geometryGroup.numMorphTargets !== undefined ) {
  11782. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11783. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11784. }
  11785. }
  11786. if ( geometryGroup.numMorphNormals !== undefined ) {
  11787. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11788. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11789. }
  11790. }
  11791. deleteBuffers( geometryGroup );
  11792. }
  11793. } else {
  11794. deleteBuffers( geometry );
  11795. }
  11796. }
  11797. };
  11798. var deallocateTexture = function ( texture ) {
  11799. if ( texture.image && texture.image.__webglTextureCube ) {
  11800. // cube texture
  11801. _gl.deleteTexture( texture.image.__webglTextureCube );
  11802. } else {
  11803. // 2D texture
  11804. if ( ! texture.__webglInit ) return;
  11805. texture.__webglInit = false;
  11806. _gl.deleteTexture( texture.__webglTexture );
  11807. }
  11808. };
  11809. var deallocateRenderTarget = function ( renderTarget ) {
  11810. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  11811. _gl.deleteTexture( renderTarget.__webglTexture );
  11812. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  11813. for ( var i = 0; i < 6; i ++ ) {
  11814. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  11815. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  11816. }
  11817. } else {
  11818. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  11819. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  11820. }
  11821. };
  11822. var deallocateMaterial = function ( material ) {
  11823. var program = material.program;
  11824. if ( program === undefined ) return;
  11825. material.program = undefined;
  11826. // only deallocate GL program if this was the last use of shared program
  11827. // assumed there is only single copy of any program in the _programs list
  11828. // (that's how it's constructed)
  11829. var i, il, programInfo;
  11830. var deleteProgram = false;
  11831. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11832. programInfo = _programs[ i ];
  11833. if ( programInfo.program === program ) {
  11834. programInfo.usedTimes --;
  11835. if ( programInfo.usedTimes === 0 ) {
  11836. deleteProgram = true;
  11837. }
  11838. break;
  11839. }
  11840. }
  11841. if ( deleteProgram === true ) {
  11842. // avoid using array.splice, this is costlier than creating new array from scratch
  11843. var newPrograms = [];
  11844. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11845. programInfo = _programs[ i ];
  11846. if ( programInfo.program !== program ) {
  11847. newPrograms.push( programInfo );
  11848. }
  11849. }
  11850. _programs = newPrograms;
  11851. _gl.deleteProgram( program );
  11852. _this.info.memory.programs --;
  11853. }
  11854. };
  11855. // Buffer initialization
  11856. function initCustomAttributes ( geometry, object ) {
  11857. var nvertices = geometry.vertices.length;
  11858. var material = object.material;
  11859. if ( material.attributes ) {
  11860. if ( geometry.__webglCustomAttributesList === undefined ) {
  11861. geometry.__webglCustomAttributesList = [];
  11862. }
  11863. for ( var a in material.attributes ) {
  11864. var attribute = material.attributes[ a ];
  11865. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11866. attribute.__webglInitialized = true;
  11867. var size = 1; // "f" and "i"
  11868. if ( attribute.type === "v2" ) size = 2;
  11869. else if ( attribute.type === "v3" ) size = 3;
  11870. else if ( attribute.type === "v4" ) size = 4;
  11871. else if ( attribute.type === "c" ) size = 3;
  11872. attribute.size = size;
  11873. attribute.array = new Float32Array( nvertices * size );
  11874. attribute.buffer = _gl.createBuffer();
  11875. attribute.buffer.belongsToAttribute = a;
  11876. attribute.needsUpdate = true;
  11877. }
  11878. geometry.__webglCustomAttributesList.push( attribute );
  11879. }
  11880. }
  11881. };
  11882. function initParticleBuffers ( geometry, object ) {
  11883. var nvertices = geometry.vertices.length;
  11884. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11885. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11886. geometry.__sortArray = [];
  11887. geometry.__webglParticleCount = nvertices;
  11888. initCustomAttributes ( geometry, object );
  11889. };
  11890. function initLineBuffers ( geometry, object ) {
  11891. var nvertices = geometry.vertices.length;
  11892. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11893. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11894. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  11895. geometry.__webglLineCount = nvertices;
  11896. initCustomAttributes ( geometry, object );
  11897. };
  11898. function initRibbonBuffers ( geometry, object ) {
  11899. var nvertices = geometry.vertices.length;
  11900. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11901. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11902. geometry.__normalArray = new Float32Array( nvertices * 3 );
  11903. geometry.__webglVertexCount = nvertices;
  11904. initCustomAttributes ( geometry, object );
  11905. };
  11906. function initMeshBuffers ( geometryGroup, object ) {
  11907. var geometry = object.geometry,
  11908. faces3 = geometryGroup.faces3,
  11909. nvertices = faces3.length * 3,
  11910. ntris = faces3.length * 1,
  11911. nlines = faces3.length * 3,
  11912. material = getBufferMaterial( object, geometryGroup ),
  11913. uvType = bufferGuessUVType( material ),
  11914. normalType = bufferGuessNormalType( material ),
  11915. vertexColorType = bufferGuessVertexColorType( material );
  11916. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  11917. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  11918. if ( normalType ) {
  11919. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  11920. }
  11921. if ( geometry.hasTangents ) {
  11922. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  11923. }
  11924. if ( vertexColorType ) {
  11925. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  11926. }
  11927. if ( uvType ) {
  11928. if ( geometry.faceVertexUvs.length > 0 ) {
  11929. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  11930. }
  11931. if ( geometry.faceVertexUvs.length > 1 ) {
  11932. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  11933. }
  11934. }
  11935. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  11936. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  11937. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  11938. }
  11939. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  11940. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  11941. var m, ml;
  11942. if ( geometryGroup.numMorphTargets ) {
  11943. geometryGroup.__morphTargetsArrays = [];
  11944. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11945. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  11946. }
  11947. }
  11948. if ( geometryGroup.numMorphNormals ) {
  11949. geometryGroup.__morphNormalsArrays = [];
  11950. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11951. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  11952. }
  11953. }
  11954. geometryGroup.__webglFaceCount = ntris * 3;
  11955. geometryGroup.__webglLineCount = nlines * 2;
  11956. // custom attributes
  11957. if ( material.attributes ) {
  11958. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  11959. geometryGroup.__webglCustomAttributesList = [];
  11960. }
  11961. for ( var a in material.attributes ) {
  11962. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  11963. // attribute buffers which are correctly indexed in the setMeshBuffers function
  11964. var originalAttribute = material.attributes[ a ];
  11965. var attribute = {};
  11966. for ( var property in originalAttribute ) {
  11967. attribute[ property ] = originalAttribute[ property ];
  11968. }
  11969. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11970. attribute.__webglInitialized = true;
  11971. var size = 1; // "f" and "i"
  11972. if( attribute.type === "v2" ) size = 2;
  11973. else if( attribute.type === "v3" ) size = 3;
  11974. else if( attribute.type === "v4" ) size = 4;
  11975. else if( attribute.type === "c" ) size = 3;
  11976. attribute.size = size;
  11977. attribute.array = new Float32Array( nvertices * size );
  11978. attribute.buffer = _gl.createBuffer();
  11979. attribute.buffer.belongsToAttribute = a;
  11980. originalAttribute.needsUpdate = true;
  11981. attribute.__original = originalAttribute;
  11982. }
  11983. geometryGroup.__webglCustomAttributesList.push( attribute );
  11984. }
  11985. }
  11986. geometryGroup.__inittedArrays = true;
  11987. };
  11988. function getBufferMaterial( object, geometryGroup ) {
  11989. return object.material instanceof THREE.MeshFaceMaterial
  11990. ? object.material.materials[ geometryGroup.materialIndex ]
  11991. : object.material;
  11992. };
  11993. function materialNeedsSmoothNormals ( material ) {
  11994. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  11995. };
  11996. function bufferGuessNormalType ( material ) {
  11997. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  11998. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  11999. return false;
  12000. }
  12001. if ( materialNeedsSmoothNormals( material ) ) {
  12002. return THREE.SmoothShading;
  12003. } else {
  12004. return THREE.FlatShading;
  12005. }
  12006. };
  12007. function bufferGuessVertexColorType( material ) {
  12008. if ( material.vertexColors ) {
  12009. return material.vertexColors;
  12010. }
  12011. return false;
  12012. };
  12013. function bufferGuessUVType( material ) {
  12014. // material must use some texture to require uvs
  12015. if ( material.map ||
  12016. material.lightMap ||
  12017. material.bumpMap ||
  12018. material.normalMap ||
  12019. material.specularMap ||
  12020. material instanceof THREE.ShaderMaterial ) {
  12021. return true;
  12022. }
  12023. return false;
  12024. };
  12025. //
  12026. function initDirectBuffers( geometry ) {
  12027. var a, attribute, type;
  12028. for ( a in geometry.attributes ) {
  12029. if ( a === "index" ) {
  12030. type = _gl.ELEMENT_ARRAY_BUFFER;
  12031. } else {
  12032. type = _gl.ARRAY_BUFFER;
  12033. }
  12034. attribute = geometry.attributes[ a ];
  12035. if ( attribute.numItems === undefined ) {
  12036. attribute.numItems = attribute.array.length;
  12037. }
  12038. attribute.buffer = _gl.createBuffer();
  12039. _gl.bindBuffer( type, attribute.buffer );
  12040. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  12041. }
  12042. };
  12043. // Buffer setting
  12044. function setParticleBuffers ( geometry, hint, object ) {
  12045. var v, c, vertex, offset, index, color,
  12046. vertices = geometry.vertices,
  12047. vl = vertices.length,
  12048. colors = geometry.colors,
  12049. cl = colors.length,
  12050. vertexArray = geometry.__vertexArray,
  12051. colorArray = geometry.__colorArray,
  12052. sortArray = geometry.__sortArray,
  12053. dirtyVertices = geometry.verticesNeedUpdate,
  12054. dirtyElements = geometry.elementsNeedUpdate,
  12055. dirtyColors = geometry.colorsNeedUpdate,
  12056. customAttributes = geometry.__webglCustomAttributesList,
  12057. i, il,
  12058. a, ca, cal, value,
  12059. customAttribute;
  12060. if ( object.sortParticles ) {
  12061. _projScreenMatrixPS.copy( _projScreenMatrix );
  12062. _projScreenMatrixPS.multiply( object.matrixWorld );
  12063. for ( v = 0; v < vl; v ++ ) {
  12064. vertex = vertices[ v ];
  12065. _vector3.copy( vertex );
  12066. _vector3.applyProjection( _projScreenMatrixPS );
  12067. sortArray[ v ] = [ _vector3.z, v ];
  12068. }
  12069. sortArray.sort( numericalSort );
  12070. for ( v = 0; v < vl; v ++ ) {
  12071. vertex = vertices[ sortArray[v][1] ];
  12072. offset = v * 3;
  12073. vertexArray[ offset ] = vertex.x;
  12074. vertexArray[ offset + 1 ] = vertex.y;
  12075. vertexArray[ offset + 2 ] = vertex.z;
  12076. }
  12077. for ( c = 0; c < cl; c ++ ) {
  12078. offset = c * 3;
  12079. color = colors[ sortArray[c][1] ];
  12080. colorArray[ offset ] = color.r;
  12081. colorArray[ offset + 1 ] = color.g;
  12082. colorArray[ offset + 2 ] = color.b;
  12083. }
  12084. if ( customAttributes ) {
  12085. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12086. customAttribute = customAttributes[ i ];
  12087. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  12088. offset = 0;
  12089. cal = customAttribute.value.length;
  12090. if ( customAttribute.size === 1 ) {
  12091. for ( ca = 0; ca < cal; ca ++ ) {
  12092. index = sortArray[ ca ][ 1 ];
  12093. customAttribute.array[ ca ] = customAttribute.value[ index ];
  12094. }
  12095. } else if ( customAttribute.size === 2 ) {
  12096. for ( ca = 0; ca < cal; ca ++ ) {
  12097. index = sortArray[ ca ][ 1 ];
  12098. value = customAttribute.value[ index ];
  12099. customAttribute.array[ offset ] = value.x;
  12100. customAttribute.array[ offset + 1 ] = value.y;
  12101. offset += 2;
  12102. }
  12103. } else if ( customAttribute.size === 3 ) {
  12104. if ( customAttribute.type === "c" ) {
  12105. for ( ca = 0; ca < cal; ca ++ ) {
  12106. index = sortArray[ ca ][ 1 ];
  12107. value = customAttribute.value[ index ];
  12108. customAttribute.array[ offset ] = value.r;
  12109. customAttribute.array[ offset + 1 ] = value.g;
  12110. customAttribute.array[ offset + 2 ] = value.b;
  12111. offset += 3;
  12112. }
  12113. } else {
  12114. for ( ca = 0; ca < cal; ca ++ ) {
  12115. index = sortArray[ ca ][ 1 ];
  12116. value = customAttribute.value[ index ];
  12117. customAttribute.array[ offset ] = value.x;
  12118. customAttribute.array[ offset + 1 ] = value.y;
  12119. customAttribute.array[ offset + 2 ] = value.z;
  12120. offset += 3;
  12121. }
  12122. }
  12123. } else if ( customAttribute.size === 4 ) {
  12124. for ( ca = 0; ca < cal; ca ++ ) {
  12125. index = sortArray[ ca ][ 1 ];
  12126. value = customAttribute.value[ index ];
  12127. customAttribute.array[ offset ] = value.x;
  12128. customAttribute.array[ offset + 1 ] = value.y;
  12129. customAttribute.array[ offset + 2 ] = value.z;
  12130. customAttribute.array[ offset + 3 ] = value.w;
  12131. offset += 4;
  12132. }
  12133. }
  12134. }
  12135. }
  12136. } else {
  12137. if ( dirtyVertices ) {
  12138. for ( v = 0; v < vl; v ++ ) {
  12139. vertex = vertices[ v ];
  12140. offset = v * 3;
  12141. vertexArray[ offset ] = vertex.x;
  12142. vertexArray[ offset + 1 ] = vertex.y;
  12143. vertexArray[ offset + 2 ] = vertex.z;
  12144. }
  12145. }
  12146. if ( dirtyColors ) {
  12147. for ( c = 0; c < cl; c ++ ) {
  12148. color = colors[ c ];
  12149. offset = c * 3;
  12150. colorArray[ offset ] = color.r;
  12151. colorArray[ offset + 1 ] = color.g;
  12152. colorArray[ offset + 2 ] = color.b;
  12153. }
  12154. }
  12155. if ( customAttributes ) {
  12156. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12157. customAttribute = customAttributes[ i ];
  12158. if ( customAttribute.needsUpdate &&
  12159. ( customAttribute.boundTo === undefined ||
  12160. customAttribute.boundTo === "vertices") ) {
  12161. cal = customAttribute.value.length;
  12162. offset = 0;
  12163. if ( customAttribute.size === 1 ) {
  12164. for ( ca = 0; ca < cal; ca ++ ) {
  12165. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12166. }
  12167. } else if ( customAttribute.size === 2 ) {
  12168. for ( ca = 0; ca < cal; ca ++ ) {
  12169. value = customAttribute.value[ ca ];
  12170. customAttribute.array[ offset ] = value.x;
  12171. customAttribute.array[ offset + 1 ] = value.y;
  12172. offset += 2;
  12173. }
  12174. } else if ( customAttribute.size === 3 ) {
  12175. if ( customAttribute.type === "c" ) {
  12176. for ( ca = 0; ca < cal; ca ++ ) {
  12177. value = customAttribute.value[ ca ];
  12178. customAttribute.array[ offset ] = value.r;
  12179. customAttribute.array[ offset + 1 ] = value.g;
  12180. customAttribute.array[ offset + 2 ] = value.b;
  12181. offset += 3;
  12182. }
  12183. } else {
  12184. for ( ca = 0; ca < cal; ca ++ ) {
  12185. value = customAttribute.value[ ca ];
  12186. customAttribute.array[ offset ] = value.x;
  12187. customAttribute.array[ offset + 1 ] = value.y;
  12188. customAttribute.array[ offset + 2 ] = value.z;
  12189. offset += 3;
  12190. }
  12191. }
  12192. } else if ( customAttribute.size === 4 ) {
  12193. for ( ca = 0; ca < cal; ca ++ ) {
  12194. value = customAttribute.value[ ca ];
  12195. customAttribute.array[ offset ] = value.x;
  12196. customAttribute.array[ offset + 1 ] = value.y;
  12197. customAttribute.array[ offset + 2 ] = value.z;
  12198. customAttribute.array[ offset + 3 ] = value.w;
  12199. offset += 4;
  12200. }
  12201. }
  12202. }
  12203. }
  12204. }
  12205. }
  12206. if ( dirtyVertices || object.sortParticles ) {
  12207. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12208. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12209. }
  12210. if ( dirtyColors || object.sortParticles ) {
  12211. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12212. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12213. }
  12214. if ( customAttributes ) {
  12215. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12216. customAttribute = customAttributes[ i ];
  12217. if ( customAttribute.needsUpdate || object.sortParticles ) {
  12218. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12219. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12220. }
  12221. }
  12222. }
  12223. };
  12224. function setLineBuffers ( geometry, hint ) {
  12225. var v, c, d, vertex, offset, color,
  12226. vertices = geometry.vertices,
  12227. colors = geometry.colors,
  12228. lineDistances = geometry.lineDistances,
  12229. vl = vertices.length,
  12230. cl = colors.length,
  12231. dl = lineDistances.length,
  12232. vertexArray = geometry.__vertexArray,
  12233. colorArray = geometry.__colorArray,
  12234. lineDistanceArray = geometry.__lineDistanceArray,
  12235. dirtyVertices = geometry.verticesNeedUpdate,
  12236. dirtyColors = geometry.colorsNeedUpdate,
  12237. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  12238. customAttributes = geometry.__webglCustomAttributesList,
  12239. i, il,
  12240. a, ca, cal, value,
  12241. customAttribute;
  12242. if ( dirtyVertices ) {
  12243. for ( v = 0; v < vl; v ++ ) {
  12244. vertex = vertices[ v ];
  12245. offset = v * 3;
  12246. vertexArray[ offset ] = vertex.x;
  12247. vertexArray[ offset + 1 ] = vertex.y;
  12248. vertexArray[ offset + 2 ] = vertex.z;
  12249. }
  12250. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12251. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12252. }
  12253. if ( dirtyColors ) {
  12254. for ( c = 0; c < cl; c ++ ) {
  12255. color = colors[ c ];
  12256. offset = c * 3;
  12257. colorArray[ offset ] = color.r;
  12258. colorArray[ offset + 1 ] = color.g;
  12259. colorArray[ offset + 2 ] = color.b;
  12260. }
  12261. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12262. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12263. }
  12264. if ( dirtyLineDistances ) {
  12265. for ( d = 0; d < dl; d ++ ) {
  12266. lineDistanceArray[ d ] = lineDistances[ d ];
  12267. }
  12268. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  12269. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  12270. }
  12271. if ( customAttributes ) {
  12272. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12273. customAttribute = customAttributes[ i ];
  12274. if ( customAttribute.needsUpdate &&
  12275. ( customAttribute.boundTo === undefined ||
  12276. customAttribute.boundTo === "vertices" ) ) {
  12277. offset = 0;
  12278. cal = customAttribute.value.length;
  12279. if ( customAttribute.size === 1 ) {
  12280. for ( ca = 0; ca < cal; ca ++ ) {
  12281. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12282. }
  12283. } else if ( customAttribute.size === 2 ) {
  12284. for ( ca = 0; ca < cal; ca ++ ) {
  12285. value = customAttribute.value[ ca ];
  12286. customAttribute.array[ offset ] = value.x;
  12287. customAttribute.array[ offset + 1 ] = value.y;
  12288. offset += 2;
  12289. }
  12290. } else if ( customAttribute.size === 3 ) {
  12291. if ( customAttribute.type === "c" ) {
  12292. for ( ca = 0; ca < cal; ca ++ ) {
  12293. value = customAttribute.value[ ca ];
  12294. customAttribute.array[ offset ] = value.r;
  12295. customAttribute.array[ offset + 1 ] = value.g;
  12296. customAttribute.array[ offset + 2 ] = value.b;
  12297. offset += 3;
  12298. }
  12299. } else {
  12300. for ( ca = 0; ca < cal; ca ++ ) {
  12301. value = customAttribute.value[ ca ];
  12302. customAttribute.array[ offset ] = value.x;
  12303. customAttribute.array[ offset + 1 ] = value.y;
  12304. customAttribute.array[ offset + 2 ] = value.z;
  12305. offset += 3;
  12306. }
  12307. }
  12308. } else if ( customAttribute.size === 4 ) {
  12309. for ( ca = 0; ca < cal; ca ++ ) {
  12310. value = customAttribute.value[ ca ];
  12311. customAttribute.array[ offset ] = value.x;
  12312. customAttribute.array[ offset + 1 ] = value.y;
  12313. customAttribute.array[ offset + 2 ] = value.z;
  12314. customAttribute.array[ offset + 3 ] = value.w;
  12315. offset += 4;
  12316. }
  12317. }
  12318. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12319. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12320. }
  12321. }
  12322. }
  12323. };
  12324. function setRibbonBuffers ( geometry, hint ) {
  12325. var v, c, n, vertex, offset, color, normal,
  12326. i, il, ca, cal, customAttribute, value,
  12327. vertices = geometry.vertices,
  12328. colors = geometry.colors,
  12329. normals = geometry.normals,
  12330. vl = vertices.length,
  12331. cl = colors.length,
  12332. nl = normals.length,
  12333. vertexArray = geometry.__vertexArray,
  12334. colorArray = geometry.__colorArray,
  12335. normalArray = geometry.__normalArray,
  12336. dirtyVertices = geometry.verticesNeedUpdate,
  12337. dirtyColors = geometry.colorsNeedUpdate,
  12338. dirtyNormals = geometry.normalsNeedUpdate,
  12339. customAttributes = geometry.__webglCustomAttributesList;
  12340. if ( dirtyVertices ) {
  12341. for ( v = 0; v < vl; v ++ ) {
  12342. vertex = vertices[ v ];
  12343. offset = v * 3;
  12344. vertexArray[ offset ] = vertex.x;
  12345. vertexArray[ offset + 1 ] = vertex.y;
  12346. vertexArray[ offset + 2 ] = vertex.z;
  12347. }
  12348. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12349. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12350. }
  12351. if ( dirtyColors ) {
  12352. for ( c = 0; c < cl; c ++ ) {
  12353. color = colors[ c ];
  12354. offset = c * 3;
  12355. colorArray[ offset ] = color.r;
  12356. colorArray[ offset + 1 ] = color.g;
  12357. colorArray[ offset + 2 ] = color.b;
  12358. }
  12359. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12360. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12361. }
  12362. if ( dirtyNormals ) {
  12363. for ( n = 0; n < nl; n ++ ) {
  12364. normal = normals[ n ];
  12365. offset = n * 3;
  12366. normalArray[ offset ] = normal.x;
  12367. normalArray[ offset + 1 ] = normal.y;
  12368. normalArray[ offset + 2 ] = normal.z;
  12369. }
  12370. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  12371. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12372. }
  12373. if ( customAttributes ) {
  12374. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12375. customAttribute = customAttributes[ i ];
  12376. if ( customAttribute.needsUpdate &&
  12377. ( customAttribute.boundTo === undefined ||
  12378. customAttribute.boundTo === "vertices" ) ) {
  12379. offset = 0;
  12380. cal = customAttribute.value.length;
  12381. if ( customAttribute.size === 1 ) {
  12382. for ( ca = 0; ca < cal; ca ++ ) {
  12383. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12384. }
  12385. } else if ( customAttribute.size === 2 ) {
  12386. for ( ca = 0; ca < cal; ca ++ ) {
  12387. value = customAttribute.value[ ca ];
  12388. customAttribute.array[ offset ] = value.x;
  12389. customAttribute.array[ offset + 1 ] = value.y;
  12390. offset += 2;
  12391. }
  12392. } else if ( customAttribute.size === 3 ) {
  12393. if ( customAttribute.type === "c" ) {
  12394. for ( ca = 0; ca < cal; ca ++ ) {
  12395. value = customAttribute.value[ ca ];
  12396. customAttribute.array[ offset ] = value.r;
  12397. customAttribute.array[ offset + 1 ] = value.g;
  12398. customAttribute.array[ offset + 2 ] = value.b;
  12399. offset += 3;
  12400. }
  12401. } else {
  12402. for ( ca = 0; ca < cal; ca ++ ) {
  12403. value = customAttribute.value[ ca ];
  12404. customAttribute.array[ offset ] = value.x;
  12405. customAttribute.array[ offset + 1 ] = value.y;
  12406. customAttribute.array[ offset + 2 ] = value.z;
  12407. offset += 3;
  12408. }
  12409. }
  12410. } else if ( customAttribute.size === 4 ) {
  12411. for ( ca = 0; ca < cal; ca ++ ) {
  12412. value = customAttribute.value[ ca ];
  12413. customAttribute.array[ offset ] = value.x;
  12414. customAttribute.array[ offset + 1 ] = value.y;
  12415. customAttribute.array[ offset + 2 ] = value.z;
  12416. customAttribute.array[ offset + 3 ] = value.w;
  12417. offset += 4;
  12418. }
  12419. }
  12420. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12421. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12422. }
  12423. }
  12424. }
  12425. };
  12426. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12427. if ( ! geometryGroup.__inittedArrays ) {
  12428. return;
  12429. }
  12430. var normalType = bufferGuessNormalType( material ),
  12431. vertexColorType = bufferGuessVertexColorType( material ),
  12432. uvType = bufferGuessUVType( material ),
  12433. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12434. var f, fl, fi, face,
  12435. vertexNormals, faceNormal, normal,
  12436. vertexColors, faceColor,
  12437. vertexTangents,
  12438. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12439. c1, c2, c3, c4,
  12440. sw1, sw2, sw3, sw4,
  12441. si1, si2, si3, si4,
  12442. sa1, sa2, sa3, sa4,
  12443. sb1, sb2, sb3, sb4,
  12444. m, ml, i, il,
  12445. vn, uvi, uv2i,
  12446. vk, vkl, vka,
  12447. nka, chf, faceVertexNormals,
  12448. a,
  12449. vertexIndex = 0,
  12450. offset = 0,
  12451. offset_uv = 0,
  12452. offset_uv2 = 0,
  12453. offset_face = 0,
  12454. offset_normal = 0,
  12455. offset_tangent = 0,
  12456. offset_line = 0,
  12457. offset_color = 0,
  12458. offset_skin = 0,
  12459. offset_morphTarget = 0,
  12460. offset_custom = 0,
  12461. offset_customSrc = 0,
  12462. value,
  12463. vertexArray = geometryGroup.__vertexArray,
  12464. uvArray = geometryGroup.__uvArray,
  12465. uv2Array = geometryGroup.__uv2Array,
  12466. normalArray = geometryGroup.__normalArray,
  12467. tangentArray = geometryGroup.__tangentArray,
  12468. colorArray = geometryGroup.__colorArray,
  12469. skinIndexArray = geometryGroup.__skinIndexArray,
  12470. skinWeightArray = geometryGroup.__skinWeightArray,
  12471. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12472. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12473. customAttributes = geometryGroup.__webglCustomAttributesList,
  12474. customAttribute,
  12475. faceArray = geometryGroup.__faceArray,
  12476. lineArray = geometryGroup.__lineArray,
  12477. geometry = object.geometry, // this is shared for all chunks
  12478. dirtyVertices = geometry.verticesNeedUpdate,
  12479. dirtyElements = geometry.elementsNeedUpdate,
  12480. dirtyUvs = geometry.uvsNeedUpdate,
  12481. dirtyNormals = geometry.normalsNeedUpdate,
  12482. dirtyTangents = geometry.tangentsNeedUpdate,
  12483. dirtyColors = geometry.colorsNeedUpdate,
  12484. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12485. vertices = geometry.vertices,
  12486. chunk_faces3 = geometryGroup.faces3,
  12487. obj_faces = geometry.faces,
  12488. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12489. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12490. obj_colors = geometry.colors,
  12491. obj_skinIndices = geometry.skinIndices,
  12492. obj_skinWeights = geometry.skinWeights,
  12493. morphTargets = geometry.morphTargets,
  12494. morphNormals = geometry.morphNormals;
  12495. if ( dirtyVertices ) {
  12496. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12497. face = obj_faces[ chunk_faces3[ f ] ];
  12498. v1 = vertices[ face.a ];
  12499. v2 = vertices[ face.b ];
  12500. v3 = vertices[ face.c ];
  12501. vertexArray[ offset ] = v1.x;
  12502. vertexArray[ offset + 1 ] = v1.y;
  12503. vertexArray[ offset + 2 ] = v1.z;
  12504. vertexArray[ offset + 3 ] = v2.x;
  12505. vertexArray[ offset + 4 ] = v2.y;
  12506. vertexArray[ offset + 5 ] = v2.z;
  12507. vertexArray[ offset + 6 ] = v3.x;
  12508. vertexArray[ offset + 7 ] = v3.y;
  12509. vertexArray[ offset + 8 ] = v3.z;
  12510. offset += 9;
  12511. }
  12512. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12513. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12514. }
  12515. if ( dirtyMorphTargets ) {
  12516. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  12517. offset_morphTarget = 0;
  12518. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12519. chf = chunk_faces3[ f ];
  12520. face = obj_faces[ chf ];
  12521. // morph positions
  12522. v1 = morphTargets[ vk ].vertices[ face.a ];
  12523. v2 = morphTargets[ vk ].vertices[ face.b ];
  12524. v3 = morphTargets[ vk ].vertices[ face.c ];
  12525. vka = morphTargetsArrays[ vk ];
  12526. vka[ offset_morphTarget ] = v1.x;
  12527. vka[ offset_morphTarget + 1 ] = v1.y;
  12528. vka[ offset_morphTarget + 2 ] = v1.z;
  12529. vka[ offset_morphTarget + 3 ] = v2.x;
  12530. vka[ offset_morphTarget + 4 ] = v2.y;
  12531. vka[ offset_morphTarget + 5 ] = v2.z;
  12532. vka[ offset_morphTarget + 6 ] = v3.x;
  12533. vka[ offset_morphTarget + 7 ] = v3.y;
  12534. vka[ offset_morphTarget + 8 ] = v3.z;
  12535. // morph normals
  12536. if ( material.morphNormals ) {
  12537. if ( needsSmoothNormals ) {
  12538. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12539. n1 = faceVertexNormals.a;
  12540. n2 = faceVertexNormals.b;
  12541. n3 = faceVertexNormals.c;
  12542. } else {
  12543. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12544. n2 = n1;
  12545. n3 = n1;
  12546. }
  12547. nka = morphNormalsArrays[ vk ];
  12548. nka[ offset_morphTarget ] = n1.x;
  12549. nka[ offset_morphTarget + 1 ] = n1.y;
  12550. nka[ offset_morphTarget + 2 ] = n1.z;
  12551. nka[ offset_morphTarget + 3 ] = n2.x;
  12552. nka[ offset_morphTarget + 4 ] = n2.y;
  12553. nka[ offset_morphTarget + 5 ] = n2.z;
  12554. nka[ offset_morphTarget + 6 ] = n3.x;
  12555. nka[ offset_morphTarget + 7 ] = n3.y;
  12556. nka[ offset_morphTarget + 8 ] = n3.z;
  12557. }
  12558. //
  12559. offset_morphTarget += 9;
  12560. }
  12561. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  12562. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  12563. if ( material.morphNormals ) {
  12564. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  12565. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  12566. }
  12567. }
  12568. }
  12569. if ( obj_skinWeights.length ) {
  12570. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12571. face = obj_faces[ chunk_faces3[ f ] ];
  12572. // weights
  12573. sw1 = obj_skinWeights[ face.a ];
  12574. sw2 = obj_skinWeights[ face.b ];
  12575. sw3 = obj_skinWeights[ face.c ];
  12576. skinWeightArray[ offset_skin ] = sw1.x;
  12577. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12578. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12579. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12580. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12581. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12582. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12583. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12584. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12585. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12586. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12587. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12588. // indices
  12589. si1 = obj_skinIndices[ face.a ];
  12590. si2 = obj_skinIndices[ face.b ];
  12591. si3 = obj_skinIndices[ face.c ];
  12592. skinIndexArray[ offset_skin ] = si1.x;
  12593. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12594. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12595. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12596. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12597. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12598. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12599. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12600. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12601. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12602. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12603. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12604. offset_skin += 12;
  12605. }
  12606. if ( offset_skin > 0 ) {
  12607. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12608. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  12609. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12610. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  12611. }
  12612. }
  12613. if ( dirtyColors && vertexColorType ) {
  12614. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12615. face = obj_faces[ chunk_faces3[ f ] ];
  12616. vertexColors = face.vertexColors;
  12617. faceColor = face.color;
  12618. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  12619. c1 = vertexColors[ 0 ];
  12620. c2 = vertexColors[ 1 ];
  12621. c3 = vertexColors[ 2 ];
  12622. } else {
  12623. c1 = faceColor;
  12624. c2 = faceColor;
  12625. c3 = faceColor;
  12626. }
  12627. colorArray[ offset_color ] = c1.r;
  12628. colorArray[ offset_color + 1 ] = c1.g;
  12629. colorArray[ offset_color + 2 ] = c1.b;
  12630. colorArray[ offset_color + 3 ] = c2.r;
  12631. colorArray[ offset_color + 4 ] = c2.g;
  12632. colorArray[ offset_color + 5 ] = c2.b;
  12633. colorArray[ offset_color + 6 ] = c3.r;
  12634. colorArray[ offset_color + 7 ] = c3.g;
  12635. colorArray[ offset_color + 8 ] = c3.b;
  12636. offset_color += 9;
  12637. }
  12638. if ( offset_color > 0 ) {
  12639. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12640. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12641. }
  12642. }
  12643. if ( dirtyTangents && geometry.hasTangents ) {
  12644. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12645. face = obj_faces[ chunk_faces3[ f ] ];
  12646. vertexTangents = face.vertexTangents;
  12647. t1 = vertexTangents[ 0 ];
  12648. t2 = vertexTangents[ 1 ];
  12649. t3 = vertexTangents[ 2 ];
  12650. tangentArray[ offset_tangent ] = t1.x;
  12651. tangentArray[ offset_tangent + 1 ] = t1.y;
  12652. tangentArray[ offset_tangent + 2 ] = t1.z;
  12653. tangentArray[ offset_tangent + 3 ] = t1.w;
  12654. tangentArray[ offset_tangent + 4 ] = t2.x;
  12655. tangentArray[ offset_tangent + 5 ] = t2.y;
  12656. tangentArray[ offset_tangent + 6 ] = t2.z;
  12657. tangentArray[ offset_tangent + 7 ] = t2.w;
  12658. tangentArray[ offset_tangent + 8 ] = t3.x;
  12659. tangentArray[ offset_tangent + 9 ] = t3.y;
  12660. tangentArray[ offset_tangent + 10 ] = t3.z;
  12661. tangentArray[ offset_tangent + 11 ] = t3.w;
  12662. offset_tangent += 12;
  12663. }
  12664. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12665. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  12666. }
  12667. if ( dirtyNormals && normalType ) {
  12668. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12669. face = obj_faces[ chunk_faces3[ f ] ];
  12670. vertexNormals = face.vertexNormals;
  12671. faceNormal = face.normal;
  12672. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  12673. for ( i = 0; i < 3; i ++ ) {
  12674. vn = vertexNormals[ i ];
  12675. normalArray[ offset_normal ] = vn.x;
  12676. normalArray[ offset_normal + 1 ] = vn.y;
  12677. normalArray[ offset_normal + 2 ] = vn.z;
  12678. offset_normal += 3;
  12679. }
  12680. } else {
  12681. for ( i = 0; i < 3; i ++ ) {
  12682. normalArray[ offset_normal ] = faceNormal.x;
  12683. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12684. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12685. offset_normal += 3;
  12686. }
  12687. }
  12688. }
  12689. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12690. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12691. }
  12692. if ( dirtyUvs && obj_uvs && uvType ) {
  12693. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12694. fi = chunk_faces3[ f ];
  12695. uv = obj_uvs[ fi ];
  12696. if ( uv === undefined ) continue;
  12697. for ( i = 0; i < 3; i ++ ) {
  12698. uvi = uv[ i ];
  12699. uvArray[ offset_uv ] = uvi.x;
  12700. uvArray[ offset_uv + 1 ] = uvi.y;
  12701. offset_uv += 2;
  12702. }
  12703. }
  12704. if ( offset_uv > 0 ) {
  12705. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12706. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  12707. }
  12708. }
  12709. if ( dirtyUvs && obj_uvs2 && uvType ) {
  12710. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12711. fi = chunk_faces3[ f ];
  12712. uv2 = obj_uvs2[ fi ];
  12713. if ( uv2 === undefined ) continue;
  12714. for ( i = 0; i < 3; i ++ ) {
  12715. uv2i = uv2[ i ];
  12716. uv2Array[ offset_uv2 ] = uv2i.x;
  12717. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12718. offset_uv2 += 2;
  12719. }
  12720. }
  12721. if ( offset_uv2 > 0 ) {
  12722. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12723. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  12724. }
  12725. }
  12726. if ( dirtyElements ) {
  12727. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12728. faceArray[ offset_face ] = vertexIndex;
  12729. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12730. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  12731. offset_face += 3;
  12732. lineArray[ offset_line ] = vertexIndex;
  12733. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12734. lineArray[ offset_line + 2 ] = vertexIndex;
  12735. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  12736. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12737. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12738. offset_line += 6;
  12739. vertexIndex += 3;
  12740. }
  12741. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12742. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  12743. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12744. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  12745. }
  12746. if ( customAttributes ) {
  12747. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12748. customAttribute = customAttributes[ i ];
  12749. if ( ! customAttribute.__original.needsUpdate ) continue;
  12750. offset_custom = 0;
  12751. offset_customSrc = 0;
  12752. if ( customAttribute.size === 1 ) {
  12753. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12754. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12755. face = obj_faces[ chunk_faces3[ f ] ];
  12756. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12757. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12758. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12759. offset_custom += 3;
  12760. }
  12761. } else if ( customAttribute.boundTo === "faces" ) {
  12762. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12763. value = customAttribute.value[ chunk_faces3[ f ] ];
  12764. customAttribute.array[ offset_custom ] = value;
  12765. customAttribute.array[ offset_custom + 1 ] = value;
  12766. customAttribute.array[ offset_custom + 2 ] = value;
  12767. offset_custom += 3;
  12768. }
  12769. }
  12770. } else if ( customAttribute.size === 2 ) {
  12771. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12772. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12773. face = obj_faces[ chunk_faces3[ f ] ];
  12774. v1 = customAttribute.value[ face.a ];
  12775. v2 = customAttribute.value[ face.b ];
  12776. v3 = customAttribute.value[ face.c ];
  12777. customAttribute.array[ offset_custom ] = v1.x;
  12778. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12779. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12780. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12781. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12782. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12783. offset_custom += 6;
  12784. }
  12785. } else if ( customAttribute.boundTo === "faces" ) {
  12786. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12787. value = customAttribute.value[ chunk_faces3[ f ] ];
  12788. v1 = value;
  12789. v2 = value;
  12790. v3 = value;
  12791. customAttribute.array[ offset_custom ] = v1.x;
  12792. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12793. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12794. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12795. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12796. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12797. offset_custom += 6;
  12798. }
  12799. }
  12800. } else if ( customAttribute.size === 3 ) {
  12801. var pp;
  12802. if ( customAttribute.type === "c" ) {
  12803. pp = [ "r", "g", "b" ];
  12804. } else {
  12805. pp = [ "x", "y", "z" ];
  12806. }
  12807. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12808. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12809. face = obj_faces[ chunk_faces3[ f ] ];
  12810. v1 = customAttribute.value[ face.a ];
  12811. v2 = customAttribute.value[ face.b ];
  12812. v3 = customAttribute.value[ face.c ];
  12813. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12814. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12815. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12816. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12817. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12818. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12819. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12820. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12821. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12822. offset_custom += 9;
  12823. }
  12824. } else if ( customAttribute.boundTo === "faces" ) {
  12825. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12826. value = customAttribute.value[ chunk_faces3[ f ] ];
  12827. v1 = value;
  12828. v2 = value;
  12829. v3 = value;
  12830. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12831. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12832. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12833. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12834. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12835. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12836. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12837. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12838. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12839. offset_custom += 9;
  12840. }
  12841. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12842. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12843. value = customAttribute.value[ chunk_faces3[ f ] ];
  12844. v1 = value[ 0 ];
  12845. v2 = value[ 1 ];
  12846. v3 = value[ 2 ];
  12847. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12848. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12849. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12850. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12851. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12852. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12853. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12854. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12855. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12856. offset_custom += 9;
  12857. }
  12858. }
  12859. } else if ( customAttribute.size === 4 ) {
  12860. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12861. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12862. face = obj_faces[ chunk_faces3[ f ] ];
  12863. v1 = customAttribute.value[ face.a ];
  12864. v2 = customAttribute.value[ face.b ];
  12865. v3 = customAttribute.value[ face.c ];
  12866. customAttribute.array[ offset_custom ] = v1.x;
  12867. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12868. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12869. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12870. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12871. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12872. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12873. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12874. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12875. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12876. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12877. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12878. offset_custom += 12;
  12879. }
  12880. } else if ( customAttribute.boundTo === "faces" ) {
  12881. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12882. value = customAttribute.value[ chunk_faces3[ f ] ];
  12883. v1 = value;
  12884. v2 = value;
  12885. v3 = value;
  12886. customAttribute.array[ offset_custom ] = v1.x;
  12887. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12888. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12889. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12890. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12891. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12892. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12893. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12894. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12895. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12896. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12897. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12898. offset_custom += 12;
  12899. }
  12900. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12901. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12902. value = customAttribute.value[ chunk_faces3[ f ] ];
  12903. v1 = value[ 0 ];
  12904. v2 = value[ 1 ];
  12905. v3 = value[ 2 ];
  12906. customAttribute.array[ offset_custom ] = v1.x;
  12907. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12908. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12909. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12910. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12911. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12912. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12913. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12914. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12915. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12916. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12917. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12918. offset_custom += 12;
  12919. }
  12920. }
  12921. }
  12922. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12923. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12924. }
  12925. }
  12926. if ( dispose ) {
  12927. delete geometryGroup.__inittedArrays;
  12928. delete geometryGroup.__colorArray;
  12929. delete geometryGroup.__normalArray;
  12930. delete geometryGroup.__tangentArray;
  12931. delete geometryGroup.__uvArray;
  12932. delete geometryGroup.__uv2Array;
  12933. delete geometryGroup.__faceArray;
  12934. delete geometryGroup.__vertexArray;
  12935. delete geometryGroup.__lineArray;
  12936. delete geometryGroup.__skinIndexArray;
  12937. delete geometryGroup.__skinWeightArray;
  12938. }
  12939. };
  12940. function setDirectBuffers ( geometry, hint, dispose ) {
  12941. var attributes = geometry.attributes;
  12942. var attributeName, attributeItem;
  12943. for ( attributeName in attributes ) {
  12944. attributeItem = attributes[ attributeName ];
  12945. if ( attributeItem.needsUpdate ) {
  12946. if ( attributeName === 'index' ) {
  12947. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  12948. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  12949. } else {
  12950. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  12951. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  12952. }
  12953. attributeItem.needsUpdate = false;
  12954. }
  12955. if ( dispose && ! attributeItem.dynamic ) {
  12956. attributeItem.array = null;
  12957. }
  12958. }
  12959. };
  12960. // Buffer rendering
  12961. this.renderBufferImmediate = function ( object, program, material ) {
  12962. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  12963. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  12964. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  12965. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  12966. if ( object.hasPositions ) {
  12967. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  12968. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12969. _gl.enableVertexAttribArray( program.attributes.position );
  12970. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12971. }
  12972. if ( object.hasNormals ) {
  12973. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  12974. if ( material.shading === THREE.FlatShading ) {
  12975. var nx, ny, nz,
  12976. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  12977. normalArray,
  12978. i, il = object.count * 3;
  12979. for( i = 0; i < il; i += 9 ) {
  12980. normalArray = object.normalArray;
  12981. nax = normalArray[ i ];
  12982. nay = normalArray[ i + 1 ];
  12983. naz = normalArray[ i + 2 ];
  12984. nbx = normalArray[ i + 3 ];
  12985. nby = normalArray[ i + 4 ];
  12986. nbz = normalArray[ i + 5 ];
  12987. ncx = normalArray[ i + 6 ];
  12988. ncy = normalArray[ i + 7 ];
  12989. ncz = normalArray[ i + 8 ];
  12990. nx = ( nax + nbx + ncx ) / 3;
  12991. ny = ( nay + nby + ncy ) / 3;
  12992. nz = ( naz + nbz + ncz ) / 3;
  12993. normalArray[ i ] = nx;
  12994. normalArray[ i + 1 ] = ny;
  12995. normalArray[ i + 2 ] = nz;
  12996. normalArray[ i + 3 ] = nx;
  12997. normalArray[ i + 4 ] = ny;
  12998. normalArray[ i + 5 ] = nz;
  12999. normalArray[ i + 6 ] = nx;
  13000. normalArray[ i + 7 ] = ny;
  13001. normalArray[ i + 8 ] = nz;
  13002. }
  13003. }
  13004. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13005. _gl.enableVertexAttribArray( program.attributes.normal );
  13006. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13007. }
  13008. if ( object.hasUvs && material.map ) {
  13009. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13010. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13011. _gl.enableVertexAttribArray( program.attributes.uv );
  13012. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13013. }
  13014. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13015. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13016. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13017. _gl.enableVertexAttribArray( program.attributes.color );
  13018. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13019. }
  13020. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13021. object.count = 0;
  13022. };
  13023. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13024. if ( material.visible === false ) return;
  13025. var linewidth, a, attribute;
  13026. var attributeItem, attributeName, attributePointer, attributeSize;
  13027. var program = setProgram( camera, lights, fog, material, object );
  13028. var programAttributes = program.attributes;
  13029. var geometryAttributes = geometry.attributes;
  13030. var updateBuffers = false,
  13031. wireframeBit = material.wireframe ? 1 : 0,
  13032. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13033. if ( geometryHash !== _currentGeometryGroupHash ) {
  13034. _currentGeometryGroupHash = geometryHash;
  13035. updateBuffers = true;
  13036. }
  13037. if ( updateBuffers ) {
  13038. disableAttributes();
  13039. }
  13040. // render mesh
  13041. if ( object instanceof THREE.Mesh ) {
  13042. var index = geometryAttributes[ "index" ];
  13043. // indexed triangles
  13044. if ( index ) {
  13045. var offsets = geometry.offsets;
  13046. // if there is more than 1 chunk
  13047. // must set attribute pointers to use new offsets for each chunk
  13048. // even if geometry and materials didn't change
  13049. if ( offsets.length > 1 ) updateBuffers = true;
  13050. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13051. var startIndex = offsets[ i ].index;
  13052. if ( updateBuffers ) {
  13053. for ( attributeName in programAttributes ) {
  13054. attributePointer = programAttributes[ attributeName ];
  13055. attributeItem = geometryAttributes[ attributeName ];
  13056. if ( attributePointer >= 0 ) {
  13057. if ( attributeItem ) {
  13058. attributeSize = attributeItem.itemSize;
  13059. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13060. enableAttribute( attributePointer );
  13061. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13062. } else if ( material.defaultAttributeValues ) {
  13063. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13064. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13065. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13066. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13067. }
  13068. }
  13069. }
  13070. }
  13071. // indices
  13072. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13073. }
  13074. // render indexed triangles
  13075. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  13076. _this.info.render.calls ++;
  13077. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13078. _this.info.render.faces += offsets[ i ].count / 3;
  13079. }
  13080. // non-indexed triangles
  13081. } else {
  13082. if ( updateBuffers ) {
  13083. for ( attributeName in programAttributes ) {
  13084. if ( attributeName === 'index') continue;
  13085. attributePointer = programAttributes[ attributeName ];
  13086. attributeItem = geometryAttributes[ attributeName ];
  13087. if ( attributePointer >= 0 ) {
  13088. if ( attributeItem ) {
  13089. attributeSize = attributeItem.itemSize;
  13090. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13091. enableAttribute( attributePointer );
  13092. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13093. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13094. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13095. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13096. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13097. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13098. }
  13099. }
  13100. }
  13101. }
  13102. }
  13103. var position = geometry.attributes[ "position" ];
  13104. // render non-indexed triangles
  13105. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  13106. _this.info.render.calls ++;
  13107. _this.info.render.vertices += position.numItems / 3;
  13108. _this.info.render.faces += position.numItems / 3 / 3;
  13109. }
  13110. // render particles
  13111. } else if ( object instanceof THREE.ParticleSystem ) {
  13112. if ( updateBuffers ) {
  13113. for ( attributeName in programAttributes ) {
  13114. attributePointer = programAttributes[ attributeName ];
  13115. attributeItem = geometryAttributes[ attributeName ];
  13116. if ( attributePointer >= 0 ) {
  13117. if ( attributeItem ) {
  13118. attributeSize = attributeItem.itemSize;
  13119. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13120. enableAttribute( attributePointer );
  13121. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13122. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13123. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13124. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13125. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13126. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13127. }
  13128. }
  13129. }
  13130. }
  13131. var position = geometryAttributes[ "position" ];
  13132. // render particles
  13133. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  13134. _this.info.render.calls ++;
  13135. _this.info.render.points += position.numItems / 3;
  13136. }
  13137. } else if ( object instanceof THREE.Line ) {
  13138. if ( updateBuffers ) {
  13139. for ( attributeName in programAttributes ) {
  13140. attributePointer = programAttributes[ attributeName ];
  13141. attributeItem = geometryAttributes[ attributeName ];
  13142. if ( attributePointer >= 0 ) {
  13143. if ( attributeItem ) {
  13144. attributeSize = attributeItem.itemSize;
  13145. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13146. enableAttribute( attributePointer );
  13147. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13148. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13149. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13150. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13151. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13152. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13153. }
  13154. }
  13155. }
  13156. }
  13157. // render lines
  13158. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13159. setLineWidth( material.linewidth );
  13160. var position = geometryAttributes[ "position" ];
  13161. _gl.drawArrays( primitives, 0, position.numItems / 3 );
  13162. _this.info.render.calls ++;
  13163. _this.info.render.points += position.numItems;
  13164. }
  13165. }
  13166. };
  13167. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13168. if ( material.visible === false ) return;
  13169. var linewidth, a, attribute, i, il;
  13170. var program = setProgram( camera, lights, fog, material, object );
  13171. var attributes = program.attributes;
  13172. var updateBuffers = false,
  13173. wireframeBit = material.wireframe ? 1 : 0,
  13174. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13175. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13176. _currentGeometryGroupHash = geometryGroupHash;
  13177. updateBuffers = true;
  13178. }
  13179. if ( updateBuffers ) {
  13180. disableAttributes();
  13181. }
  13182. // vertices
  13183. if ( !material.morphTargets && attributes.position >= 0 ) {
  13184. if ( updateBuffers ) {
  13185. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13186. enableAttribute( attributes.position );
  13187. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13188. }
  13189. } else {
  13190. if ( object.morphTargetBase ) {
  13191. setupMorphTargets( material, geometryGroup, object );
  13192. }
  13193. }
  13194. if ( updateBuffers ) {
  13195. // custom attributes
  13196. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13197. if ( geometryGroup.__webglCustomAttributesList ) {
  13198. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13199. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13200. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13201. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13202. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13203. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13204. }
  13205. }
  13206. }
  13207. // colors
  13208. if ( attributes.color >= 0 ) {
  13209. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  13210. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13211. enableAttribute( attributes.color );
  13212. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13213. } else if ( material.defaultAttributeValues ) {
  13214. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  13215. }
  13216. }
  13217. // normals
  13218. if ( attributes.normal >= 0 ) {
  13219. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13220. enableAttribute( attributes.normal );
  13221. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13222. }
  13223. // tangents
  13224. if ( attributes.tangent >= 0 ) {
  13225. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13226. enableAttribute( attributes.tangent );
  13227. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13228. }
  13229. // uvs
  13230. if ( attributes.uv >= 0 ) {
  13231. if ( object.geometry.faceVertexUvs[0] ) {
  13232. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13233. enableAttribute( attributes.uv );
  13234. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13235. } else if ( material.defaultAttributeValues ) {
  13236. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  13237. }
  13238. }
  13239. if ( attributes.uv2 >= 0 ) {
  13240. if ( object.geometry.faceVertexUvs[1] ) {
  13241. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13242. enableAttribute( attributes.uv2 );
  13243. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13244. } else if ( material.defaultAttributeValues ) {
  13245. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  13246. }
  13247. }
  13248. if ( material.skinning &&
  13249. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13250. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13251. enableAttribute( attributes.skinIndex );
  13252. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13253. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13254. enableAttribute( attributes.skinWeight );
  13255. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13256. }
  13257. // line distances
  13258. if ( attributes.lineDistance >= 0 ) {
  13259. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13260. enableAttribute( attributes.lineDistance );
  13261. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13262. }
  13263. }
  13264. // render mesh
  13265. if ( object instanceof THREE.Mesh ) {
  13266. // wireframe
  13267. if ( material.wireframe ) {
  13268. setLineWidth( material.wireframeLinewidth );
  13269. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13270. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  13271. // triangles
  13272. } else {
  13273. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13274. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  13275. }
  13276. _this.info.render.calls ++;
  13277. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13278. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13279. // render lines
  13280. } else if ( object instanceof THREE.Line ) {
  13281. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13282. setLineWidth( material.linewidth );
  13283. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  13284. _this.info.render.calls ++;
  13285. // render particles
  13286. } else if ( object instanceof THREE.ParticleSystem ) {
  13287. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13288. _this.info.render.calls ++;
  13289. _this.info.render.points += geometryGroup.__webglParticleCount;
  13290. // render ribbon
  13291. } else if ( object instanceof THREE.Ribbon ) {
  13292. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  13293. _this.info.render.calls ++;
  13294. }
  13295. };
  13296. function enableAttribute( attribute ) {
  13297. if ( ! _enabledAttributes[ attribute ] ) {
  13298. _gl.enableVertexAttribArray( attribute );
  13299. _enabledAttributes[ attribute ] = true;
  13300. }
  13301. };
  13302. function disableAttributes() {
  13303. for ( var attribute in _enabledAttributes ) {
  13304. if ( _enabledAttributes[ attribute ] ) {
  13305. _gl.disableVertexAttribArray( attribute );
  13306. _enabledAttributes[ attribute ] = false;
  13307. }
  13308. }
  13309. };
  13310. function setupMorphTargets ( material, geometryGroup, object ) {
  13311. // set base
  13312. var attributes = material.program.attributes;
  13313. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13314. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13315. enableAttribute( attributes.position );
  13316. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13317. } else if ( attributes.position >= 0 ) {
  13318. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13319. enableAttribute( attributes.position );
  13320. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13321. }
  13322. if ( object.morphTargetForcedOrder.length ) {
  13323. // set forced order
  13324. var m = 0;
  13325. var order = object.morphTargetForcedOrder;
  13326. var influences = object.morphTargetInfluences;
  13327. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13328. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13329. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13330. enableAttribute( attributes[ "morphTarget" + m ] );
  13331. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13332. }
  13333. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13334. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13335. enableAttribute( attributes[ "morphNormal" + m ] );
  13336. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13337. }
  13338. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13339. m ++;
  13340. }
  13341. } else {
  13342. // find the most influencing
  13343. var influence, activeInfluenceIndices = [];
  13344. var influences = object.morphTargetInfluences;
  13345. var i, il = influences.length;
  13346. for ( i = 0; i < il; i ++ ) {
  13347. influence = influences[ i ];
  13348. if ( influence > 0 ) {
  13349. activeInfluenceIndices.push( [ influence, i ] );
  13350. }
  13351. }
  13352. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13353. activeInfluenceIndices.sort( numericalSort );
  13354. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13355. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13356. activeInfluenceIndices.sort( numericalSort );
  13357. } else if ( activeInfluenceIndices.length === 0 ) {
  13358. activeInfluenceIndices.push( [ 0, 0 ] );
  13359. };
  13360. var influenceIndex, m = 0;
  13361. while ( m < material.numSupportedMorphTargets ) {
  13362. if ( activeInfluenceIndices[ m ] ) {
  13363. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13364. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13365. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13366. enableAttribute( attributes[ "morphTarget" + m ] );
  13367. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13368. }
  13369. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13370. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13371. enableAttribute( attributes[ "morphNormal" + m ] );
  13372. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13373. }
  13374. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13375. } else {
  13376. /*
  13377. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13378. if ( material.morphNormals ) {
  13379. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13380. }
  13381. */
  13382. object.__webglMorphTargetInfluences[ m ] = 0;
  13383. }
  13384. m ++;
  13385. }
  13386. }
  13387. // load updated influences uniform
  13388. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13389. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13390. }
  13391. };
  13392. // Sorting
  13393. function painterSortStable ( a, b ) {
  13394. if ( a.z !== b.z ) {
  13395. return b.z - a.z;
  13396. } else {
  13397. return a.id - b.id;
  13398. }
  13399. };
  13400. function numericalSort ( a, b ) {
  13401. return b[ 0 ] - a[ 0 ];
  13402. };
  13403. // Rendering
  13404. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13405. if ( camera instanceof THREE.Camera === false ) {
  13406. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13407. return;
  13408. }
  13409. var i, il,
  13410. webglObject, object,
  13411. renderList,
  13412. lights = scene.__lights,
  13413. fog = scene.fog;
  13414. // reset caching for this frame
  13415. _currentMaterialId = -1;
  13416. _lightsNeedUpdate = true;
  13417. // update scene graph
  13418. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13419. // update camera matrices and frustum
  13420. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13421. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13422. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13423. _frustum.setFromMatrix( _projScreenMatrix );
  13424. // update WebGL objects
  13425. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13426. // custom render plugins (pre pass)
  13427. renderPlugins( this.renderPluginsPre, scene, camera );
  13428. //
  13429. _this.info.render.calls = 0;
  13430. _this.info.render.vertices = 0;
  13431. _this.info.render.faces = 0;
  13432. _this.info.render.points = 0;
  13433. this.setRenderTarget( renderTarget );
  13434. if ( this.autoClear || forceClear ) {
  13435. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13436. }
  13437. // set matrices for regular objects (frustum culled)
  13438. renderList = scene.__webglObjects;
  13439. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13440. webglObject = renderList[ i ];
  13441. object = webglObject.object;
  13442. webglObject.id = i;
  13443. webglObject.render = false;
  13444. if ( object.visible ) {
  13445. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  13446. setupMatrices( object, camera );
  13447. unrollBufferMaterial( webglObject );
  13448. webglObject.render = true;
  13449. if ( this.sortObjects === true ) {
  13450. if ( object.renderDepth !== null ) {
  13451. webglObject.z = object.renderDepth;
  13452. } else {
  13453. _vector3.getPositionFromMatrix( object.matrixWorld );
  13454. _vector3.applyProjection( _projScreenMatrix );
  13455. webglObject.z = _vector3.z;
  13456. }
  13457. }
  13458. }
  13459. }
  13460. }
  13461. if ( this.sortObjects ) {
  13462. renderList.sort( painterSortStable );
  13463. }
  13464. // set matrices for immediate objects
  13465. renderList = scene.__webglObjectsImmediate;
  13466. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13467. webglObject = renderList[ i ];
  13468. object = webglObject.object;
  13469. if ( object.visible ) {
  13470. setupMatrices( object, camera );
  13471. unrollImmediateBufferMaterial( webglObject );
  13472. }
  13473. }
  13474. if ( scene.overrideMaterial ) {
  13475. var material = scene.overrideMaterial;
  13476. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13477. this.setDepthTest( material.depthTest );
  13478. this.setDepthWrite( material.depthWrite );
  13479. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13480. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13481. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13482. } else {
  13483. var material = null;
  13484. // opaque pass (front-to-back order)
  13485. this.setBlending( THREE.NoBlending );
  13486. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13487. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13488. // transparent pass (back-to-front order)
  13489. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13490. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13491. }
  13492. // custom render plugins (post pass)
  13493. renderPlugins( this.renderPluginsPost, scene, camera );
  13494. // Generate mipmap if we're using any kind of mipmap filtering
  13495. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13496. updateRenderTargetMipmap( renderTarget );
  13497. }
  13498. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13499. this.setDepthTest( true );
  13500. this.setDepthWrite( true );
  13501. // _gl.finish();
  13502. };
  13503. function renderPlugins( plugins, scene, camera ) {
  13504. if ( ! plugins.length ) return;
  13505. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13506. // reset state for plugin (to start from clean slate)
  13507. _currentProgram = null;
  13508. _currentCamera = null;
  13509. _oldBlending = -1;
  13510. _oldDepthTest = -1;
  13511. _oldDepthWrite = -1;
  13512. _oldDoubleSided = -1;
  13513. _oldFlipSided = -1;
  13514. _currentGeometryGroupHash = -1;
  13515. _currentMaterialId = -1;
  13516. _lightsNeedUpdate = true;
  13517. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13518. // reset state after plugin (anything could have changed)
  13519. _currentProgram = null;
  13520. _currentCamera = null;
  13521. _oldBlending = -1;
  13522. _oldDepthTest = -1;
  13523. _oldDepthWrite = -1;
  13524. _oldDoubleSided = -1;
  13525. _oldFlipSided = -1;
  13526. _currentGeometryGroupHash = -1;
  13527. _currentMaterialId = -1;
  13528. _lightsNeedUpdate = true;
  13529. }
  13530. };
  13531. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13532. var webglObject, object, buffer, material, start, end, delta;
  13533. if ( reverse ) {
  13534. start = renderList.length - 1;
  13535. end = -1;
  13536. delta = -1;
  13537. } else {
  13538. start = 0;
  13539. end = renderList.length;
  13540. delta = 1;
  13541. }
  13542. for ( var i = start; i !== end; i += delta ) {
  13543. webglObject = renderList[ i ];
  13544. if ( webglObject.render ) {
  13545. object = webglObject.object;
  13546. buffer = webglObject.buffer;
  13547. if ( overrideMaterial ) {
  13548. material = overrideMaterial;
  13549. } else {
  13550. material = webglObject[ materialType ];
  13551. if ( ! material ) continue;
  13552. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13553. _this.setDepthTest( material.depthTest );
  13554. _this.setDepthWrite( material.depthWrite );
  13555. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13556. }
  13557. _this.setMaterialFaces( material );
  13558. if ( buffer instanceof THREE.BufferGeometry ) {
  13559. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  13560. } else {
  13561. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  13562. }
  13563. }
  13564. }
  13565. };
  13566. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13567. var webglObject, object, material, program;
  13568. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13569. webglObject = renderList[ i ];
  13570. object = webglObject.object;
  13571. if ( object.visible ) {
  13572. if ( overrideMaterial ) {
  13573. material = overrideMaterial;
  13574. } else {
  13575. material = webglObject[ materialType ];
  13576. if ( ! material ) continue;
  13577. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13578. _this.setDepthTest( material.depthTest );
  13579. _this.setDepthWrite( material.depthWrite );
  13580. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13581. }
  13582. _this.renderImmediateObject( camera, lights, fog, material, object );
  13583. }
  13584. }
  13585. };
  13586. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13587. var program = setProgram( camera, lights, fog, material, object );
  13588. _currentGeometryGroupHash = -1;
  13589. _this.setMaterialFaces( material );
  13590. if ( object.immediateRenderCallback ) {
  13591. object.immediateRenderCallback( program, _gl, _frustum );
  13592. } else {
  13593. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13594. }
  13595. };
  13596. function unrollImmediateBufferMaterial ( globject ) {
  13597. var object = globject.object,
  13598. material = object.material;
  13599. if ( material.transparent ) {
  13600. globject.transparent = material;
  13601. globject.opaque = null;
  13602. } else {
  13603. globject.opaque = material;
  13604. globject.transparent = null;
  13605. }
  13606. };
  13607. function unrollBufferMaterial ( globject ) {
  13608. var object = globject.object,
  13609. buffer = globject.buffer,
  13610. material, materialIndex, meshMaterial;
  13611. meshMaterial = object.material;
  13612. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  13613. materialIndex = buffer.materialIndex;
  13614. material = meshMaterial.materials[ materialIndex ];
  13615. if ( material.transparent ) {
  13616. globject.transparent = material;
  13617. globject.opaque = null;
  13618. } else {
  13619. globject.opaque = material;
  13620. globject.transparent = null;
  13621. }
  13622. } else {
  13623. material = meshMaterial;
  13624. if ( material ) {
  13625. if ( material.transparent ) {
  13626. globject.transparent = material;
  13627. globject.opaque = null;
  13628. } else {
  13629. globject.opaque = material;
  13630. globject.transparent = null;
  13631. }
  13632. }
  13633. }
  13634. };
  13635. // Geometry splitting
  13636. function sortFacesByMaterial ( geometry, material ) {
  13637. var f, fl, face, materialIndex, vertices,
  13638. groupHash, hash_map = {};
  13639. var numMorphTargets = geometry.morphTargets.length;
  13640. var numMorphNormals = geometry.morphNormals.length;
  13641. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  13642. geometry.geometryGroups = {};
  13643. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  13644. face = geometry.faces[ f ];
  13645. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  13646. if ( hash_map[ materialIndex ] === undefined ) {
  13647. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  13648. }
  13649. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13650. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13651. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13652. }
  13653. vertices = 3;
  13654. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  13655. hash_map[ materialIndex ].counter += 1;
  13656. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13657. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13658. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13659. }
  13660. }
  13661. geometry.geometryGroups[ groupHash ].faces3.push( f );
  13662. geometry.geometryGroups[ groupHash ].vertices += vertices;
  13663. }
  13664. geometry.geometryGroupsList = [];
  13665. for ( var g in geometry.geometryGroups ) {
  13666. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  13667. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  13668. }
  13669. };
  13670. // Objects refresh
  13671. this.initWebGLObjects = function ( scene ) {
  13672. if ( !scene.__webglObjects ) {
  13673. scene.__webglObjects = [];
  13674. scene.__webglObjectsImmediate = [];
  13675. scene.__webglSprites = [];
  13676. scene.__webglFlares = [];
  13677. }
  13678. while ( scene.__objectsAdded.length ) {
  13679. addObject( scene.__objectsAdded[ 0 ], scene );
  13680. scene.__objectsAdded.splice( 0, 1 );
  13681. }
  13682. while ( scene.__objectsRemoved.length ) {
  13683. removeObject( scene.__objectsRemoved[ 0 ], scene );
  13684. scene.__objectsRemoved.splice( 0, 1 );
  13685. }
  13686. // update must be called after objects adding / removal
  13687. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  13688. var object = scene.__webglObjects[ o ].object;
  13689. // TODO: Remove this hack (WebGLRenderer refactoring)
  13690. if ( object.__webglInit === undefined ) {
  13691. if ( object.__webglActive !== undefined ) {
  13692. removeObject( object, scene );
  13693. }
  13694. addObject( object, scene );
  13695. }
  13696. updateObject( object );
  13697. }
  13698. };
  13699. // Objects adding
  13700. function addObject( object, scene ) {
  13701. var g, geometry, material, geometryGroup;
  13702. if ( object.__webglInit === undefined ) {
  13703. object.__webglInit = true;
  13704. object._modelViewMatrix = new THREE.Matrix4();
  13705. object._normalMatrix = new THREE.Matrix3();
  13706. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  13707. object.geometry.__webglInit = true;
  13708. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  13709. }
  13710. geometry = object.geometry;
  13711. if ( geometry === undefined ) {
  13712. // fail silently for now
  13713. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13714. initDirectBuffers( geometry );
  13715. } else if ( object instanceof THREE.Mesh ) {
  13716. material = object.material;
  13717. if ( geometry.geometryGroups === undefined ) {
  13718. sortFacesByMaterial( geometry, material );
  13719. }
  13720. // create separate VBOs per geometry chunk
  13721. for ( g in geometry.geometryGroups ) {
  13722. geometryGroup = geometry.geometryGroups[ g ];
  13723. // initialise VBO on the first access
  13724. if ( ! geometryGroup.__webglVertexBuffer ) {
  13725. createMeshBuffers( geometryGroup );
  13726. initMeshBuffers( geometryGroup, object );
  13727. geometry.verticesNeedUpdate = true;
  13728. geometry.morphTargetsNeedUpdate = true;
  13729. geometry.elementsNeedUpdate = true;
  13730. geometry.uvsNeedUpdate = true;
  13731. geometry.normalsNeedUpdate = true;
  13732. geometry.tangentsNeedUpdate = true;
  13733. geometry.colorsNeedUpdate = true;
  13734. }
  13735. }
  13736. } else if ( object instanceof THREE.Ribbon ) {
  13737. if ( ! geometry.__webglVertexBuffer ) {
  13738. createRibbonBuffers( geometry );
  13739. initRibbonBuffers( geometry, object );
  13740. geometry.verticesNeedUpdate = true;
  13741. geometry.colorsNeedUpdate = true;
  13742. geometry.normalsNeedUpdate = true;
  13743. }
  13744. } else if ( object instanceof THREE.Line ) {
  13745. if ( ! geometry.__webglVertexBuffer ) {
  13746. createLineBuffers( geometry );
  13747. initLineBuffers( geometry, object );
  13748. geometry.verticesNeedUpdate = true;
  13749. geometry.colorsNeedUpdate = true;
  13750. geometry.lineDistancesNeedUpdate = true;
  13751. }
  13752. } else if ( object instanceof THREE.ParticleSystem ) {
  13753. if ( ! geometry.__webglVertexBuffer ) {
  13754. createParticleBuffers( geometry );
  13755. initParticleBuffers( geometry, object );
  13756. geometry.verticesNeedUpdate = true;
  13757. geometry.colorsNeedUpdate = true;
  13758. }
  13759. }
  13760. }
  13761. if ( object.__webglActive === undefined ) {
  13762. if ( object instanceof THREE.Mesh ) {
  13763. geometry = object.geometry;
  13764. if ( geometry instanceof THREE.BufferGeometry ) {
  13765. addBuffer( scene.__webglObjects, geometry, object );
  13766. } else if ( geometry instanceof THREE.Geometry ) {
  13767. for ( g in geometry.geometryGroups ) {
  13768. geometryGroup = geometry.geometryGroups[ g ];
  13769. addBuffer( scene.__webglObjects, geometryGroup, object );
  13770. }
  13771. }
  13772. } else if ( object instanceof THREE.Ribbon ||
  13773. object instanceof THREE.Line ||
  13774. object instanceof THREE.ParticleSystem ) {
  13775. geometry = object.geometry;
  13776. addBuffer( scene.__webglObjects, geometry, object );
  13777. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13778. addBufferImmediate( scene.__webglObjectsImmediate, object );
  13779. } else if ( object instanceof THREE.Sprite ) {
  13780. scene.__webglSprites.push( object );
  13781. } else if ( object instanceof THREE.LensFlare ) {
  13782. scene.__webglFlares.push( object );
  13783. }
  13784. object.__webglActive = true;
  13785. }
  13786. };
  13787. function addBuffer( objlist, buffer, object ) {
  13788. objlist.push(
  13789. {
  13790. id: null,
  13791. buffer: buffer,
  13792. object: object,
  13793. opaque: null,
  13794. transparent: null,
  13795. z: 0
  13796. }
  13797. );
  13798. };
  13799. function addBufferImmediate( objlist, object ) {
  13800. objlist.push(
  13801. {
  13802. id: null,
  13803. object: object,
  13804. opaque: null,
  13805. transparent: null,
  13806. z: 0
  13807. }
  13808. );
  13809. };
  13810. // Objects updates
  13811. function updateObject( object ) {
  13812. var geometry = object.geometry,
  13813. geometryGroup, customAttributesDirty, material;
  13814. if ( geometry instanceof THREE.BufferGeometry ) {
  13815. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13816. } else if ( object instanceof THREE.Mesh ) {
  13817. // check all geometry groups
  13818. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  13819. geometryGroup = geometry.geometryGroupsList[ i ];
  13820. material = getBufferMaterial( object, geometryGroup );
  13821. if ( geometry.buffersNeedUpdate ) {
  13822. initMeshBuffers( geometryGroup, object );
  13823. }
  13824. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13825. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  13826. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13827. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  13828. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  13829. }
  13830. }
  13831. geometry.verticesNeedUpdate = false;
  13832. geometry.morphTargetsNeedUpdate = false;
  13833. geometry.elementsNeedUpdate = false;
  13834. geometry.uvsNeedUpdate = false;
  13835. geometry.normalsNeedUpdate = false;
  13836. geometry.colorsNeedUpdate = false;
  13837. geometry.tangentsNeedUpdate = false;
  13838. geometry.buffersNeedUpdate = false;
  13839. material.attributes && clearCustomAttributes( material );
  13840. } else if ( object instanceof THREE.Ribbon ) {
  13841. material = getBufferMaterial( object, geometry );
  13842. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13843. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  13844. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  13845. }
  13846. geometry.verticesNeedUpdate = false;
  13847. geometry.colorsNeedUpdate = false;
  13848. geometry.normalsNeedUpdate = false;
  13849. material.attributes && clearCustomAttributes( material );
  13850. } else if ( object instanceof THREE.Line ) {
  13851. material = getBufferMaterial( object, geometry );
  13852. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13853. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  13854. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  13855. }
  13856. geometry.verticesNeedUpdate = false;
  13857. geometry.colorsNeedUpdate = false;
  13858. geometry.lineDistancesNeedUpdate = false;
  13859. material.attributes && clearCustomAttributes( material );
  13860. } else if ( object instanceof THREE.ParticleSystem ) {
  13861. material = getBufferMaterial( object, geometry );
  13862. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13863. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  13864. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  13865. }
  13866. geometry.verticesNeedUpdate = false;
  13867. geometry.colorsNeedUpdate = false;
  13868. material.attributes && clearCustomAttributes( material );
  13869. }
  13870. };
  13871. // Objects updates - custom attributes check
  13872. function areCustomAttributesDirty( material ) {
  13873. for ( var a in material.attributes ) {
  13874. if ( material.attributes[ a ].needsUpdate ) return true;
  13875. }
  13876. return false;
  13877. };
  13878. function clearCustomAttributes( material ) {
  13879. for ( var a in material.attributes ) {
  13880. material.attributes[ a ].needsUpdate = false;
  13881. }
  13882. };
  13883. // Objects removal
  13884. function removeObject( object, scene ) {
  13885. if ( object instanceof THREE.Mesh ||
  13886. object instanceof THREE.ParticleSystem ||
  13887. object instanceof THREE.Ribbon ||
  13888. object instanceof THREE.Line ) {
  13889. removeInstances( scene.__webglObjects, object );
  13890. } else if ( object instanceof THREE.Sprite ) {
  13891. removeInstancesDirect( scene.__webglSprites, object );
  13892. } else if ( object instanceof THREE.LensFlare ) {
  13893. removeInstancesDirect( scene.__webglFlares, object );
  13894. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13895. removeInstances( scene.__webglObjectsImmediate, object );
  13896. }
  13897. delete object.__webglActive;
  13898. };
  13899. function removeInstances( objlist, object ) {
  13900. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13901. if ( objlist[ o ].object === object ) {
  13902. objlist.splice( o, 1 );
  13903. }
  13904. }
  13905. };
  13906. function removeInstancesDirect( objlist, object ) {
  13907. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13908. if ( objlist[ o ] === object ) {
  13909. objlist.splice( o, 1 );
  13910. }
  13911. }
  13912. };
  13913. // Materials
  13914. this.initMaterial = function ( material, lights, fog, object ) {
  13915. material.addEventListener( 'dispose', onMaterialDispose );
  13916. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  13917. if ( material instanceof THREE.MeshDepthMaterial ) {
  13918. shaderID = 'depth';
  13919. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13920. shaderID = 'normal';
  13921. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  13922. shaderID = 'basic';
  13923. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13924. shaderID = 'lambert';
  13925. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13926. shaderID = 'phong';
  13927. } else if ( material instanceof THREE.LineBasicMaterial ) {
  13928. shaderID = 'basic';
  13929. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13930. shaderID = 'dashed';
  13931. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13932. shaderID = 'particle_basic';
  13933. }
  13934. if ( shaderID ) {
  13935. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  13936. }
  13937. // heuristics to create shader parameters according to lights in the scene
  13938. // (not to blow over maxLights budget)
  13939. maxLightCount = allocateLights( lights );
  13940. maxShadows = allocateShadows( lights );
  13941. maxBones = allocateBones( object );
  13942. parameters = {
  13943. map: !!material.map,
  13944. envMap: !!material.envMap,
  13945. lightMap: !!material.lightMap,
  13946. bumpMap: !!material.bumpMap,
  13947. normalMap: !!material.normalMap,
  13948. specularMap: !!material.specularMap,
  13949. vertexColors: material.vertexColors,
  13950. fog: fog,
  13951. useFog: material.fog,
  13952. fogExp: fog instanceof THREE.FogExp2,
  13953. sizeAttenuation: material.sizeAttenuation,
  13954. skinning: material.skinning,
  13955. maxBones: maxBones,
  13956. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  13957. boneTextureWidth: object && object.boneTextureWidth,
  13958. boneTextureHeight: object && object.boneTextureHeight,
  13959. morphTargets: material.morphTargets,
  13960. morphNormals: material.morphNormals,
  13961. maxMorphTargets: this.maxMorphTargets,
  13962. maxMorphNormals: this.maxMorphNormals,
  13963. maxDirLights: maxLightCount.directional,
  13964. maxPointLights: maxLightCount.point,
  13965. maxSpotLights: maxLightCount.spot,
  13966. maxHemiLights: maxLightCount.hemi,
  13967. maxShadows: maxShadows,
  13968. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  13969. shadowMapType: this.shadowMapType,
  13970. shadowMapDebug: this.shadowMapDebug,
  13971. shadowMapCascade: this.shadowMapCascade,
  13972. alphaTest: material.alphaTest,
  13973. metal: material.metal,
  13974. perPixel: material.perPixel,
  13975. wrapAround: material.wrapAround,
  13976. doubleSided: material.side === THREE.DoubleSide,
  13977. flipSided: material.side === THREE.BackSide
  13978. };
  13979. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters, material.index0AttributeName );
  13980. var attributes = material.program.attributes;
  13981. if ( material.morphTargets ) {
  13982. material.numSupportedMorphTargets = 0;
  13983. var id, base = "morphTarget";
  13984. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  13985. id = base + i;
  13986. if ( attributes[ id ] >= 0 ) {
  13987. material.numSupportedMorphTargets ++;
  13988. }
  13989. }
  13990. }
  13991. if ( material.morphNormals ) {
  13992. material.numSupportedMorphNormals = 0;
  13993. var id, base = "morphNormal";
  13994. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  13995. id = base + i;
  13996. if ( attributes[ id ] >= 0 ) {
  13997. material.numSupportedMorphNormals ++;
  13998. }
  13999. }
  14000. }
  14001. material.uniformsList = [];
  14002. for ( u in material.uniforms ) {
  14003. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14004. }
  14005. };
  14006. function setMaterialShaders( material, shaders ) {
  14007. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14008. material.vertexShader = shaders.vertexShader;
  14009. material.fragmentShader = shaders.fragmentShader;
  14010. };
  14011. function setProgram( camera, lights, fog, material, object ) {
  14012. _usedTextureUnits = 0;
  14013. if ( material.needsUpdate ) {
  14014. if ( material.program ) deallocateMaterial( material );
  14015. _this.initMaterial( material, lights, fog, object );
  14016. material.needsUpdate = false;
  14017. }
  14018. if ( material.morphTargets ) {
  14019. if ( ! object.__webglMorphTargetInfluences ) {
  14020. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14021. }
  14022. }
  14023. var refreshMaterial = false;
  14024. var program = material.program,
  14025. p_uniforms = program.uniforms,
  14026. m_uniforms = material.uniforms;
  14027. if ( program !== _currentProgram ) {
  14028. _gl.useProgram( program );
  14029. _currentProgram = program;
  14030. refreshMaterial = true;
  14031. }
  14032. if ( material.id !== _currentMaterialId ) {
  14033. _currentMaterialId = material.id;
  14034. refreshMaterial = true;
  14035. }
  14036. if ( refreshMaterial || camera !== _currentCamera ) {
  14037. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14038. if ( camera !== _currentCamera ) _currentCamera = camera;
  14039. }
  14040. // skinning uniforms must be set even if material didn't change
  14041. // auto-setting of texture unit for bone texture must go before other textures
  14042. // not sure why, but otherwise weird things happen
  14043. if ( material.skinning ) {
  14044. if ( _supportsBoneTextures && object.useVertexTexture ) {
  14045. if ( p_uniforms.boneTexture !== null ) {
  14046. var textureUnit = getTextureUnit();
  14047. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14048. _this.setTexture( object.boneTexture, textureUnit );
  14049. }
  14050. } else {
  14051. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14052. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  14053. }
  14054. }
  14055. }
  14056. if ( refreshMaterial ) {
  14057. // refresh uniforms common to several materials
  14058. if ( fog && material.fog ) {
  14059. refreshUniformsFog( m_uniforms, fog );
  14060. }
  14061. if ( material instanceof THREE.MeshPhongMaterial ||
  14062. material instanceof THREE.MeshLambertMaterial ||
  14063. material.lights ) {
  14064. if ( _lightsNeedUpdate ) {
  14065. setupLights( program, lights );
  14066. _lightsNeedUpdate = false;
  14067. }
  14068. refreshUniformsLights( m_uniforms, _lights );
  14069. }
  14070. if ( material instanceof THREE.MeshBasicMaterial ||
  14071. material instanceof THREE.MeshLambertMaterial ||
  14072. material instanceof THREE.MeshPhongMaterial ) {
  14073. refreshUniformsCommon( m_uniforms, material );
  14074. }
  14075. // refresh single material specific uniforms
  14076. if ( material instanceof THREE.LineBasicMaterial ) {
  14077. refreshUniformsLine( m_uniforms, material );
  14078. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14079. refreshUniformsLine( m_uniforms, material );
  14080. refreshUniformsDash( m_uniforms, material );
  14081. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  14082. refreshUniformsParticle( m_uniforms, material );
  14083. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14084. refreshUniformsPhong( m_uniforms, material );
  14085. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14086. refreshUniformsLambert( m_uniforms, material );
  14087. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14088. m_uniforms.mNear.value = camera.near;
  14089. m_uniforms.mFar.value = camera.far;
  14090. m_uniforms.opacity.value = material.opacity;
  14091. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14092. m_uniforms.opacity.value = material.opacity;
  14093. }
  14094. if ( object.receiveShadow && ! material._shadowPass ) {
  14095. refreshUniformsShadow( m_uniforms, lights );
  14096. }
  14097. // load common uniforms
  14098. loadUniformsGeneric( program, material.uniformsList );
  14099. // load material specific uniforms
  14100. // (shader material also gets them for the sake of genericity)
  14101. if ( material instanceof THREE.ShaderMaterial ||
  14102. material instanceof THREE.MeshPhongMaterial ||
  14103. material.envMap ) {
  14104. if ( p_uniforms.cameraPosition !== null ) {
  14105. _vector3.getPositionFromMatrix( camera.matrixWorld );
  14106. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14107. }
  14108. }
  14109. if ( material instanceof THREE.MeshPhongMaterial ||
  14110. material instanceof THREE.MeshLambertMaterial ||
  14111. material instanceof THREE.ShaderMaterial ||
  14112. material.skinning ) {
  14113. if ( p_uniforms.viewMatrix !== null ) {
  14114. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14115. }
  14116. }
  14117. }
  14118. loadUniformsMatrices( p_uniforms, object );
  14119. if ( p_uniforms.modelMatrix !== null ) {
  14120. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14121. }
  14122. return program;
  14123. };
  14124. // Uniforms (refresh uniforms objects)
  14125. function refreshUniformsCommon ( uniforms, material ) {
  14126. uniforms.opacity.value = material.opacity;
  14127. if ( _this.gammaInput ) {
  14128. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14129. } else {
  14130. uniforms.diffuse.value = material.color;
  14131. }
  14132. uniforms.map.value = material.map;
  14133. uniforms.lightMap.value = material.lightMap;
  14134. uniforms.specularMap.value = material.specularMap;
  14135. if ( material.bumpMap ) {
  14136. uniforms.bumpMap.value = material.bumpMap;
  14137. uniforms.bumpScale.value = material.bumpScale;
  14138. }
  14139. if ( material.normalMap ) {
  14140. uniforms.normalMap.value = material.normalMap;
  14141. uniforms.normalScale.value.copy( material.normalScale );
  14142. }
  14143. // uv repeat and offset setting priorities
  14144. // 1. color map
  14145. // 2. specular map
  14146. // 3. normal map
  14147. // 4. bump map
  14148. var uvScaleMap;
  14149. if ( material.map ) {
  14150. uvScaleMap = material.map;
  14151. } else if ( material.specularMap ) {
  14152. uvScaleMap = material.specularMap;
  14153. } else if ( material.normalMap ) {
  14154. uvScaleMap = material.normalMap;
  14155. } else if ( material.bumpMap ) {
  14156. uvScaleMap = material.bumpMap;
  14157. }
  14158. if ( uvScaleMap !== undefined ) {
  14159. var offset = uvScaleMap.offset;
  14160. var repeat = uvScaleMap.repeat;
  14161. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14162. }
  14163. uniforms.envMap.value = material.envMap;
  14164. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14165. if ( _this.gammaInput ) {
  14166. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14167. uniforms.reflectivity.value = material.reflectivity;
  14168. } else {
  14169. uniforms.reflectivity.value = material.reflectivity;
  14170. }
  14171. uniforms.refractionRatio.value = material.refractionRatio;
  14172. uniforms.combine.value = material.combine;
  14173. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14174. };
  14175. function refreshUniformsLine ( uniforms, material ) {
  14176. uniforms.diffuse.value = material.color;
  14177. uniforms.opacity.value = material.opacity;
  14178. };
  14179. function refreshUniformsDash ( uniforms, material ) {
  14180. uniforms.dashSize.value = material.dashSize;
  14181. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14182. uniforms.scale.value = material.scale;
  14183. };
  14184. function refreshUniformsParticle ( uniforms, material ) {
  14185. uniforms.psColor.value = material.color;
  14186. uniforms.opacity.value = material.opacity;
  14187. uniforms.size.value = material.size;
  14188. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14189. uniforms.map.value = material.map;
  14190. };
  14191. function refreshUniformsFog ( uniforms, fog ) {
  14192. uniforms.fogColor.value = fog.color;
  14193. if ( fog instanceof THREE.Fog ) {
  14194. uniforms.fogNear.value = fog.near;
  14195. uniforms.fogFar.value = fog.far;
  14196. } else if ( fog instanceof THREE.FogExp2 ) {
  14197. uniforms.fogDensity.value = fog.density;
  14198. }
  14199. };
  14200. function refreshUniformsPhong ( uniforms, material ) {
  14201. uniforms.shininess.value = material.shininess;
  14202. if ( _this.gammaInput ) {
  14203. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14204. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14205. uniforms.specular.value.copyGammaToLinear( material.specular );
  14206. } else {
  14207. uniforms.ambient.value = material.ambient;
  14208. uniforms.emissive.value = material.emissive;
  14209. uniforms.specular.value = material.specular;
  14210. }
  14211. if ( material.wrapAround ) {
  14212. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14213. }
  14214. };
  14215. function refreshUniformsLambert ( uniforms, material ) {
  14216. if ( _this.gammaInput ) {
  14217. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14218. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14219. } else {
  14220. uniforms.ambient.value = material.ambient;
  14221. uniforms.emissive.value = material.emissive;
  14222. }
  14223. if ( material.wrapAround ) {
  14224. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14225. }
  14226. };
  14227. function refreshUniformsLights ( uniforms, lights ) {
  14228. uniforms.ambientLightColor.value = lights.ambient;
  14229. uniforms.directionalLightColor.value = lights.directional.colors;
  14230. uniforms.directionalLightDirection.value = lights.directional.positions;
  14231. uniforms.pointLightColor.value = lights.point.colors;
  14232. uniforms.pointLightPosition.value = lights.point.positions;
  14233. uniforms.pointLightDistance.value = lights.point.distances;
  14234. uniforms.spotLightColor.value = lights.spot.colors;
  14235. uniforms.spotLightPosition.value = lights.spot.positions;
  14236. uniforms.spotLightDistance.value = lights.spot.distances;
  14237. uniforms.spotLightDirection.value = lights.spot.directions;
  14238. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14239. uniforms.spotLightExponent.value = lights.spot.exponents;
  14240. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14241. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14242. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14243. };
  14244. function refreshUniformsShadow ( uniforms, lights ) {
  14245. if ( uniforms.shadowMatrix ) {
  14246. var j = 0;
  14247. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14248. var light = lights[ i ];
  14249. if ( ! light.castShadow ) continue;
  14250. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14251. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14252. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14253. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14254. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14255. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14256. j ++;
  14257. }
  14258. }
  14259. }
  14260. };
  14261. // Uniforms (load to GPU)
  14262. function loadUniformsMatrices ( uniforms, object ) {
  14263. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14264. if ( uniforms.normalMatrix ) {
  14265. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14266. }
  14267. };
  14268. function getTextureUnit() {
  14269. var textureUnit = _usedTextureUnits;
  14270. if ( textureUnit >= _maxTextures ) {
  14271. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14272. }
  14273. _usedTextureUnits += 1;
  14274. return textureUnit;
  14275. };
  14276. function loadUniformsGeneric ( program, uniforms ) {
  14277. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14278. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14279. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14280. if ( !location ) continue;
  14281. uniform = uniforms[ j ][ 0 ];
  14282. type = uniform.type;
  14283. value = uniform.value;
  14284. if ( type === "i" ) { // single integer
  14285. _gl.uniform1i( location, value );
  14286. } else if ( type === "f" ) { // single float
  14287. _gl.uniform1f( location, value );
  14288. } else if ( type === "v2" ) { // single THREE.Vector2
  14289. _gl.uniform2f( location, value.x, value.y );
  14290. } else if ( type === "v3" ) { // single THREE.Vector3
  14291. _gl.uniform3f( location, value.x, value.y, value.z );
  14292. } else if ( type === "v4" ) { // single THREE.Vector4
  14293. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14294. } else if ( type === "c" ) { // single THREE.Color
  14295. _gl.uniform3f( location, value.r, value.g, value.b );
  14296. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14297. _gl.uniform1iv( location, value );
  14298. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14299. _gl.uniform3iv( location, value );
  14300. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14301. _gl.uniform1fv( location, value );
  14302. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14303. _gl.uniform3fv( location, value );
  14304. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14305. if ( uniform._array === undefined ) {
  14306. uniform._array = new Float32Array( 2 * value.length );
  14307. }
  14308. for ( i = 0, il = value.length; i < il; i ++ ) {
  14309. offset = i * 2;
  14310. uniform._array[ offset ] = value[ i ].x;
  14311. uniform._array[ offset + 1 ] = value[ i ].y;
  14312. }
  14313. _gl.uniform2fv( location, uniform._array );
  14314. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14315. if ( uniform._array === undefined ) {
  14316. uniform._array = new Float32Array( 3 * value.length );
  14317. }
  14318. for ( i = 0, il = value.length; i < il; i ++ ) {
  14319. offset = i * 3;
  14320. uniform._array[ offset ] = value[ i ].x;
  14321. uniform._array[ offset + 1 ] = value[ i ].y;
  14322. uniform._array[ offset + 2 ] = value[ i ].z;
  14323. }
  14324. _gl.uniform3fv( location, uniform._array );
  14325. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14326. if ( uniform._array === undefined ) {
  14327. uniform._array = new Float32Array( 4 * value.length );
  14328. }
  14329. for ( i = 0, il = value.length; i < il; i ++ ) {
  14330. offset = i * 4;
  14331. uniform._array[ offset ] = value[ i ].x;
  14332. uniform._array[ offset + 1 ] = value[ i ].y;
  14333. uniform._array[ offset + 2 ] = value[ i ].z;
  14334. uniform._array[ offset + 3 ] = value[ i ].w;
  14335. }
  14336. _gl.uniform4fv( location, uniform._array );
  14337. } else if ( type === "m4") { // single THREE.Matrix4
  14338. if ( uniform._array === undefined ) {
  14339. uniform._array = new Float32Array( 16 );
  14340. }
  14341. value.flattenToArray( uniform._array );
  14342. _gl.uniformMatrix4fv( location, false, uniform._array );
  14343. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14344. if ( uniform._array === undefined ) {
  14345. uniform._array = new Float32Array( 16 * value.length );
  14346. }
  14347. for ( i = 0, il = value.length; i < il; i ++ ) {
  14348. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14349. }
  14350. _gl.uniformMatrix4fv( location, false, uniform._array );
  14351. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14352. texture = value;
  14353. textureUnit = getTextureUnit();
  14354. _gl.uniform1i( location, textureUnit );
  14355. if ( !texture ) continue;
  14356. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14357. setCubeTexture( texture, textureUnit );
  14358. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14359. setCubeTextureDynamic( texture, textureUnit );
  14360. } else {
  14361. _this.setTexture( texture, textureUnit );
  14362. }
  14363. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14364. if ( uniform._array === undefined ) {
  14365. uniform._array = [];
  14366. }
  14367. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14368. uniform._array[ i ] = getTextureUnit();
  14369. }
  14370. _gl.uniform1iv( location, uniform._array );
  14371. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14372. texture = uniform.value[ i ];
  14373. textureUnit = uniform._array[ i ];
  14374. if ( !texture ) continue;
  14375. _this.setTexture( texture, textureUnit );
  14376. }
  14377. } else {
  14378. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  14379. }
  14380. }
  14381. };
  14382. function setupMatrices ( object, camera ) {
  14383. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14384. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14385. };
  14386. //
  14387. function setColorGamma( array, offset, color, intensitySq ) {
  14388. array[ offset ] = color.r * color.r * intensitySq;
  14389. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14390. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14391. };
  14392. function setColorLinear( array, offset, color, intensity ) {
  14393. array[ offset ] = color.r * intensity;
  14394. array[ offset + 1 ] = color.g * intensity;
  14395. array[ offset + 2 ] = color.b * intensity;
  14396. };
  14397. function setupLights ( program, lights ) {
  14398. var l, ll, light, n,
  14399. r = 0, g = 0, b = 0,
  14400. color, skyColor, groundColor,
  14401. intensity, intensitySq,
  14402. position,
  14403. distance,
  14404. zlights = _lights,
  14405. dirColors = zlights.directional.colors,
  14406. dirPositions = zlights.directional.positions,
  14407. pointColors = zlights.point.colors,
  14408. pointPositions = zlights.point.positions,
  14409. pointDistances = zlights.point.distances,
  14410. spotColors = zlights.spot.colors,
  14411. spotPositions = zlights.spot.positions,
  14412. spotDistances = zlights.spot.distances,
  14413. spotDirections = zlights.spot.directions,
  14414. spotAnglesCos = zlights.spot.anglesCos,
  14415. spotExponents = zlights.spot.exponents,
  14416. hemiSkyColors = zlights.hemi.skyColors,
  14417. hemiGroundColors = zlights.hemi.groundColors,
  14418. hemiPositions = zlights.hemi.positions,
  14419. dirLength = 0,
  14420. pointLength = 0,
  14421. spotLength = 0,
  14422. hemiLength = 0,
  14423. dirCount = 0,
  14424. pointCount = 0,
  14425. spotCount = 0,
  14426. hemiCount = 0,
  14427. dirOffset = 0,
  14428. pointOffset = 0,
  14429. spotOffset = 0,
  14430. hemiOffset = 0;
  14431. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14432. light = lights[ l ];
  14433. if ( light.onlyShadow ) continue;
  14434. color = light.color;
  14435. intensity = light.intensity;
  14436. distance = light.distance;
  14437. if ( light instanceof THREE.AmbientLight ) {
  14438. if ( ! light.visible ) continue;
  14439. if ( _this.gammaInput ) {
  14440. r += color.r * color.r;
  14441. g += color.g * color.g;
  14442. b += color.b * color.b;
  14443. } else {
  14444. r += color.r;
  14445. g += color.g;
  14446. b += color.b;
  14447. }
  14448. } else if ( light instanceof THREE.DirectionalLight ) {
  14449. dirCount += 1;
  14450. if ( ! light.visible ) continue;
  14451. _direction.getPositionFromMatrix( light.matrixWorld );
  14452. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14453. _direction.sub( _vector3 );
  14454. _direction.normalize();
  14455. // skip lights with undefined direction
  14456. // these create troubles in OpenGL (making pixel black)
  14457. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14458. dirOffset = dirLength * 3;
  14459. dirPositions[ dirOffset ] = _direction.x;
  14460. dirPositions[ dirOffset + 1 ] = _direction.y;
  14461. dirPositions[ dirOffset + 2 ] = _direction.z;
  14462. if ( _this.gammaInput ) {
  14463. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14464. } else {
  14465. setColorLinear( dirColors, dirOffset, color, intensity );
  14466. }
  14467. dirLength += 1;
  14468. } else if ( light instanceof THREE.PointLight ) {
  14469. pointCount += 1;
  14470. if ( ! light.visible ) continue;
  14471. pointOffset = pointLength * 3;
  14472. if ( _this.gammaInput ) {
  14473. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14474. } else {
  14475. setColorLinear( pointColors, pointOffset, color, intensity );
  14476. }
  14477. _vector3.getPositionFromMatrix( light.matrixWorld );
  14478. pointPositions[ pointOffset ] = _vector3.x;
  14479. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14480. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14481. pointDistances[ pointLength ] = distance;
  14482. pointLength += 1;
  14483. } else if ( light instanceof THREE.SpotLight ) {
  14484. spotCount += 1;
  14485. if ( ! light.visible ) continue;
  14486. spotOffset = spotLength * 3;
  14487. if ( _this.gammaInput ) {
  14488. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14489. } else {
  14490. setColorLinear( spotColors, spotOffset, color, intensity );
  14491. }
  14492. _vector3.getPositionFromMatrix( light.matrixWorld );
  14493. spotPositions[ spotOffset ] = _vector3.x;
  14494. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14495. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14496. spotDistances[ spotLength ] = distance;
  14497. _direction.copy( _vector3 );
  14498. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14499. _direction.sub( _vector3 );
  14500. _direction.normalize();
  14501. spotDirections[ spotOffset ] = _direction.x;
  14502. spotDirections[ spotOffset + 1 ] = _direction.y;
  14503. spotDirections[ spotOffset + 2 ] = _direction.z;
  14504. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14505. spotExponents[ spotLength ] = light.exponent;
  14506. spotLength += 1;
  14507. } else if ( light instanceof THREE.HemisphereLight ) {
  14508. hemiCount += 1;
  14509. if ( ! light.visible ) continue;
  14510. _direction.getPositionFromMatrix( light.matrixWorld );
  14511. _direction.normalize();
  14512. // skip lights with undefined direction
  14513. // these create troubles in OpenGL (making pixel black)
  14514. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14515. hemiOffset = hemiLength * 3;
  14516. hemiPositions[ hemiOffset ] = _direction.x;
  14517. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14518. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14519. skyColor = light.color;
  14520. groundColor = light.groundColor;
  14521. if ( _this.gammaInput ) {
  14522. intensitySq = intensity * intensity;
  14523. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14524. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14525. } else {
  14526. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14527. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14528. }
  14529. hemiLength += 1;
  14530. }
  14531. }
  14532. // null eventual remains from removed lights
  14533. // (this is to avoid if in shader)
  14534. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14535. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14536. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14537. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14538. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14539. zlights.directional.length = dirLength;
  14540. zlights.point.length = pointLength;
  14541. zlights.spot.length = spotLength;
  14542. zlights.hemi.length = hemiLength;
  14543. zlights.ambient[ 0 ] = r;
  14544. zlights.ambient[ 1 ] = g;
  14545. zlights.ambient[ 2 ] = b;
  14546. };
  14547. // GL state setting
  14548. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14549. if ( cullFace === THREE.CullFaceNone ) {
  14550. _gl.disable( _gl.CULL_FACE );
  14551. } else {
  14552. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14553. _gl.frontFace( _gl.CW );
  14554. } else {
  14555. _gl.frontFace( _gl.CCW );
  14556. }
  14557. if ( cullFace === THREE.CullFaceBack ) {
  14558. _gl.cullFace( _gl.BACK );
  14559. } else if ( cullFace === THREE.CullFaceFront ) {
  14560. _gl.cullFace( _gl.FRONT );
  14561. } else {
  14562. _gl.cullFace( _gl.FRONT_AND_BACK );
  14563. }
  14564. _gl.enable( _gl.CULL_FACE );
  14565. }
  14566. };
  14567. this.setMaterialFaces = function ( material ) {
  14568. var doubleSided = material.side === THREE.DoubleSide;
  14569. var flipSided = material.side === THREE.BackSide;
  14570. if ( _oldDoubleSided !== doubleSided ) {
  14571. if ( doubleSided ) {
  14572. _gl.disable( _gl.CULL_FACE );
  14573. } else {
  14574. _gl.enable( _gl.CULL_FACE );
  14575. }
  14576. _oldDoubleSided = doubleSided;
  14577. }
  14578. if ( _oldFlipSided !== flipSided ) {
  14579. if ( flipSided ) {
  14580. _gl.frontFace( _gl.CW );
  14581. } else {
  14582. _gl.frontFace( _gl.CCW );
  14583. }
  14584. _oldFlipSided = flipSided;
  14585. }
  14586. };
  14587. this.setDepthTest = function ( depthTest ) {
  14588. if ( _oldDepthTest !== depthTest ) {
  14589. if ( depthTest ) {
  14590. _gl.enable( _gl.DEPTH_TEST );
  14591. } else {
  14592. _gl.disable( _gl.DEPTH_TEST );
  14593. }
  14594. _oldDepthTest = depthTest;
  14595. }
  14596. };
  14597. this.setDepthWrite = function ( depthWrite ) {
  14598. if ( _oldDepthWrite !== depthWrite ) {
  14599. _gl.depthMask( depthWrite );
  14600. _oldDepthWrite = depthWrite;
  14601. }
  14602. };
  14603. function setLineWidth ( width ) {
  14604. if ( width !== _oldLineWidth ) {
  14605. _gl.lineWidth( width );
  14606. _oldLineWidth = width;
  14607. }
  14608. };
  14609. function setPolygonOffset ( polygonoffset, factor, units ) {
  14610. if ( _oldPolygonOffset !== polygonoffset ) {
  14611. if ( polygonoffset ) {
  14612. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  14613. } else {
  14614. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  14615. }
  14616. _oldPolygonOffset = polygonoffset;
  14617. }
  14618. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  14619. _gl.polygonOffset( factor, units );
  14620. _oldPolygonOffsetFactor = factor;
  14621. _oldPolygonOffsetUnits = units;
  14622. }
  14623. };
  14624. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  14625. if ( blending !== _oldBlending ) {
  14626. if ( blending === THREE.NoBlending ) {
  14627. _gl.disable( _gl.BLEND );
  14628. } else if ( blending === THREE.AdditiveBlending ) {
  14629. _gl.enable( _gl.BLEND );
  14630. _gl.blendEquation( _gl.FUNC_ADD );
  14631. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  14632. } else if ( blending === THREE.SubtractiveBlending ) {
  14633. // TODO: Find blendFuncSeparate() combination
  14634. _gl.enable( _gl.BLEND );
  14635. _gl.blendEquation( _gl.FUNC_ADD );
  14636. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  14637. } else if ( blending === THREE.MultiplyBlending ) {
  14638. // TODO: Find blendFuncSeparate() combination
  14639. _gl.enable( _gl.BLEND );
  14640. _gl.blendEquation( _gl.FUNC_ADD );
  14641. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  14642. } else if ( blending === THREE.CustomBlending ) {
  14643. _gl.enable( _gl.BLEND );
  14644. } else {
  14645. _gl.enable( _gl.BLEND );
  14646. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  14647. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  14648. }
  14649. _oldBlending = blending;
  14650. }
  14651. if ( blending === THREE.CustomBlending ) {
  14652. if ( blendEquation !== _oldBlendEquation ) {
  14653. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  14654. _oldBlendEquation = blendEquation;
  14655. }
  14656. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  14657. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  14658. _oldBlendSrc = blendSrc;
  14659. _oldBlendDst = blendDst;
  14660. }
  14661. } else {
  14662. _oldBlendEquation = null;
  14663. _oldBlendSrc = null;
  14664. _oldBlendDst = null;
  14665. }
  14666. };
  14667. // Defines
  14668. function generateDefines ( defines ) {
  14669. var value, chunk, chunks = [];
  14670. for ( var d in defines ) {
  14671. value = defines[ d ];
  14672. if ( value === false ) continue;
  14673. chunk = "#define " + d + " " + value;
  14674. chunks.push( chunk );
  14675. }
  14676. return chunks.join( "\n" );
  14677. };
  14678. // Shaders
  14679. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters, index0AttributeName ) {
  14680. var p, pl, d, program, code;
  14681. var chunks = [];
  14682. // Generate code
  14683. if ( shaderID ) {
  14684. chunks.push( shaderID );
  14685. } else {
  14686. chunks.push( fragmentShader );
  14687. chunks.push( vertexShader );
  14688. }
  14689. for ( d in defines ) {
  14690. chunks.push( d );
  14691. chunks.push( defines[ d ] );
  14692. }
  14693. for ( p in parameters ) {
  14694. chunks.push( p );
  14695. chunks.push( parameters[ p ] );
  14696. }
  14697. code = chunks.join();
  14698. // Check if code has been already compiled
  14699. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  14700. var programInfo = _programs[ p ];
  14701. if ( programInfo.code === code ) {
  14702. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  14703. programInfo.usedTimes ++;
  14704. return programInfo.program;
  14705. }
  14706. }
  14707. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  14708. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  14709. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  14710. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  14711. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  14712. }
  14713. // console.log( "building new program " );
  14714. //
  14715. var customDefines = generateDefines( defines );
  14716. //
  14717. program = _gl.createProgram();
  14718. var prefix_vertex = [
  14719. "precision " + _precision + " float;",
  14720. "precision " + _precision + " int;",
  14721. customDefines,
  14722. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  14723. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14724. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14725. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14726. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14727. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14728. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14729. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14730. "#define MAX_SHADOWS " + parameters.maxShadows,
  14731. "#define MAX_BONES " + parameters.maxBones,
  14732. parameters.map ? "#define USE_MAP" : "",
  14733. parameters.envMap ? "#define USE_ENVMAP" : "",
  14734. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14735. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14736. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14737. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14738. parameters.vertexColors ? "#define USE_COLOR" : "",
  14739. parameters.skinning ? "#define USE_SKINNING" : "",
  14740. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  14741. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  14742. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  14743. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  14744. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  14745. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14746. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14747. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14748. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14749. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14750. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14751. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14752. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14753. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  14754. "uniform mat4 modelMatrix;",
  14755. "uniform mat4 modelViewMatrix;",
  14756. "uniform mat4 projectionMatrix;",
  14757. "uniform mat4 viewMatrix;",
  14758. "uniform mat3 normalMatrix;",
  14759. "uniform vec3 cameraPosition;",
  14760. "attribute vec3 position;",
  14761. "attribute vec3 normal;",
  14762. "attribute vec2 uv;",
  14763. "attribute vec2 uv2;",
  14764. "#ifdef USE_COLOR",
  14765. "attribute vec3 color;",
  14766. "#endif",
  14767. "#ifdef USE_MORPHTARGETS",
  14768. "attribute vec3 morphTarget0;",
  14769. "attribute vec3 morphTarget1;",
  14770. "attribute vec3 morphTarget2;",
  14771. "attribute vec3 morphTarget3;",
  14772. "#ifdef USE_MORPHNORMALS",
  14773. "attribute vec3 morphNormal0;",
  14774. "attribute vec3 morphNormal1;",
  14775. "attribute vec3 morphNormal2;",
  14776. "attribute vec3 morphNormal3;",
  14777. "#else",
  14778. "attribute vec3 morphTarget4;",
  14779. "attribute vec3 morphTarget5;",
  14780. "attribute vec3 morphTarget6;",
  14781. "attribute vec3 morphTarget7;",
  14782. "#endif",
  14783. "#endif",
  14784. "#ifdef USE_SKINNING",
  14785. "attribute vec4 skinIndex;",
  14786. "attribute vec4 skinWeight;",
  14787. "#endif",
  14788. ""
  14789. ].join("\n");
  14790. var prefix_fragment = [
  14791. "precision " + _precision + " float;",
  14792. "precision " + _precision + " int;",
  14793. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  14794. customDefines,
  14795. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14796. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14797. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14798. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14799. "#define MAX_SHADOWS " + parameters.maxShadows,
  14800. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  14801. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14802. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14803. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14804. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  14805. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  14806. parameters.map ? "#define USE_MAP" : "",
  14807. parameters.envMap ? "#define USE_ENVMAP" : "",
  14808. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14809. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14810. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14811. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14812. parameters.vertexColors ? "#define USE_COLOR" : "",
  14813. parameters.metal ? "#define METAL" : "",
  14814. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14815. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14816. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14817. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14818. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14819. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14820. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14821. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14822. "uniform mat4 viewMatrix;",
  14823. "uniform vec3 cameraPosition;",
  14824. ""
  14825. ].join("\n");
  14826. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  14827. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  14828. _gl.attachShader( program, glVertexShader );
  14829. _gl.attachShader( program, glFragmentShader );
  14830. //Force a particular attribute to index 0.
  14831. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  14832. //And, color, for example is often automatically bound to index 0 so disabling it
  14833. if ( index0AttributeName ) {
  14834. _gl.bindAttribLocation( program, 0, index0AttributeName );
  14835. }
  14836. _gl.linkProgram( program );
  14837. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  14838. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  14839. console.error( "Program Info Log: " + _gl.getProgramInfoLog( program ) );
  14840. }
  14841. // clean up
  14842. _gl.deleteShader( glFragmentShader );
  14843. _gl.deleteShader( glVertexShader );
  14844. // console.log( prefix_fragment + fragmentShader );
  14845. // console.log( prefix_vertex + vertexShader );
  14846. program.uniforms = {};
  14847. program.attributes = {};
  14848. var identifiers, u, a, i;
  14849. // cache uniform locations
  14850. identifiers = [
  14851. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  14852. 'morphTargetInfluences'
  14853. ];
  14854. if ( parameters.useVertexTexture ) {
  14855. identifiers.push( 'boneTexture' );
  14856. } else {
  14857. identifiers.push( 'boneGlobalMatrices' );
  14858. }
  14859. for ( u in uniforms ) {
  14860. identifiers.push( u );
  14861. }
  14862. cacheUniformLocations( program, identifiers );
  14863. // cache attributes locations
  14864. identifiers = [
  14865. "position", "normal", "uv", "uv2", "tangent", "color",
  14866. "skinIndex", "skinWeight", "lineDistance"
  14867. ];
  14868. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  14869. identifiers.push( "morphTarget" + i );
  14870. }
  14871. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  14872. identifiers.push( "morphNormal" + i );
  14873. }
  14874. for ( a in attributes ) {
  14875. identifiers.push( a );
  14876. }
  14877. cacheAttributeLocations( program, identifiers );
  14878. program.id = _programs_counter ++;
  14879. _programs.push( { program: program, code: code, usedTimes: 1 } );
  14880. _this.info.memory.programs = _programs.length;
  14881. return program;
  14882. };
  14883. // Shader parameters cache
  14884. function cacheUniformLocations ( program, identifiers ) {
  14885. var i, l, id;
  14886. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14887. id = identifiers[ i ];
  14888. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  14889. }
  14890. };
  14891. function cacheAttributeLocations ( program, identifiers ) {
  14892. var i, l, id;
  14893. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14894. id = identifiers[ i ];
  14895. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  14896. }
  14897. };
  14898. function addLineNumbers ( string ) {
  14899. var chunks = string.split( "\n" );
  14900. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  14901. // Chrome reports shader errors on lines
  14902. // starting counting from 1
  14903. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  14904. }
  14905. return chunks.join( "\n" );
  14906. };
  14907. function getShader ( type, string ) {
  14908. var shader;
  14909. if ( type === "fragment" ) {
  14910. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  14911. } else if ( type === "vertex" ) {
  14912. shader = _gl.createShader( _gl.VERTEX_SHADER );
  14913. }
  14914. _gl.shaderSource( shader, string );
  14915. _gl.compileShader( shader );
  14916. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  14917. console.error( _gl.getShaderInfoLog( shader ) );
  14918. console.error( addLineNumbers( string ) );
  14919. return null;
  14920. }
  14921. return shader;
  14922. };
  14923. // Textures
  14924. function isPowerOfTwo ( value ) {
  14925. return ( value & ( value - 1 ) ) === 0;
  14926. };
  14927. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14928. if ( isImagePowerOfTwo ) {
  14929. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14930. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14931. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14932. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14933. } else {
  14934. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14935. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14936. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14937. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14938. }
  14939. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  14940. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  14941. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  14942. texture.__oldAnisotropy = texture.anisotropy;
  14943. }
  14944. }
  14945. };
  14946. this.setTexture = function ( texture, slot ) {
  14947. if ( texture.needsUpdate ) {
  14948. if ( ! texture.__webglInit ) {
  14949. texture.__webglInit = true;
  14950. texture.addEventListener( 'dispose', onTextureDispose );
  14951. texture.__webglTexture = _gl.createTexture();
  14952. _this.info.memory.textures ++;
  14953. }
  14954. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14955. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14956. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14957. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14958. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14959. var image = texture.image,
  14960. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14961. glFormat = paramThreeToGL( texture.format ),
  14962. glType = paramThreeToGL( texture.type );
  14963. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  14964. var mipmap, mipmaps = texture.mipmaps;
  14965. if ( texture instanceof THREE.DataTexture ) {
  14966. // use manually created mipmaps if available
  14967. // if there are no manual mipmaps
  14968. // set 0 level mipmap and then use GL to generate other mipmap levels
  14969. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14970. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14971. mipmap = mipmaps[ i ];
  14972. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14973. }
  14974. texture.generateMipmaps = false;
  14975. } else {
  14976. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14977. }
  14978. } else if ( texture instanceof THREE.CompressedTexture ) {
  14979. // compressed textures can only use manually created mipmaps
  14980. // WebGL can't generate mipmaps for DDS textures
  14981. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14982. mipmap = mipmaps[ i ];
  14983. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14984. }
  14985. } else { // regular Texture (image, video, canvas)
  14986. // use manually created mipmaps if available
  14987. // if there are no manual mipmaps
  14988. // set 0 level mipmap and then use GL to generate other mipmap levels
  14989. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14990. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14991. mipmap = mipmaps[ i ];
  14992. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  14993. }
  14994. texture.generateMipmaps = false;
  14995. } else {
  14996. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  14997. }
  14998. }
  14999. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15000. texture.needsUpdate = false;
  15001. if ( texture.onUpdate ) texture.onUpdate();
  15002. } else {
  15003. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15004. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15005. }
  15006. };
  15007. function clampToMaxSize ( image, maxSize ) {
  15008. if ( image.width <= maxSize && image.height <= maxSize ) {
  15009. return image;
  15010. }
  15011. // Warning: Scaling through the canvas will only work with images that use
  15012. // premultiplied alpha.
  15013. var maxDimension = Math.max( image.width, image.height );
  15014. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15015. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15016. var canvas = document.createElement( 'canvas' );
  15017. canvas.width = newWidth;
  15018. canvas.height = newHeight;
  15019. var ctx = canvas.getContext( "2d" );
  15020. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15021. return canvas;
  15022. }
  15023. function setCubeTexture ( texture, slot ) {
  15024. if ( texture.image.length === 6 ) {
  15025. if ( texture.needsUpdate ) {
  15026. if ( ! texture.image.__webglTextureCube ) {
  15027. texture.addEventListener( 'dispose', onTextureDispose );
  15028. texture.image.__webglTextureCube = _gl.createTexture();
  15029. _this.info.memory.textures ++;
  15030. }
  15031. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15032. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15033. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15034. var isCompressed = texture instanceof THREE.CompressedTexture;
  15035. var cubeImage = [];
  15036. for ( var i = 0; i < 6; i ++ ) {
  15037. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15038. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15039. } else {
  15040. cubeImage[ i ] = texture.image[ i ];
  15041. }
  15042. }
  15043. var image = cubeImage[ 0 ],
  15044. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  15045. glFormat = paramThreeToGL( texture.format ),
  15046. glType = paramThreeToGL( texture.type );
  15047. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15048. for ( var i = 0; i < 6; i ++ ) {
  15049. if ( isCompressed ) {
  15050. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15051. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15052. mipmap = mipmaps[ j ];
  15053. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15054. }
  15055. } else {
  15056. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15057. }
  15058. }
  15059. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15060. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15061. }
  15062. texture.needsUpdate = false;
  15063. if ( texture.onUpdate ) texture.onUpdate();
  15064. } else {
  15065. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15066. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15067. }
  15068. }
  15069. };
  15070. function setCubeTextureDynamic ( texture, slot ) {
  15071. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15072. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15073. };
  15074. // Render targets
  15075. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15076. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15077. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15078. };
  15079. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15080. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15081. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15082. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15083. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15084. /* For some reason this is not working. Defaulting to RGBA4.
  15085. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15086. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15087. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15088. */
  15089. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15090. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15091. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15092. } else {
  15093. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15094. }
  15095. };
  15096. this.setRenderTarget = function ( renderTarget ) {
  15097. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15098. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15099. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15100. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15101. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15102. renderTarget.__webglTexture = _gl.createTexture();
  15103. _this.info.memory.textures ++;
  15104. // Setup texture, create render and frame buffers
  15105. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  15106. glFormat = paramThreeToGL( renderTarget.format ),
  15107. glType = paramThreeToGL( renderTarget.type );
  15108. if ( isCube ) {
  15109. renderTarget.__webglFramebuffer = [];
  15110. renderTarget.__webglRenderbuffer = [];
  15111. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15112. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15113. for ( var i = 0; i < 6; i ++ ) {
  15114. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15115. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15116. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15117. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15118. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15119. }
  15120. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15121. } else {
  15122. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15123. if ( renderTarget.shareDepthFrom ) {
  15124. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15125. } else {
  15126. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15127. }
  15128. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15129. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15130. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15131. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15132. if ( renderTarget.shareDepthFrom ) {
  15133. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15134. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15135. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15136. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15137. }
  15138. } else {
  15139. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15140. }
  15141. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15142. }
  15143. // Release everything
  15144. if ( isCube ) {
  15145. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15146. } else {
  15147. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15148. }
  15149. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15150. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15151. }
  15152. var framebuffer, width, height, vx, vy;
  15153. if ( renderTarget ) {
  15154. if ( isCube ) {
  15155. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15156. } else {
  15157. framebuffer = renderTarget.__webglFramebuffer;
  15158. }
  15159. width = renderTarget.width;
  15160. height = renderTarget.height;
  15161. vx = 0;
  15162. vy = 0;
  15163. } else {
  15164. framebuffer = null;
  15165. width = _viewportWidth;
  15166. height = _viewportHeight;
  15167. vx = _viewportX;
  15168. vy = _viewportY;
  15169. }
  15170. if ( framebuffer !== _currentFramebuffer ) {
  15171. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15172. _gl.viewport( vx, vy, width, height );
  15173. _currentFramebuffer = framebuffer;
  15174. }
  15175. _currentWidth = width;
  15176. _currentHeight = height;
  15177. };
  15178. function updateRenderTargetMipmap ( renderTarget ) {
  15179. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15180. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15181. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15182. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15183. } else {
  15184. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15185. _gl.generateMipmap( _gl.TEXTURE_2D );
  15186. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15187. }
  15188. };
  15189. // Fallback filters for non-power-of-2 textures
  15190. function filterFallback ( f ) {
  15191. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15192. return _gl.NEAREST;
  15193. }
  15194. return _gl.LINEAR;
  15195. };
  15196. // Map three.js constants to WebGL constants
  15197. function paramThreeToGL ( p ) {
  15198. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15199. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15200. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15201. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15202. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15203. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15204. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15205. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15206. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15207. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15208. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15209. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15210. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15211. if ( p === THREE.ByteType ) return _gl.BYTE;
  15212. if ( p === THREE.ShortType ) return _gl.SHORT;
  15213. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15214. if ( p === THREE.IntType ) return _gl.INT;
  15215. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15216. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15217. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15218. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15219. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15220. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15221. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15222. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15223. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15224. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15225. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15226. if ( p === THREE.OneFactor ) return _gl.ONE;
  15227. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15228. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15229. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15230. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15231. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15232. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15233. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15234. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15235. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15236. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15237. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15238. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15239. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15240. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15241. }
  15242. return 0;
  15243. };
  15244. // Allocations
  15245. function allocateBones ( object ) {
  15246. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15247. return 1024;
  15248. } else {
  15249. // default for when object is not specified
  15250. // ( for example when prebuilding shader
  15251. // to be used with multiple objects )
  15252. //
  15253. // - leave some extra space for other uniforms
  15254. // - limit here is ANGLE's 254 max uniform vectors
  15255. // (up to 54 should be safe)
  15256. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15257. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15258. var maxBones = nVertexMatrices;
  15259. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15260. maxBones = Math.min( object.bones.length, maxBones );
  15261. if ( maxBones < object.bones.length ) {
  15262. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15263. }
  15264. }
  15265. return maxBones;
  15266. }
  15267. };
  15268. function allocateLights( lights ) {
  15269. var dirLights = 0;
  15270. var pointLights = 0;
  15271. var spotLights = 0;
  15272. var hemiLights = 0;
  15273. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15274. var light = lights[ l ];
  15275. if ( light.onlyShadow ) continue;
  15276. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15277. if ( light instanceof THREE.PointLight ) pointLights ++;
  15278. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15279. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15280. }
  15281. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15282. };
  15283. function allocateShadows( lights ) {
  15284. var maxShadows = 0;
  15285. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  15286. var light = lights[ l ];
  15287. if ( ! light.castShadow ) continue;
  15288. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15289. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15290. }
  15291. return maxShadows;
  15292. };
  15293. // Initialization
  15294. function initGL() {
  15295. try {
  15296. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  15297. throw 'Error creating WebGL context.';
  15298. }
  15299. } catch ( error ) {
  15300. console.error( error );
  15301. }
  15302. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15303. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15304. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15305. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15306. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15307. if ( ! _glExtensionTextureFloat ) {
  15308. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15309. }
  15310. if ( ! _glExtensionStandardDerivatives ) {
  15311. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15312. }
  15313. if ( ! _glExtensionTextureFilterAnisotropic ) {
  15314. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15315. }
  15316. if ( ! _glExtensionCompressedTextureS3TC ) {
  15317. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15318. }
  15319. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15320. _gl.getShaderPrecisionFormat = function() {
  15321. return {
  15322. "rangeMin" : 1,
  15323. "rangeMax" : 1,
  15324. "precision" : 1
  15325. };
  15326. }
  15327. }
  15328. };
  15329. function setDefaultGLState () {
  15330. _gl.clearColor( 0, 0, 0, 1 );
  15331. _gl.clearDepth( 1 );
  15332. _gl.clearStencil( 0 );
  15333. _gl.enable( _gl.DEPTH_TEST );
  15334. _gl.depthFunc( _gl.LEQUAL );
  15335. _gl.frontFace( _gl.CCW );
  15336. _gl.cullFace( _gl.BACK );
  15337. _gl.enable( _gl.CULL_FACE );
  15338. _gl.enable( _gl.BLEND );
  15339. _gl.blendEquation( _gl.FUNC_ADD );
  15340. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15341. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15342. };
  15343. // default plugins (order is important)
  15344. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15345. this.addPrePlugin( this.shadowMapPlugin );
  15346. this.addPostPlugin( new THREE.SpritePlugin() );
  15347. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15348. };
  15349. /**
  15350. * @author szimek / https://github.com/szimek/
  15351. * @author alteredq / http://alteredqualia.com/
  15352. */
  15353. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15354. this.width = width;
  15355. this.height = height;
  15356. options = options || {};
  15357. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15358. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15359. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15360. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15361. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15362. this.offset = new THREE.Vector2( 0, 0 );
  15363. this.repeat = new THREE.Vector2( 1, 1 );
  15364. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15365. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15366. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15367. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15368. this.generateMipmaps = true;
  15369. this.shareDepthFrom = null;
  15370. };
  15371. THREE.WebGLRenderTarget.prototype = {
  15372. constructor: THREE.WebGLRenderTarget,
  15373. clone: function () {
  15374. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15375. tmp.wrapS = this.wrapS;
  15376. tmp.wrapT = this.wrapT;
  15377. tmp.magFilter = this.magFilter;
  15378. tmp.minFilter = this.minFilter;
  15379. tmp.anisotropy = this.anisotropy;
  15380. tmp.offset.copy( this.offset );
  15381. tmp.repeat.copy( this.repeat );
  15382. tmp.format = this.format;
  15383. tmp.type = this.type;
  15384. tmp.depthBuffer = this.depthBuffer;
  15385. tmp.stencilBuffer = this.stencilBuffer;
  15386. tmp.generateMipmaps = this.generateMipmaps;
  15387. tmp.shareDepthFrom = this.shareDepthFrom;
  15388. return tmp;
  15389. },
  15390. dispose: function () {
  15391. this.dispatchEvent( { type: 'dispose' } );
  15392. }
  15393. };
  15394. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  15395. /**
  15396. * @author alteredq / http://alteredqualia.com
  15397. */
  15398. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15399. THREE.WebGLRenderTarget.call( this, width, height, options );
  15400. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15401. };
  15402. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15403. /**
  15404. * @author mrdoob / http://mrdoob.com/
  15405. */
  15406. THREE.RenderableVertex = function () {
  15407. this.positionWorld = new THREE.Vector3();
  15408. this.positionScreen = new THREE.Vector4();
  15409. this.visible = true;
  15410. };
  15411. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15412. this.positionWorld.copy( vertex.positionWorld );
  15413. this.positionScreen.copy( vertex.positionScreen );
  15414. };
  15415. /**
  15416. * @author mrdoob / http://mrdoob.com/
  15417. */
  15418. THREE.RenderableFace3 = function () {
  15419. this.id = 0;
  15420. this.v1 = new THREE.RenderableVertex();
  15421. this.v2 = new THREE.RenderableVertex();
  15422. this.v3 = new THREE.RenderableVertex();
  15423. this.centroidModel = new THREE.Vector3();
  15424. this.normalModel = new THREE.Vector3();
  15425. this.normalModelView = new THREE.Vector3();
  15426. this.vertexNormalsLength = 0;
  15427. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15428. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15429. this.color = null;
  15430. this.material = null;
  15431. this.uvs = [[]];
  15432. this.z = 0;
  15433. };
  15434. /**
  15435. * @author mrdoob / http://mrdoob.com/
  15436. */
  15437. THREE.RenderableObject = function () {
  15438. this.id = 0;
  15439. this.object = null;
  15440. this.z = 0;
  15441. };
  15442. /**
  15443. * @author mrdoob / http://mrdoob.com/
  15444. */
  15445. THREE.RenderableParticle = function () {
  15446. this.id = 0;
  15447. this.object = null;
  15448. this.x = 0;
  15449. this.y = 0;
  15450. this.z = 0;
  15451. this.rotation = null;
  15452. this.scale = new THREE.Vector2();
  15453. this.material = null;
  15454. };
  15455. /**
  15456. * @author mrdoob / http://mrdoob.com/
  15457. */
  15458. THREE.RenderableLine = function () {
  15459. this.id = 0;
  15460. this.v1 = new THREE.RenderableVertex();
  15461. this.v2 = new THREE.RenderableVertex();
  15462. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  15463. this.material = null;
  15464. this.z = 0;
  15465. };
  15466. /**
  15467. * @author mrdoob / http://mrdoob.com/
  15468. * @author alteredq / http://alteredqualia.com/
  15469. */
  15470. THREE.GeometryUtils = {
  15471. // Merge two geometries or geometry and geometry from object (using object's transform)
  15472. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  15473. var matrix, normalMatrix,
  15474. vertexOffset = geometry1.vertices.length,
  15475. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15476. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15477. vertices1 = geometry1.vertices,
  15478. vertices2 = geometry2.vertices,
  15479. faces1 = geometry1.faces,
  15480. faces2 = geometry2.faces,
  15481. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15482. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15483. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  15484. if ( object2 instanceof THREE.Mesh ) {
  15485. object2.matrixAutoUpdate && object2.updateMatrix();
  15486. matrix = object2.matrix;
  15487. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  15488. }
  15489. // vertices
  15490. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15491. var vertex = vertices2[ i ];
  15492. var vertexCopy = vertex.clone();
  15493. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15494. vertices1.push( vertexCopy );
  15495. }
  15496. // faces
  15497. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15498. var face = faces2[ i ], faceCopy, normal, color,
  15499. faceVertexNormals = face.vertexNormals,
  15500. faceVertexColors = face.vertexColors;
  15501. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15502. faceCopy.normal.copy( face.normal );
  15503. if ( normalMatrix ) {
  15504. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15505. }
  15506. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15507. normal = faceVertexNormals[ j ].clone();
  15508. if ( normalMatrix ) {
  15509. normal.applyMatrix3( normalMatrix ).normalize();
  15510. }
  15511. faceCopy.vertexNormals.push( normal );
  15512. }
  15513. faceCopy.color.copy( face.color );
  15514. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15515. color = faceVertexColors[ j ];
  15516. faceCopy.vertexColors.push( color.clone() );
  15517. }
  15518. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  15519. faceCopy.centroid.copy( face.centroid );
  15520. if ( matrix ) {
  15521. faceCopy.centroid.applyMatrix4( matrix );
  15522. }
  15523. faces1.push( faceCopy );
  15524. }
  15525. // uvs
  15526. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15527. var uv = uvs2[ i ], uvCopy = [];
  15528. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15529. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15530. }
  15531. uvs1.push( uvCopy );
  15532. }
  15533. },
  15534. removeMaterials: function ( geometry, materialIndexArray ) {
  15535. var materialIndexMap = {};
  15536. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  15537. materialIndexMap[ materialIndexArray[i] ] = true;
  15538. }
  15539. var face, newFaces = [];
  15540. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15541. face = geometry.faces[ i ];
  15542. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  15543. }
  15544. geometry.faces = newFaces;
  15545. },
  15546. // Get random point in triangle (via barycentric coordinates)
  15547. // (uniform distribution)
  15548. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15549. randomPointInTriangle: function () {
  15550. var vector = new THREE.Vector3();
  15551. return function ( vectorA, vectorB, vectorC ) {
  15552. var point = new THREE.Vector3();
  15553. var a = THREE.Math.random16();
  15554. var b = THREE.Math.random16();
  15555. if ( ( a + b ) > 1 ) {
  15556. a = 1 - a;
  15557. b = 1 - b;
  15558. }
  15559. var c = 1 - a - b;
  15560. point.copy( vectorA );
  15561. point.multiplyScalar( a );
  15562. vector.copy( vectorB );
  15563. vector.multiplyScalar( b );
  15564. point.add( vector );
  15565. vector.copy( vectorC );
  15566. vector.multiplyScalar( c );
  15567. point.add( vector );
  15568. return point;
  15569. };
  15570. }(),
  15571. // Get random point in face (triangle / quad)
  15572. // (uniform distribution)
  15573. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15574. var vA, vB, vC, vD;
  15575. vA = geometry.vertices[ face.a ];
  15576. vB = geometry.vertices[ face.b ];
  15577. vC = geometry.vertices[ face.c ];
  15578. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15579. },
  15580. // Get uniformly distributed random points in mesh
  15581. // - create array with cumulative sums of face areas
  15582. // - pick random number from 0 to total area
  15583. // - find corresponding place in area array by binary search
  15584. // - get random point in face
  15585. randomPointsInGeometry: function ( geometry, n ) {
  15586. var face, i,
  15587. faces = geometry.faces,
  15588. vertices = geometry.vertices,
  15589. il = faces.length,
  15590. totalArea = 0,
  15591. cumulativeAreas = [],
  15592. vA, vB, vC, vD;
  15593. // precompute face areas
  15594. for ( i = 0; i < il; i ++ ) {
  15595. face = faces[ i ];
  15596. vA = vertices[ face.a ];
  15597. vB = vertices[ face.b ];
  15598. vC = vertices[ face.c ];
  15599. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  15600. totalArea += face._area;
  15601. cumulativeAreas[ i ] = totalArea;
  15602. }
  15603. // binary search cumulative areas array
  15604. function binarySearchIndices( value ) {
  15605. function binarySearch( start, end ) {
  15606. // return closest larger index
  15607. // if exact number is not found
  15608. if ( end < start )
  15609. return start;
  15610. var mid = start + Math.floor( ( end - start ) / 2 );
  15611. if ( cumulativeAreas[ mid ] > value ) {
  15612. return binarySearch( start, mid - 1 );
  15613. } else if ( cumulativeAreas[ mid ] < value ) {
  15614. return binarySearch( mid + 1, end );
  15615. } else {
  15616. return mid;
  15617. }
  15618. }
  15619. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  15620. return result;
  15621. }
  15622. // pick random face weighted by face area
  15623. var r, index,
  15624. result = [];
  15625. var stats = {};
  15626. for ( i = 0; i < n; i ++ ) {
  15627. r = THREE.Math.random16() * totalArea;
  15628. index = binarySearchIndices( r );
  15629. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  15630. if ( ! stats[ index ] ) {
  15631. stats[ index ] = 1;
  15632. } else {
  15633. stats[ index ] += 1;
  15634. }
  15635. }
  15636. return result;
  15637. },
  15638. // Get triangle area (half of parallelogram)
  15639. // http://mathworld.wolfram.com/TriangleArea.html
  15640. triangleArea: function () {
  15641. var vector1 = new THREE.Vector3();
  15642. var vector2 = new THREE.Vector3();
  15643. return function ( vectorA, vectorB, vectorC ) {
  15644. vector1.subVectors( vectorB, vectorA );
  15645. vector2.subVectors( vectorC, vectorA );
  15646. vector1.cross( vector2 );
  15647. return 0.5 * vector1.length();
  15648. };
  15649. }(),
  15650. // Center geometry so that 0,0,0 is in center of bounding box
  15651. center: function ( geometry ) {
  15652. geometry.computeBoundingBox();
  15653. var bb = geometry.boundingBox;
  15654. var offset = new THREE.Vector3();
  15655. offset.addVectors( bb.min, bb.max );
  15656. offset.multiplyScalar( -0.5 );
  15657. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  15658. geometry.computeBoundingBox();
  15659. return offset;
  15660. },
  15661. triangulateQuads: function ( geometry ) {
  15662. var i, il, j, jl;
  15663. var faces = [];
  15664. var faceVertexUvs = [];
  15665. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15666. faceVertexUvs[ i ] = [];
  15667. }
  15668. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15669. var face = geometry.faces[ i ];
  15670. faces.push( face );
  15671. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15672. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15673. }
  15674. }
  15675. geometry.faces = faces;
  15676. geometry.faceVertexUvs = faceVertexUvs;
  15677. geometry.computeCentroids();
  15678. geometry.computeFaceNormals();
  15679. geometry.computeVertexNormals();
  15680. if ( geometry.hasTangents ) geometry.computeTangents();
  15681. },
  15682. setMaterialIndex: function ( geometry, index, startFace, endFace ){
  15683. var faces = geometry.faces;
  15684. var start = startFace || 0;
  15685. var end = endFace || faces.length - 1;
  15686. for ( var i = start; i <= end; i ++ ) {
  15687. faces[i].materialIndex = index;
  15688. }
  15689. }
  15690. };
  15691. /**
  15692. * @author alteredq / http://alteredqualia.com/
  15693. * @author mrdoob / http://mrdoob.com/
  15694. */
  15695. THREE.ImageUtils = {
  15696. crossOrigin: 'anonymous',
  15697. loadTexture: function ( url, mapping, onLoad, onError ) {
  15698. var image = new Image();
  15699. var texture = new THREE.Texture( image, mapping );
  15700. var loader = new THREE.ImageLoader();
  15701. loader.crossOrigin = this.crossOrigin;
  15702. loader.load( url, function ( image ) {
  15703. texture.image = image;
  15704. texture.needsUpdate = true;
  15705. if ( onLoad ) onLoad( texture );
  15706. } );
  15707. texture.sourceFile = url;
  15708. return texture;
  15709. },
  15710. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15711. var texture = new THREE.CompressedTexture();
  15712. texture.mapping = mapping;
  15713. var request = new XMLHttpRequest();
  15714. request.onload = function () {
  15715. var buffer = request.response;
  15716. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15717. texture.format = dds.format;
  15718. texture.mipmaps = dds.mipmaps;
  15719. texture.image.width = dds.width;
  15720. texture.image.height = dds.height;
  15721. // gl.generateMipmap fails for compressed textures
  15722. // mipmaps must be embedded in the DDS file
  15723. // or texture filters must not use mipmapping
  15724. texture.generateMipmaps = false;
  15725. texture.needsUpdate = true;
  15726. if ( onLoad ) onLoad( texture );
  15727. }
  15728. request.onerror = onError;
  15729. request.open( 'GET', url, true );
  15730. request.responseType = "arraybuffer";
  15731. request.send( null );
  15732. return texture;
  15733. },
  15734. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15735. var images = [];
  15736. images.loadCount = 0;
  15737. var texture = new THREE.Texture();
  15738. texture.image = images;
  15739. if ( mapping !== undefined ) texture.mapping = mapping;
  15740. // no flipping needed for cube textures
  15741. texture.flipY = false;
  15742. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15743. var cubeImage = new Image();
  15744. images[ i ] = cubeImage;
  15745. cubeImage.onload = function () {
  15746. images.loadCount += 1;
  15747. if ( images.loadCount === 6 ) {
  15748. texture.needsUpdate = true;
  15749. if ( onLoad ) onLoad( texture );
  15750. }
  15751. };
  15752. cubeImage.onerror = onError;
  15753. cubeImage.crossOrigin = this.crossOrigin;
  15754. cubeImage.src = array[ i ];
  15755. }
  15756. return texture;
  15757. },
  15758. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15759. var images = [];
  15760. images.loadCount = 0;
  15761. var texture = new THREE.CompressedTexture();
  15762. texture.image = images;
  15763. if ( mapping !== undefined ) texture.mapping = mapping;
  15764. // no flipping for cube textures
  15765. // (also flipping doesn't work for compressed textures )
  15766. texture.flipY = false;
  15767. // can't generate mipmaps for compressed textures
  15768. // mips must be embedded in DDS files
  15769. texture.generateMipmaps = false;
  15770. var generateCubeFaceCallback = function ( rq, img ) {
  15771. return function () {
  15772. var buffer = rq.response;
  15773. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15774. img.format = dds.format;
  15775. img.mipmaps = dds.mipmaps;
  15776. img.width = dds.width;
  15777. img.height = dds.height;
  15778. images.loadCount += 1;
  15779. if ( images.loadCount === 6 ) {
  15780. texture.format = dds.format;
  15781. texture.needsUpdate = true;
  15782. if ( onLoad ) onLoad( texture );
  15783. }
  15784. }
  15785. }
  15786. // compressed cubemap textures as 6 separate DDS files
  15787. if ( array instanceof Array ) {
  15788. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15789. var cubeImage = {};
  15790. images[ i ] = cubeImage;
  15791. var request = new XMLHttpRequest();
  15792. request.onload = generateCubeFaceCallback( request, cubeImage );
  15793. request.onerror = onError;
  15794. var url = array[ i ];
  15795. request.open( 'GET', url, true );
  15796. request.responseType = "arraybuffer";
  15797. request.send( null );
  15798. }
  15799. // compressed cubemap texture stored in a single DDS file
  15800. } else {
  15801. var url = array;
  15802. var request = new XMLHttpRequest();
  15803. request.onload = function( ) {
  15804. var buffer = request.response;
  15805. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15806. if ( dds.isCubemap ) {
  15807. var faces = dds.mipmaps.length / dds.mipmapCount;
  15808. for ( var f = 0; f < faces; f ++ ) {
  15809. images[ f ] = { mipmaps : [] };
  15810. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15811. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15812. images[ f ].format = dds.format;
  15813. images[ f ].width = dds.width;
  15814. images[ f ].height = dds.height;
  15815. }
  15816. }
  15817. texture.format = dds.format;
  15818. texture.needsUpdate = true;
  15819. if ( onLoad ) onLoad( texture );
  15820. }
  15821. }
  15822. request.onerror = onError;
  15823. request.open( 'GET', url, true );
  15824. request.responseType = "arraybuffer";
  15825. request.send( null );
  15826. }
  15827. return texture;
  15828. },
  15829. parseDDS: function ( buffer, loadMipmaps ) {
  15830. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15831. // Adapted from @toji's DDS utils
  15832. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15833. // All values and structures referenced from:
  15834. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15835. var DDS_MAGIC = 0x20534444;
  15836. var DDSD_CAPS = 0x1,
  15837. DDSD_HEIGHT = 0x2,
  15838. DDSD_WIDTH = 0x4,
  15839. DDSD_PITCH = 0x8,
  15840. DDSD_PIXELFORMAT = 0x1000,
  15841. DDSD_MIPMAPCOUNT = 0x20000,
  15842. DDSD_LINEARSIZE = 0x80000,
  15843. DDSD_DEPTH = 0x800000;
  15844. var DDSCAPS_COMPLEX = 0x8,
  15845. DDSCAPS_MIPMAP = 0x400000,
  15846. DDSCAPS_TEXTURE = 0x1000;
  15847. var DDSCAPS2_CUBEMAP = 0x200,
  15848. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15849. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15850. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15851. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15852. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15853. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15854. DDSCAPS2_VOLUME = 0x200000;
  15855. var DDPF_ALPHAPIXELS = 0x1,
  15856. DDPF_ALPHA = 0x2,
  15857. DDPF_FOURCC = 0x4,
  15858. DDPF_RGB = 0x40,
  15859. DDPF_YUV = 0x200,
  15860. DDPF_LUMINANCE = 0x20000;
  15861. function fourCCToInt32( value ) {
  15862. return value.charCodeAt(0) +
  15863. (value.charCodeAt(1) << 8) +
  15864. (value.charCodeAt(2) << 16) +
  15865. (value.charCodeAt(3) << 24);
  15866. }
  15867. function int32ToFourCC( value ) {
  15868. return String.fromCharCode(
  15869. value & 0xff,
  15870. (value >> 8) & 0xff,
  15871. (value >> 16) & 0xff,
  15872. (value >> 24) & 0xff
  15873. );
  15874. }
  15875. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15876. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15877. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15878. var headerLengthInt = 31; // The header length in 32 bit ints
  15879. // Offsets into the header array
  15880. var off_magic = 0;
  15881. var off_size = 1;
  15882. var off_flags = 2;
  15883. var off_height = 3;
  15884. var off_width = 4;
  15885. var off_mipmapCount = 7;
  15886. var off_pfFlags = 20;
  15887. var off_pfFourCC = 21;
  15888. var off_caps = 27;
  15889. var off_caps2 = 28;
  15890. var off_caps3 = 29;
  15891. var off_caps4 = 30;
  15892. // Parse header
  15893. var header = new Int32Array( buffer, 0, headerLengthInt );
  15894. if ( header[ off_magic ] !== DDS_MAGIC ) {
  15895. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  15896. return dds;
  15897. }
  15898. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  15899. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  15900. return dds;
  15901. }
  15902. var blockBytes;
  15903. var fourCC = header[ off_pfFourCC ];
  15904. switch ( fourCC ) {
  15905. case FOURCC_DXT1:
  15906. blockBytes = 8;
  15907. dds.format = THREE.RGB_S3TC_DXT1_Format;
  15908. break;
  15909. case FOURCC_DXT3:
  15910. blockBytes = 16;
  15911. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  15912. break;
  15913. case FOURCC_DXT5:
  15914. blockBytes = 16;
  15915. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  15916. break;
  15917. default:
  15918. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  15919. return dds;
  15920. }
  15921. dds.mipmapCount = 1;
  15922. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  15923. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  15924. }
  15925. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  15926. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  15927. dds.width = header[ off_width ];
  15928. dds.height = header[ off_height ];
  15929. var dataOffset = header[ off_size ] + 4;
  15930. // Extract mipmaps buffers
  15931. var width = dds.width;
  15932. var height = dds.height;
  15933. var faces = dds.isCubemap ? 6 : 1;
  15934. for ( var face = 0; face < faces; face ++ ) {
  15935. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15936. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  15937. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  15938. var mipmap = { "data": byteArray, "width": width, "height": height };
  15939. dds.mipmaps.push( mipmap );
  15940. dataOffset += dataLength;
  15941. width = Math.max( width * 0.5, 1 );
  15942. height = Math.max( height * 0.5, 1 );
  15943. }
  15944. width = dds.width;
  15945. height = dds.height;
  15946. }
  15947. return dds;
  15948. },
  15949. getNormalMap: function ( image, depth ) {
  15950. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  15951. var cross = function ( a, b ) {
  15952. 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 ] ];
  15953. }
  15954. var subtract = function ( a, b ) {
  15955. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  15956. }
  15957. var normalize = function ( a ) {
  15958. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  15959. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  15960. }
  15961. depth = depth | 1;
  15962. var width = image.width;
  15963. var height = image.height;
  15964. var canvas = document.createElement( 'canvas' );
  15965. canvas.width = width;
  15966. canvas.height = height;
  15967. var context = canvas.getContext( '2d' );
  15968. context.drawImage( image, 0, 0 );
  15969. var data = context.getImageData( 0, 0, width, height ).data;
  15970. var imageData = context.createImageData( width, height );
  15971. var output = imageData.data;
  15972. for ( var x = 0; x < width; x ++ ) {
  15973. for ( var y = 0; y < height; y ++ ) {
  15974. var ly = y - 1 < 0 ? 0 : y - 1;
  15975. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  15976. var lx = x - 1 < 0 ? 0 : x - 1;
  15977. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  15978. var points = [];
  15979. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  15980. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  15981. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  15982. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  15983. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  15984. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  15985. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  15986. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  15987. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  15988. var normals = [];
  15989. var num_points = points.length;
  15990. for ( var i = 0; i < num_points; i ++ ) {
  15991. var v1 = points[ i ];
  15992. var v2 = points[ ( i + 1 ) % num_points ];
  15993. v1 = subtract( v1, origin );
  15994. v2 = subtract( v2, origin );
  15995. normals.push( normalize( cross( v1, v2 ) ) );
  15996. }
  15997. var normal = [ 0, 0, 0 ];
  15998. for ( var i = 0; i < normals.length; i ++ ) {
  15999. normal[ 0 ] += normals[ i ][ 0 ];
  16000. normal[ 1 ] += normals[ i ][ 1 ];
  16001. normal[ 2 ] += normals[ i ][ 2 ];
  16002. }
  16003. normal[ 0 ] /= normals.length;
  16004. normal[ 1 ] /= normals.length;
  16005. normal[ 2 ] /= normals.length;
  16006. var idx = ( y * width + x ) * 4;
  16007. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16008. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16009. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16010. output[ idx + 3 ] = 255;
  16011. }
  16012. }
  16013. context.putImageData( imageData, 0, 0 );
  16014. return canvas;
  16015. },
  16016. generateDataTexture: function ( width, height, color ) {
  16017. var size = width * height;
  16018. var data = new Uint8Array( 3 * size );
  16019. var r = Math.floor( color.r * 255 );
  16020. var g = Math.floor( color.g * 255 );
  16021. var b = Math.floor( color.b * 255 );
  16022. for ( var i = 0; i < size; i ++ ) {
  16023. data[ i * 3 ] = r;
  16024. data[ i * 3 + 1 ] = g;
  16025. data[ i * 3 + 2 ] = b;
  16026. }
  16027. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16028. texture.needsUpdate = true;
  16029. return texture;
  16030. }
  16031. };
  16032. /**
  16033. * @author alteredq / http://alteredqualia.com/
  16034. */
  16035. THREE.SceneUtils = {
  16036. createMultiMaterialObject: function ( geometry, materials ) {
  16037. var group = new THREE.Object3D();
  16038. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16039. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16040. }
  16041. return group;
  16042. },
  16043. detach : function ( child, parent, scene ) {
  16044. child.applyMatrix( parent.matrixWorld );
  16045. parent.remove( child );
  16046. scene.add( child );
  16047. },
  16048. attach: function ( child, scene, parent ) {
  16049. var matrixWorldInverse = new THREE.Matrix4();
  16050. matrixWorldInverse.getInverse( parent.matrixWorld );
  16051. child.applyMatrix( matrixWorldInverse );
  16052. scene.remove( child );
  16053. parent.add( child );
  16054. }
  16055. };
  16056. /**
  16057. * @author zz85 / http://www.lab4games.net/zz85/blog
  16058. * @author alteredq / http://alteredqualia.com/
  16059. *
  16060. * For Text operations in three.js (See TextGeometry)
  16061. *
  16062. * It uses techniques used in:
  16063. *
  16064. * typeface.js and canvastext
  16065. * For converting fonts and rendering with javascript
  16066. * http://typeface.neocracy.org
  16067. *
  16068. * Triangulation ported from AS3
  16069. * Simple Polygon Triangulation
  16070. * http://actionsnippet.com/?p=1462
  16071. *
  16072. * A Method to triangulate shapes with holes
  16073. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16074. *
  16075. */
  16076. THREE.FontUtils = {
  16077. faces : {},
  16078. // Just for now. face[weight][style]
  16079. face : "helvetiker",
  16080. weight: "normal",
  16081. style : "normal",
  16082. size : 150,
  16083. divisions : 10,
  16084. getFace : function() {
  16085. return this.faces[ this.face ][ this.weight ][ this.style ];
  16086. },
  16087. loadFace : function( data ) {
  16088. var family = data.familyName.toLowerCase();
  16089. var ThreeFont = this;
  16090. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16091. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16092. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16093. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16094. return data;
  16095. },
  16096. drawText : function( text ) {
  16097. var characterPts = [], allPts = [];
  16098. // RenderText
  16099. var i, p,
  16100. face = this.getFace(),
  16101. scale = this.size / face.resolution,
  16102. offset = 0,
  16103. chars = String( text ).split( '' ),
  16104. length = chars.length;
  16105. var fontPaths = [];
  16106. for ( i = 0; i < length; i ++ ) {
  16107. var path = new THREE.Path();
  16108. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16109. offset += ret.offset;
  16110. fontPaths.push( ret.path );
  16111. }
  16112. // get the width
  16113. var width = offset / 2;
  16114. //
  16115. // for ( p = 0; p < allPts.length; p++ ) {
  16116. //
  16117. // allPts[ p ].x -= width;
  16118. //
  16119. // }
  16120. //var extract = this.extractPoints( allPts, characterPts );
  16121. //extract.contour = allPts;
  16122. //extract.paths = fontPaths;
  16123. //extract.offset = width;
  16124. return { paths : fontPaths, offset : width };
  16125. },
  16126. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16127. var pts = [];
  16128. var i, i2, divisions,
  16129. outline, action, length,
  16130. scaleX, scaleY,
  16131. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16132. laste,
  16133. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16134. if ( !glyph ) return;
  16135. if ( glyph.o ) {
  16136. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16137. length = outline.length;
  16138. scaleX = scale;
  16139. scaleY = scale;
  16140. for ( i = 0; i < length; ) {
  16141. action = outline[ i ++ ];
  16142. //console.log( action );
  16143. switch( action ) {
  16144. case 'm':
  16145. // Move To
  16146. x = outline[ i++ ] * scaleX + offset;
  16147. y = outline[ i++ ] * scaleY;
  16148. path.moveTo( x, y );
  16149. break;
  16150. case 'l':
  16151. // Line To
  16152. x = outline[ i++ ] * scaleX + offset;
  16153. y = outline[ i++ ] * scaleY;
  16154. path.lineTo(x,y);
  16155. break;
  16156. case 'q':
  16157. // QuadraticCurveTo
  16158. cpx = outline[ i++ ] * scaleX + offset;
  16159. cpy = outline[ i++ ] * scaleY;
  16160. cpx1 = outline[ i++ ] * scaleX + offset;
  16161. cpy1 = outline[ i++ ] * scaleY;
  16162. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16163. laste = pts[ pts.length - 1 ];
  16164. if ( laste ) {
  16165. cpx0 = laste.x;
  16166. cpy0 = laste.y;
  16167. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16168. var t = i2 / divisions;
  16169. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16170. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16171. }
  16172. }
  16173. break;
  16174. case 'b':
  16175. // Cubic Bezier Curve
  16176. cpx = outline[ i++ ] * scaleX + offset;
  16177. cpy = outline[ i++ ] * scaleY;
  16178. cpx1 = outline[ i++ ] * scaleX + offset;
  16179. cpy1 = outline[ i++ ] * -scaleY;
  16180. cpx2 = outline[ i++ ] * scaleX + offset;
  16181. cpy2 = outline[ i++ ] * -scaleY;
  16182. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16183. laste = pts[ pts.length - 1 ];
  16184. if ( laste ) {
  16185. cpx0 = laste.x;
  16186. cpy0 = laste.y;
  16187. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16188. var t = i2 / divisions;
  16189. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16190. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16191. }
  16192. }
  16193. break;
  16194. }
  16195. }
  16196. }
  16197. return { offset: glyph.ha*scale, path:path};
  16198. }
  16199. };
  16200. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16201. // Parameters
  16202. parameters = parameters || {};
  16203. var size = parameters.size !== undefined ? parameters.size : 100;
  16204. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16205. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16206. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16207. var style = parameters.style !== undefined ? parameters.style : "normal";
  16208. THREE.FontUtils.size = size;
  16209. THREE.FontUtils.divisions = curveSegments;
  16210. THREE.FontUtils.face = font;
  16211. THREE.FontUtils.weight = weight;
  16212. THREE.FontUtils.style = style;
  16213. // Get a Font data json object
  16214. var data = THREE.FontUtils.drawText( text );
  16215. var paths = data.paths;
  16216. var shapes = [];
  16217. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16218. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16219. }
  16220. return shapes;
  16221. };
  16222. /**
  16223. * This code is a quick port of code written in C++ which was submitted to
  16224. * flipcode.com by John W. Ratcliff // July 22, 2000
  16225. * See original code and more information here:
  16226. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16227. *
  16228. * ported to actionscript by Zevan Rosser
  16229. * www.actionsnippet.com
  16230. *
  16231. * ported to javascript by Joshua Koo
  16232. * http://www.lab4games.net/zz85/blog
  16233. *
  16234. */
  16235. ( function( namespace ) {
  16236. var EPSILON = 0.0000000001;
  16237. // takes in an contour array and returns
  16238. var process = function( contour, indices ) {
  16239. var n = contour.length;
  16240. if ( n < 3 ) return null;
  16241. var result = [],
  16242. verts = [],
  16243. vertIndices = [];
  16244. /* we want a counter-clockwise polygon in verts */
  16245. var u, v, w;
  16246. if ( area( contour ) > 0.0 ) {
  16247. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16248. } else {
  16249. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16250. }
  16251. var nv = n;
  16252. /* remove nv - 2 vertices, creating 1 triangle every time */
  16253. var count = 2 * nv; /* error detection */
  16254. for( v = nv - 1; nv > 2; ) {
  16255. /* if we loop, it is probably a non-simple polygon */
  16256. if ( ( count-- ) <= 0 ) {
  16257. //** Triangulate: ERROR - probable bad polygon!
  16258. //throw ( "Warning, unable to triangulate polygon!" );
  16259. //return null;
  16260. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16261. console.log( "Warning, unable to triangulate polygon!" );
  16262. if ( indices ) return vertIndices;
  16263. return result;
  16264. }
  16265. /* three consecutive vertices in current polygon, <u,v,w> */
  16266. u = v; if ( nv <= u ) u = 0; /* previous */
  16267. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16268. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16269. if ( snip( contour, u, v, w, nv, verts ) ) {
  16270. var a, b, c, s, t;
  16271. /* true names of the vertices */
  16272. a = verts[ u ];
  16273. b = verts[ v ];
  16274. c = verts[ w ];
  16275. /* output Triangle */
  16276. result.push( [ contour[ a ],
  16277. contour[ b ],
  16278. contour[ c ] ] );
  16279. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16280. /* remove v from the remaining polygon */
  16281. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16282. verts[ s ] = verts[ t ];
  16283. }
  16284. nv--;
  16285. /* reset error detection counter */
  16286. count = 2 * nv;
  16287. }
  16288. }
  16289. if ( indices ) return vertIndices;
  16290. return result;
  16291. };
  16292. // calculate area of the contour polygon
  16293. var area = function ( contour ) {
  16294. var n = contour.length;
  16295. var a = 0.0;
  16296. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16297. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16298. }
  16299. return a * 0.5;
  16300. };
  16301. var snip = function ( contour, u, v, w, n, verts ) {
  16302. var p;
  16303. var ax, ay, bx, by;
  16304. var cx, cy, px, py;
  16305. ax = contour[ verts[ u ] ].x;
  16306. ay = contour[ verts[ u ] ].y;
  16307. bx = contour[ verts[ v ] ].x;
  16308. by = contour[ verts[ v ] ].y;
  16309. cx = contour[ verts[ w ] ].x;
  16310. cy = contour[ verts[ w ] ].y;
  16311. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16312. var aX, aY, bX, bY, cX, cY;
  16313. var apx, apy, bpx, bpy, cpx, cpy;
  16314. var cCROSSap, bCROSScp, aCROSSbp;
  16315. aX = cx - bx; aY = cy - by;
  16316. bX = ax - cx; bY = ay - cy;
  16317. cX = bx - ax; cY = by - ay;
  16318. for ( p = 0; p < n; p++ ) {
  16319. if( (p === u) || (p === v) || (p === w) ) continue;
  16320. px = contour[ verts[ p ] ].x
  16321. py = contour[ verts[ p ] ].y
  16322. apx = px - ax; apy = py - ay;
  16323. bpx = px - bx; bpy = py - by;
  16324. cpx = px - cx; cpy = py - cy;
  16325. // see if p is inside triangle abc
  16326. aCROSSbp = aX*bpy - aY*bpx;
  16327. cCROSSap = cX*apy - cY*apx;
  16328. bCROSScp = bX*cpy - bY*cpx;
  16329. if ( (aCROSSbp >= -EPSILON) && (bCROSScp >= -EPSILON) && (cCROSSap >= -EPSILON) ) return false;
  16330. }
  16331. return true;
  16332. };
  16333. namespace.Triangulate = process;
  16334. namespace.Triangulate.area = area;
  16335. return namespace;
  16336. })(THREE.FontUtils);
  16337. // To use the typeface.js face files, hook up the API
  16338. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16339. THREE.typeface_js = self._typeface_js;
  16340. /**
  16341. * @author zz85 / http://www.lab4games.net/zz85/blog
  16342. * Extensible curve object
  16343. *
  16344. * Some common of Curve methods
  16345. * .getPoint(t), getTangent(t)
  16346. * .getPointAt(u), getTagentAt(u)
  16347. * .getPoints(), .getSpacedPoints()
  16348. * .getLength()
  16349. * .updateArcLengths()
  16350. *
  16351. * This following classes subclasses THREE.Curve:
  16352. *
  16353. * -- 2d classes --
  16354. * THREE.LineCurve
  16355. * THREE.QuadraticBezierCurve
  16356. * THREE.CubicBezierCurve
  16357. * THREE.SplineCurve
  16358. * THREE.ArcCurve
  16359. * THREE.EllipseCurve
  16360. *
  16361. * -- 3d classes --
  16362. * THREE.LineCurve3
  16363. * THREE.QuadraticBezierCurve3
  16364. * THREE.CubicBezierCurve3
  16365. * THREE.SplineCurve3
  16366. * THREE.ClosedSplineCurve3
  16367. *
  16368. * A series of curves can be represented as a THREE.CurvePath
  16369. *
  16370. **/
  16371. /**************************************************************
  16372. * Abstract Curve base class
  16373. **************************************************************/
  16374. THREE.Curve = function () {
  16375. };
  16376. // Virtual base class method to overwrite and implement in subclasses
  16377. // - t [0 .. 1]
  16378. THREE.Curve.prototype.getPoint = function ( t ) {
  16379. console.log( "Warning, getPoint() not implemented!" );
  16380. return null;
  16381. };
  16382. // Get point at relative position in curve according to arc length
  16383. // - u [0 .. 1]
  16384. THREE.Curve.prototype.getPointAt = function ( u ) {
  16385. var t = this.getUtoTmapping( u );
  16386. return this.getPoint( t );
  16387. };
  16388. // Get sequence of points using getPoint( t )
  16389. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16390. if ( !divisions ) divisions = 5;
  16391. var d, pts = [];
  16392. for ( d = 0; d <= divisions; d ++ ) {
  16393. pts.push( this.getPoint( d / divisions ) );
  16394. }
  16395. return pts;
  16396. };
  16397. // Get sequence of points using getPointAt( u )
  16398. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16399. if ( !divisions ) divisions = 5;
  16400. var d, pts = [];
  16401. for ( d = 0; d <= divisions; d ++ ) {
  16402. pts.push( this.getPointAt( d / divisions ) );
  16403. }
  16404. return pts;
  16405. };
  16406. // Get total curve arc length
  16407. THREE.Curve.prototype.getLength = function () {
  16408. var lengths = this.getLengths();
  16409. return lengths[ lengths.length - 1 ];
  16410. };
  16411. // Get list of cumulative segment lengths
  16412. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16413. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16414. if ( this.cacheArcLengths
  16415. && ( this.cacheArcLengths.length == divisions + 1 )
  16416. && !this.needsUpdate) {
  16417. //console.log( "cached", this.cacheArcLengths );
  16418. return this.cacheArcLengths;
  16419. }
  16420. this.needsUpdate = false;
  16421. var cache = [];
  16422. var current, last = this.getPoint( 0 );
  16423. var p, sum = 0;
  16424. cache.push( 0 );
  16425. for ( p = 1; p <= divisions; p ++ ) {
  16426. current = this.getPoint ( p / divisions );
  16427. sum += current.distanceTo( last );
  16428. cache.push( sum );
  16429. last = current;
  16430. }
  16431. this.cacheArcLengths = cache;
  16432. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16433. };
  16434. THREE.Curve.prototype.updateArcLengths = function() {
  16435. this.needsUpdate = true;
  16436. this.getLengths();
  16437. };
  16438. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16439. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16440. var arcLengths = this.getLengths();
  16441. var i = 0, il = arcLengths.length;
  16442. var targetArcLength; // The targeted u distance value to get
  16443. if ( distance ) {
  16444. targetArcLength = distance;
  16445. } else {
  16446. targetArcLength = u * arcLengths[ il - 1 ];
  16447. }
  16448. //var time = Date.now();
  16449. // binary search for the index with largest value smaller than target u distance
  16450. var low = 0, high = il - 1, comparison;
  16451. while ( low <= high ) {
  16452. 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
  16453. comparison = arcLengths[ i ] - targetArcLength;
  16454. if ( comparison < 0 ) {
  16455. low = i + 1;
  16456. continue;
  16457. } else if ( comparison > 0 ) {
  16458. high = i - 1;
  16459. continue;
  16460. } else {
  16461. high = i;
  16462. break;
  16463. // DONE
  16464. }
  16465. }
  16466. i = high;
  16467. //console.log('b' , i, low, high, Date.now()- time);
  16468. if ( arcLengths[ i ] == targetArcLength ) {
  16469. var t = i / ( il - 1 );
  16470. return t;
  16471. }
  16472. // we could get finer grain at lengths, or use simple interpolatation between two points
  16473. var lengthBefore = arcLengths[ i ];
  16474. var lengthAfter = arcLengths[ i + 1 ];
  16475. var segmentLength = lengthAfter - lengthBefore;
  16476. // determine where we are between the 'before' and 'after' points
  16477. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16478. // add that fractional amount to t
  16479. var t = ( i + segmentFraction ) / ( il -1 );
  16480. return t;
  16481. };
  16482. // Returns a unit vector tangent at t
  16483. // In case any sub curve does not implement its tangent derivation,
  16484. // 2 points a small delta apart will be used to find its gradient
  16485. // which seems to give a reasonable approximation
  16486. THREE.Curve.prototype.getTangent = function( t ) {
  16487. var delta = 0.0001;
  16488. var t1 = t - delta;
  16489. var t2 = t + delta;
  16490. // Capping in case of danger
  16491. if ( t1 < 0 ) t1 = 0;
  16492. if ( t2 > 1 ) t2 = 1;
  16493. var pt1 = this.getPoint( t1 );
  16494. var pt2 = this.getPoint( t2 );
  16495. var vec = pt2.clone().sub(pt1);
  16496. return vec.normalize();
  16497. };
  16498. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16499. var t = this.getUtoTmapping( u );
  16500. return this.getTangent( t );
  16501. };
  16502. /**************************************************************
  16503. * Utils
  16504. **************************************************************/
  16505. THREE.Curve.Utils = {
  16506. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16507. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16508. },
  16509. // Puay Bing, thanks for helping with this derivative!
  16510. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16511. return -3 * p0 * (1 - t) * (1 - t) +
  16512. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16513. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16514. 3 * t * t * p3;
  16515. },
  16516. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16517. // To check if my formulas are correct
  16518. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16519. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16520. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16521. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16522. return h00 + h10 + h01 + h11;
  16523. },
  16524. // Catmull-Rom
  16525. interpolate: function( p0, p1, p2, p3, t ) {
  16526. var v0 = ( p2 - p0 ) * 0.5;
  16527. var v1 = ( p3 - p1 ) * 0.5;
  16528. var t2 = t * t;
  16529. var t3 = t * t2;
  16530. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16531. }
  16532. };
  16533. // TODO: Transformation for Curves?
  16534. /**************************************************************
  16535. * 3D Curves
  16536. **************************************************************/
  16537. // A Factory method for creating new curve subclasses
  16538. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16539. constructor.prototype = Object.create( THREE.Curve.prototype );
  16540. constructor.prototype.getPoint = getPointFunc;
  16541. return constructor;
  16542. };
  16543. /**
  16544. * @author zz85 / http://www.lab4games.net/zz85/blog
  16545. *
  16546. **/
  16547. /**************************************************************
  16548. * Curved Path - a curve path is simply a array of connected
  16549. * curves, but retains the api of a curve
  16550. **************************************************************/
  16551. THREE.CurvePath = function () {
  16552. this.curves = [];
  16553. this.bends = [];
  16554. this.autoClose = false; // Automatically closes the path
  16555. };
  16556. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16557. THREE.CurvePath.prototype.add = function ( curve ) {
  16558. this.curves.push( curve );
  16559. };
  16560. THREE.CurvePath.prototype.checkConnection = function() {
  16561. // TODO
  16562. // If the ending of curve is not connected to the starting
  16563. // or the next curve, then, this is not a real path
  16564. };
  16565. THREE.CurvePath.prototype.closePath = function() {
  16566. // TODO Test
  16567. // and verify for vector3 (needs to implement equals)
  16568. // Add a line curve if start and end of lines are not connected
  16569. var startPoint = this.curves[0].getPoint(0);
  16570. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16571. if (!startPoint.equals(endPoint)) {
  16572. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16573. }
  16574. };
  16575. // To get accurate point with reference to
  16576. // entire path distance at time t,
  16577. // following has to be done:
  16578. // 1. Length of each sub path have to be known
  16579. // 2. Locate and identify type of curve
  16580. // 3. Get t for the curve
  16581. // 4. Return curve.getPointAt(t')
  16582. THREE.CurvePath.prototype.getPoint = function( t ) {
  16583. var d = t * this.getLength();
  16584. var curveLengths = this.getCurveLengths();
  16585. var i = 0, diff, curve;
  16586. // To think about boundaries points.
  16587. while ( i < curveLengths.length ) {
  16588. if ( curveLengths[ i ] >= d ) {
  16589. diff = curveLengths[ i ] - d;
  16590. curve = this.curves[ i ];
  16591. var u = 1 - diff / curve.getLength();
  16592. return curve.getPointAt( u );
  16593. break;
  16594. }
  16595. i ++;
  16596. }
  16597. return null;
  16598. // loop where sum != 0, sum > d , sum+1 <d
  16599. };
  16600. /*
  16601. THREE.CurvePath.prototype.getTangent = function( t ) {
  16602. };*/
  16603. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16604. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16605. // getPoint() depends on getLength
  16606. THREE.CurvePath.prototype.getLength = function() {
  16607. var lens = this.getCurveLengths();
  16608. return lens[ lens.length - 1 ];
  16609. };
  16610. // Compute lengths and cache them
  16611. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16612. THREE.CurvePath.prototype.getCurveLengths = function() {
  16613. // We use cache values if curves and cache array are same length
  16614. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16615. return this.cacheLengths;
  16616. };
  16617. // Get length of subsurve
  16618. // Push sums into cached array
  16619. var lengths = [], sums = 0;
  16620. var i, il = this.curves.length;
  16621. for ( i = 0; i < il; i ++ ) {
  16622. sums += this.curves[ i ].getLength();
  16623. lengths.push( sums );
  16624. }
  16625. this.cacheLengths = lengths;
  16626. return lengths;
  16627. };
  16628. // Returns min and max coordinates, as well as centroid
  16629. THREE.CurvePath.prototype.getBoundingBox = function () {
  16630. var points = this.getPoints();
  16631. var maxX, maxY, maxZ;
  16632. var minX, minY, minZ;
  16633. maxX = maxY = Number.NEGATIVE_INFINITY;
  16634. minX = minY = Number.POSITIVE_INFINITY;
  16635. var p, i, il, sum;
  16636. var v3 = points[0] instanceof THREE.Vector3;
  16637. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16638. for ( i = 0, il = points.length; i < il; i ++ ) {
  16639. p = points[ i ];
  16640. if ( p.x > maxX ) maxX = p.x;
  16641. else if ( p.x < minX ) minX = p.x;
  16642. if ( p.y > maxY ) maxY = p.y;
  16643. else if ( p.y < minY ) minY = p.y;
  16644. if ( v3 ) {
  16645. if ( p.z > maxZ ) maxZ = p.z;
  16646. else if ( p.z < minZ ) minZ = p.z;
  16647. }
  16648. sum.add( p );
  16649. }
  16650. var ret = {
  16651. minX: minX,
  16652. minY: minY,
  16653. maxX: maxX,
  16654. maxY: maxY,
  16655. centroid: sum.divideScalar( il )
  16656. };
  16657. if ( v3 ) {
  16658. ret.maxZ = maxZ;
  16659. ret.minZ = minZ;
  16660. }
  16661. return ret;
  16662. };
  16663. /**************************************************************
  16664. * Create Geometries Helpers
  16665. **************************************************************/
  16666. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16667. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16668. var pts = this.getPoints( divisions, true );
  16669. return this.createGeometry( pts );
  16670. };
  16671. // Generate geometry from equidistance sampling along the path
  16672. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16673. var pts = this.getSpacedPoints( divisions, true );
  16674. return this.createGeometry( pts );
  16675. };
  16676. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16677. var geometry = new THREE.Geometry();
  16678. for ( var i = 0; i < points.length; i ++ ) {
  16679. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16680. }
  16681. return geometry;
  16682. };
  16683. /**************************************************************
  16684. * Bend / Wrap Helper Methods
  16685. **************************************************************/
  16686. // Wrap path / Bend modifiers?
  16687. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16688. this.bends.push( bendpath );
  16689. };
  16690. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16691. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16692. var i, il;
  16693. if ( !bends ) {
  16694. bends = this.bends;
  16695. }
  16696. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16697. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16698. }
  16699. return oldPts;
  16700. };
  16701. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16702. var oldPts = this.getSpacedPoints( segments );
  16703. var i, il;
  16704. if ( !bends ) {
  16705. bends = this.bends;
  16706. }
  16707. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16708. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16709. }
  16710. return oldPts;
  16711. };
  16712. // This returns getPoints() bend/wrapped around the contour of a path.
  16713. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16714. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16715. var bounds = this.getBoundingBox();
  16716. var i, il, p, oldX, oldY, xNorm;
  16717. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16718. p = oldPts[ i ];
  16719. oldX = p.x;
  16720. oldY = p.y;
  16721. xNorm = oldX / bounds.maxX;
  16722. // If using actual distance, for length > path, requires line extrusions
  16723. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16724. xNorm = path.getUtoTmapping( xNorm, oldX );
  16725. // check for out of bounds?
  16726. var pathPt = path.getPoint( xNorm );
  16727. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  16728. p.x = pathPt.x + normal.x;
  16729. p.y = pathPt.y + normal.y;
  16730. }
  16731. return oldPts;
  16732. };
  16733. /**
  16734. * @author alteredq / http://alteredqualia.com/
  16735. */
  16736. THREE.Gyroscope = function () {
  16737. THREE.Object3D.call( this );
  16738. };
  16739. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16740. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16741. this.matrixAutoUpdate && this.updateMatrix();
  16742. // update matrixWorld
  16743. if ( this.matrixWorldNeedsUpdate || force ) {
  16744. if ( this.parent ) {
  16745. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16746. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  16747. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  16748. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  16749. } else {
  16750. this.matrixWorld.copy( this.matrix );
  16751. }
  16752. this.matrixWorldNeedsUpdate = false;
  16753. force = true;
  16754. }
  16755. // update children
  16756. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16757. this.children[ i ].updateMatrixWorld( force );
  16758. }
  16759. };
  16760. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16761. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16762. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  16763. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  16764. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16765. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16766. /**
  16767. * @author zz85 / http://www.lab4games.net/zz85/blog
  16768. * Creates free form 2d path using series of points, lines or curves.
  16769. *
  16770. **/
  16771. THREE.Path = function ( points ) {
  16772. THREE.CurvePath.call(this);
  16773. this.actions = [];
  16774. if ( points ) {
  16775. this.fromPoints( points );
  16776. }
  16777. };
  16778. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16779. THREE.PathActions = {
  16780. MOVE_TO: 'moveTo',
  16781. LINE_TO: 'lineTo',
  16782. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16783. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16784. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16785. ARC: 'arc', // Circle
  16786. ELLIPSE: 'ellipse'
  16787. };
  16788. // TODO Clean up PATH API
  16789. // Create path using straight lines to connect all points
  16790. // - vectors: array of Vector2
  16791. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16792. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16793. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16794. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16795. };
  16796. };
  16797. // startPath() endPath()?
  16798. THREE.Path.prototype.moveTo = function ( x, y ) {
  16799. var args = Array.prototype.slice.call( arguments );
  16800. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16801. };
  16802. THREE.Path.prototype.lineTo = function ( x, y ) {
  16803. var args = Array.prototype.slice.call( arguments );
  16804. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16805. var x0 = lastargs[ lastargs.length - 2 ];
  16806. var y0 = lastargs[ lastargs.length - 1 ];
  16807. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16808. this.curves.push( curve );
  16809. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16810. };
  16811. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16812. var args = Array.prototype.slice.call( arguments );
  16813. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16814. var x0 = lastargs[ lastargs.length - 2 ];
  16815. var y0 = lastargs[ lastargs.length - 1 ];
  16816. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16817. new THREE.Vector2( aCPx, aCPy ),
  16818. new THREE.Vector2( aX, aY ) );
  16819. this.curves.push( curve );
  16820. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16821. };
  16822. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16823. aCP2x, aCP2y,
  16824. aX, aY ) {
  16825. var args = Array.prototype.slice.call( arguments );
  16826. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16827. var x0 = lastargs[ lastargs.length - 2 ];
  16828. var y0 = lastargs[ lastargs.length - 1 ];
  16829. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16830. new THREE.Vector2( aCP1x, aCP1y ),
  16831. new THREE.Vector2( aCP2x, aCP2y ),
  16832. new THREE.Vector2( aX, aY ) );
  16833. this.curves.push( curve );
  16834. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16835. };
  16836. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16837. var args = Array.prototype.slice.call( arguments );
  16838. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16839. var x0 = lastargs[ lastargs.length - 2 ];
  16840. var y0 = lastargs[ lastargs.length - 1 ];
  16841. //---
  16842. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16843. Array.prototype.push.apply( npts, pts );
  16844. var curve = new THREE.SplineCurve( npts );
  16845. this.curves.push( curve );
  16846. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16847. };
  16848. // FUTURE: Change the API or follow canvas API?
  16849. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16850. aStartAngle, aEndAngle, aClockwise ) {
  16851. var lastargs = this.actions[ this.actions.length - 1].args;
  16852. var x0 = lastargs[ lastargs.length - 2 ];
  16853. var y0 = lastargs[ lastargs.length - 1 ];
  16854. this.absarc(aX + x0, aY + y0, aRadius,
  16855. aStartAngle, aEndAngle, aClockwise );
  16856. };
  16857. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16858. aStartAngle, aEndAngle, aClockwise ) {
  16859. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16860. };
  16861. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16862. aStartAngle, aEndAngle, aClockwise ) {
  16863. var lastargs = this.actions[ this.actions.length - 1].args;
  16864. var x0 = lastargs[ lastargs.length - 2 ];
  16865. var y0 = lastargs[ lastargs.length - 1 ];
  16866. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16867. aStartAngle, aEndAngle, aClockwise );
  16868. };
  16869. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16870. aStartAngle, aEndAngle, aClockwise ) {
  16871. var args = Array.prototype.slice.call( arguments );
  16872. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16873. aStartAngle, aEndAngle, aClockwise );
  16874. this.curves.push( curve );
  16875. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  16876. args.push(lastPoint.x);
  16877. args.push(lastPoint.y);
  16878. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16879. };
  16880. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16881. if ( ! divisions ) divisions = 40;
  16882. var points = [];
  16883. for ( var i = 0; i < divisions; i ++ ) {
  16884. points.push( this.getPoint( i / divisions ) );
  16885. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16886. }
  16887. // if ( closedPath ) {
  16888. //
  16889. // points.push( points[ 0 ] );
  16890. //
  16891. // }
  16892. return points;
  16893. };
  16894. /* Return an array of vectors based on contour of the path */
  16895. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16896. if (this.useSpacedPoints) {
  16897. console.log('tata');
  16898. return this.getSpacedPoints( divisions, closedPath );
  16899. }
  16900. divisions = divisions || 12;
  16901. var points = [];
  16902. var i, il, item, action, args;
  16903. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16904. laste, j,
  16905. t, tx, ty;
  16906. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16907. item = this.actions[ i ];
  16908. action = item.action;
  16909. args = item.args;
  16910. switch( action ) {
  16911. case THREE.PathActions.MOVE_TO:
  16912. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16913. break;
  16914. case THREE.PathActions.LINE_TO:
  16915. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16916. break;
  16917. case THREE.PathActions.QUADRATIC_CURVE_TO:
  16918. cpx = args[ 2 ];
  16919. cpy = args[ 3 ];
  16920. cpx1 = args[ 0 ];
  16921. cpy1 = args[ 1 ];
  16922. if ( points.length > 0 ) {
  16923. laste = points[ points.length - 1 ];
  16924. cpx0 = laste.x;
  16925. cpy0 = laste.y;
  16926. } else {
  16927. laste = this.actions[ i - 1 ].args;
  16928. cpx0 = laste[ laste.length - 2 ];
  16929. cpy0 = laste[ laste.length - 1 ];
  16930. }
  16931. for ( j = 1; j <= divisions; j ++ ) {
  16932. t = j / divisions;
  16933. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16934. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16935. points.push( new THREE.Vector2( tx, ty ) );
  16936. }
  16937. break;
  16938. case THREE.PathActions.BEZIER_CURVE_TO:
  16939. cpx = args[ 4 ];
  16940. cpy = args[ 5 ];
  16941. cpx1 = args[ 0 ];
  16942. cpy1 = args[ 1 ];
  16943. cpx2 = args[ 2 ];
  16944. cpy2 = args[ 3 ];
  16945. if ( points.length > 0 ) {
  16946. laste = points[ points.length - 1 ];
  16947. cpx0 = laste.x;
  16948. cpy0 = laste.y;
  16949. } else {
  16950. laste = this.actions[ i - 1 ].args;
  16951. cpx0 = laste[ laste.length - 2 ];
  16952. cpy0 = laste[ laste.length - 1 ];
  16953. }
  16954. for ( j = 1; j <= divisions; j ++ ) {
  16955. t = j / divisions;
  16956. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16957. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16958. points.push( new THREE.Vector2( tx, ty ) );
  16959. }
  16960. break;
  16961. case THREE.PathActions.CSPLINE_THRU:
  16962. laste = this.actions[ i - 1 ].args;
  16963. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  16964. var spts = [ last ];
  16965. var n = divisions * args[ 0 ].length;
  16966. spts = spts.concat( args[ 0 ] );
  16967. var spline = new THREE.SplineCurve( spts );
  16968. for ( j = 1; j <= n; j ++ ) {
  16969. points.push( spline.getPointAt( j / n ) ) ;
  16970. }
  16971. break;
  16972. case THREE.PathActions.ARC:
  16973. var aX = args[ 0 ], aY = args[ 1 ],
  16974. aRadius = args[ 2 ],
  16975. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  16976. aClockwise = !!args[ 5 ];
  16977. var deltaAngle = aEndAngle - aStartAngle;
  16978. var angle;
  16979. var tdivisions = divisions * 2;
  16980. for ( j = 1; j <= tdivisions; j ++ ) {
  16981. t = j / tdivisions;
  16982. if ( ! aClockwise ) {
  16983. t = 1 - t;
  16984. }
  16985. angle = aStartAngle + t * deltaAngle;
  16986. tx = aX + aRadius * Math.cos( angle );
  16987. ty = aY + aRadius * Math.sin( angle );
  16988. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16989. points.push( new THREE.Vector2( tx, ty ) );
  16990. }
  16991. //console.log(points);
  16992. break;
  16993. case THREE.PathActions.ELLIPSE:
  16994. var aX = args[ 0 ], aY = args[ 1 ],
  16995. xRadius = args[ 2 ],
  16996. yRadius = args[ 3 ],
  16997. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  16998. aClockwise = !!args[ 6 ];
  16999. var deltaAngle = aEndAngle - aStartAngle;
  17000. var angle;
  17001. var tdivisions = divisions * 2;
  17002. for ( j = 1; j <= tdivisions; j ++ ) {
  17003. t = j / tdivisions;
  17004. if ( ! aClockwise ) {
  17005. t = 1 - t;
  17006. }
  17007. angle = aStartAngle + t * deltaAngle;
  17008. tx = aX + xRadius * Math.cos( angle );
  17009. ty = aY + yRadius * Math.sin( angle );
  17010. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17011. points.push( new THREE.Vector2( tx, ty ) );
  17012. }
  17013. //console.log(points);
  17014. break;
  17015. } // end switch
  17016. }
  17017. // Normalize to remove the closing point by default.
  17018. var lastPoint = points[ points.length - 1];
  17019. var EPSILON = 0.0000000001;
  17020. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17021. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17022. points.splice( points.length - 1, 1);
  17023. if ( closedPath ) {
  17024. points.push( points[ 0 ] );
  17025. }
  17026. return points;
  17027. };
  17028. // Breaks path into shapes
  17029. THREE.Path.prototype.toShapes = function( isCCW ) {
  17030. var i, il, item, action, args;
  17031. var subPaths = [], lastPath = new THREE.Path();
  17032. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17033. item = this.actions[ i ];
  17034. args = item.args;
  17035. action = item.action;
  17036. if ( action == THREE.PathActions.MOVE_TO ) {
  17037. if ( lastPath.actions.length != 0 ) {
  17038. subPaths.push( lastPath );
  17039. lastPath = new THREE.Path();
  17040. }
  17041. }
  17042. lastPath[ action ].apply( lastPath, args );
  17043. }
  17044. if ( lastPath.actions.length != 0 ) {
  17045. subPaths.push( lastPath );
  17046. }
  17047. // console.log(subPaths);
  17048. if ( subPaths.length == 0 ) return [];
  17049. var solid, tmpPath, tmpShape, shapes = [];
  17050. if ( subPaths.length == 1) {
  17051. tmpPath = subPaths[0];
  17052. tmpShape = new THREE.Shape();
  17053. tmpShape.actions = tmpPath.actions;
  17054. tmpShape.curves = tmpPath.curves;
  17055. shapes.push( tmpShape );
  17056. return shapes;
  17057. }
  17058. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17059. holesFirst = isCCW ? !holesFirst : holesFirst;
  17060. // console.log("Holes first", holesFirst);
  17061. if ( holesFirst ) {
  17062. tmpShape = new THREE.Shape();
  17063. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17064. tmpPath = subPaths[ i ];
  17065. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17066. solid = isCCW ? !solid : solid;
  17067. if ( solid ) {
  17068. tmpShape.actions = tmpPath.actions;
  17069. tmpShape.curves = tmpPath.curves;
  17070. shapes.push( tmpShape );
  17071. tmpShape = new THREE.Shape();
  17072. //console.log('cw', i);
  17073. } else {
  17074. tmpShape.holes.push( tmpPath );
  17075. //console.log('ccw', i);
  17076. }
  17077. }
  17078. } else {
  17079. // Shapes first
  17080. tmpShape = undefined;
  17081. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17082. tmpPath = subPaths[ i ];
  17083. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17084. solid = isCCW ? !solid : solid;
  17085. if ( solid ) {
  17086. if ( tmpShape ) shapes.push( tmpShape );
  17087. tmpShape = new THREE.Shape();
  17088. tmpShape.actions = tmpPath.actions;
  17089. tmpShape.curves = tmpPath.curves;
  17090. } else {
  17091. tmpShape.holes.push( tmpPath );
  17092. }
  17093. }
  17094. shapes.push( tmpShape );
  17095. }
  17096. //console.log("shape", shapes);
  17097. return shapes;
  17098. };
  17099. /**
  17100. * @author zz85 / http://www.lab4games.net/zz85/blog
  17101. * Defines a 2d shape plane using paths.
  17102. **/
  17103. // STEP 1 Create a path.
  17104. // STEP 2 Turn path into shape.
  17105. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17106. // STEP 3a - Extract points from each shape, turn to vertices
  17107. // STEP 3b - Triangulate each shape, add faces.
  17108. THREE.Shape = function () {
  17109. THREE.Path.apply( this, arguments );
  17110. this.holes = [];
  17111. };
  17112. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17113. // Convenience method to return ExtrudeGeometry
  17114. THREE.Shape.prototype.extrude = function ( options ) {
  17115. var extruded = new THREE.ExtrudeGeometry( this, options );
  17116. return extruded;
  17117. };
  17118. // Convenience method to return ShapeGeometry
  17119. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17120. var geometry = new THREE.ShapeGeometry( this, options );
  17121. return geometry;
  17122. };
  17123. // Get points of holes
  17124. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17125. var i, il = this.holes.length, holesPts = [];
  17126. for ( i = 0; i < il; i ++ ) {
  17127. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17128. }
  17129. return holesPts;
  17130. };
  17131. // Get points of holes (spaced by regular distance)
  17132. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17133. var i, il = this.holes.length, holesPts = [];
  17134. for ( i = 0; i < il; i ++ ) {
  17135. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17136. }
  17137. return holesPts;
  17138. };
  17139. // Get points of shape and holes (keypoints based on segments parameter)
  17140. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17141. return {
  17142. shape: this.getTransformedPoints( divisions ),
  17143. holes: this.getPointsHoles( divisions )
  17144. };
  17145. };
  17146. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17147. if (this.useSpacedPoints) {
  17148. return this.extractAllSpacedPoints(divisions);
  17149. }
  17150. return this.extractAllPoints(divisions);
  17151. };
  17152. //
  17153. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17154. //
  17155. // return {
  17156. //
  17157. // shape: this.transform( bend, divisions ),
  17158. // holes: this.getPointsHoles( divisions, bend )
  17159. //
  17160. // };
  17161. //
  17162. // };
  17163. // Get points of shape and holes (spaced by regular distance)
  17164. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17165. return {
  17166. shape: this.getTransformedSpacedPoints( divisions ),
  17167. holes: this.getSpacedPointsHoles( divisions )
  17168. };
  17169. };
  17170. /**************************************************************
  17171. * Utils
  17172. **************************************************************/
  17173. THREE.Shape.Utils = {
  17174. /*
  17175. contour - array of vector2 for contour
  17176. holes - array of array of vector2
  17177. */
  17178. removeHoles: function ( contour, holes ) {
  17179. var shape = contour.concat(); // work on this shape
  17180. var allpoints = shape.concat();
  17181. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17182. var prevShapeVert, nextShapeVert,
  17183. prevHoleVert, nextHoleVert,
  17184. holeIndex, shapeIndex,
  17185. shapeId, shapeGroup,
  17186. h, h2,
  17187. hole, shortest, d,
  17188. p, pts1, pts2,
  17189. tmpShape1, tmpShape2,
  17190. tmpHole1, tmpHole2,
  17191. verts = [];
  17192. for ( h = 0; h < holes.length; h ++ ) {
  17193. hole = holes[ h ];
  17194. /*
  17195. shapeholes[ h ].concat(); // preserves original
  17196. holes.push( hole );
  17197. */
  17198. Array.prototype.push.apply( allpoints, hole );
  17199. shortest = Number.POSITIVE_INFINITY;
  17200. // Find the shortest pair of pts between shape and hole
  17201. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17202. // Using distanceToSquared() intead of distanceTo() should speed a little
  17203. // since running square roots operations are reduced.
  17204. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17205. pts1 = hole[ h2 ];
  17206. var dist = [];
  17207. for ( p = 0; p < shape.length; p++ ) {
  17208. pts2 = shape[ p ];
  17209. d = pts1.distanceToSquared( pts2 );
  17210. dist.push( d );
  17211. if ( d < shortest ) {
  17212. shortest = d;
  17213. holeIndex = h2;
  17214. shapeIndex = p;
  17215. }
  17216. }
  17217. }
  17218. //console.log("shortest", shortest, dist);
  17219. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17220. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17221. var areaapts = [
  17222. hole[ holeIndex ],
  17223. shape[ shapeIndex ],
  17224. shape[ prevShapeVert ]
  17225. ];
  17226. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17227. var areabpts = [
  17228. hole[ holeIndex ],
  17229. hole[ prevHoleVert ],
  17230. shape[ shapeIndex ]
  17231. ];
  17232. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17233. var shapeOffset = 1;
  17234. var holeOffset = -1;
  17235. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17236. shapeIndex += shapeOffset;
  17237. holeIndex += holeOffset;
  17238. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17239. shapeIndex %= shape.length;
  17240. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17241. holeIndex %= hole.length;
  17242. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17243. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17244. areaapts = [
  17245. hole[ holeIndex ],
  17246. shape[ shapeIndex ],
  17247. shape[ prevShapeVert ]
  17248. ];
  17249. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17250. areabpts = [
  17251. hole[ holeIndex ],
  17252. hole[ prevHoleVert ],
  17253. shape[ shapeIndex ]
  17254. ];
  17255. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17256. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17257. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17258. // In case areas are not correct.
  17259. //console.log("USE THIS");
  17260. shapeIndex = oldShapeIndex;
  17261. holeIndex = oldHoleIndex ;
  17262. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17263. shapeIndex %= shape.length;
  17264. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17265. holeIndex %= hole.length;
  17266. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17267. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17268. } else {
  17269. //console.log("USE THAT ")
  17270. }
  17271. tmpShape1 = shape.slice( 0, shapeIndex );
  17272. tmpShape2 = shape.slice( shapeIndex );
  17273. tmpHole1 = hole.slice( holeIndex );
  17274. tmpHole2 = hole.slice( 0, holeIndex );
  17275. // Should check orders here again?
  17276. var trianglea = [
  17277. hole[ holeIndex ],
  17278. shape[ shapeIndex ],
  17279. shape[ prevShapeVert ]
  17280. ];
  17281. var triangleb = [
  17282. hole[ holeIndex ] ,
  17283. hole[ prevHoleVert ],
  17284. shape[ shapeIndex ]
  17285. ];
  17286. verts.push( trianglea );
  17287. verts.push( triangleb );
  17288. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17289. }
  17290. return {
  17291. shape:shape, /* shape with no holes */
  17292. isolatedPts: verts, /* isolated faces */
  17293. allpoints: allpoints
  17294. }
  17295. },
  17296. triangulateShape: function ( contour, holes ) {
  17297. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17298. var shape = shapeWithoutHoles.shape,
  17299. allpoints = shapeWithoutHoles.allpoints,
  17300. isolatedPts = shapeWithoutHoles.isolatedPts;
  17301. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17302. // 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.
  17303. //console.log( "triangles",triangles, triangles.length );
  17304. //console.log( "allpoints",allpoints, allpoints.length );
  17305. var i, il, f, face,
  17306. key, index,
  17307. allPointsMap = {},
  17308. isolatedPointsMap = {};
  17309. // prepare all points map
  17310. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17311. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17312. if ( allPointsMap[ key ] !== undefined ) {
  17313. console.log( "Duplicate point", key );
  17314. }
  17315. allPointsMap[ key ] = i;
  17316. }
  17317. // check all face vertices against all points map
  17318. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17319. face = triangles[ i ];
  17320. for ( f = 0; f < 3; f ++ ) {
  17321. key = face[ f ].x + ":" + face[ f ].y;
  17322. index = allPointsMap[ key ];
  17323. if ( index !== undefined ) {
  17324. face[ f ] = index;
  17325. }
  17326. }
  17327. }
  17328. // check isolated points vertices against all points map
  17329. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17330. face = isolatedPts[ i ];
  17331. for ( f = 0; f < 3; f ++ ) {
  17332. key = face[ f ].x + ":" + face[ f ].y;
  17333. index = allPointsMap[ key ];
  17334. if ( index !== undefined ) {
  17335. face[ f ] = index;
  17336. }
  17337. }
  17338. }
  17339. return triangles.concat( isolatedPts );
  17340. }, // end triangulate shapes
  17341. /*
  17342. triangulate2 : function( pts, holes ) {
  17343. // For use with Poly2Tri.js
  17344. var allpts = pts.concat();
  17345. var shape = [];
  17346. for (var p in pts) {
  17347. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17348. }
  17349. var swctx = new js.poly2tri.SweepContext(shape);
  17350. for (var h in holes) {
  17351. var aHole = holes[h];
  17352. var newHole = []
  17353. for (i in aHole) {
  17354. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17355. allpts.push(aHole[i]);
  17356. }
  17357. swctx.AddHole(newHole);
  17358. }
  17359. var find;
  17360. var findIndexForPt = function (pt) {
  17361. find = new THREE.Vector2(pt.x, pt.y);
  17362. var p;
  17363. for (p=0, pl = allpts.length; p<pl; p++) {
  17364. if (allpts[p].equals(find)) return p;
  17365. }
  17366. return -1;
  17367. };
  17368. // triangulate
  17369. js.poly2tri.sweep.Triangulate(swctx);
  17370. var triangles = swctx.GetTriangles();
  17371. var tr ;
  17372. var facesPts = [];
  17373. for (var t in triangles) {
  17374. tr = triangles[t];
  17375. facesPts.push([
  17376. findIndexForPt(tr.GetPoint(0)),
  17377. findIndexForPt(tr.GetPoint(1)),
  17378. findIndexForPt(tr.GetPoint(2))
  17379. ]);
  17380. }
  17381. // console.log(facesPts);
  17382. // console.log("triangles", triangles.length, triangles);
  17383. // Returns array of faces with 3 element each
  17384. return facesPts;
  17385. },
  17386. */
  17387. isClockWise: function ( pts ) {
  17388. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17389. },
  17390. // Bezier Curves formulas obtained from
  17391. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17392. // Quad Bezier Functions
  17393. b2p0: function ( t, p ) {
  17394. var k = 1 - t;
  17395. return k * k * p;
  17396. },
  17397. b2p1: function ( t, p ) {
  17398. return 2 * ( 1 - t ) * t * p;
  17399. },
  17400. b2p2: function ( t, p ) {
  17401. return t * t * p;
  17402. },
  17403. b2: function ( t, p0, p1, p2 ) {
  17404. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17405. },
  17406. // Cubic Bezier Functions
  17407. b3p0: function ( t, p ) {
  17408. var k = 1 - t;
  17409. return k * k * k * p;
  17410. },
  17411. b3p1: function ( t, p ) {
  17412. var k = 1 - t;
  17413. return 3 * k * k * t * p;
  17414. },
  17415. b3p2: function ( t, p ) {
  17416. var k = 1 - t;
  17417. return 3 * k * t * t * p;
  17418. },
  17419. b3p3: function ( t, p ) {
  17420. return t * t * t * p;
  17421. },
  17422. b3: function ( t, p0, p1, p2, p3 ) {
  17423. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17424. }
  17425. };
  17426. /**************************************************************
  17427. * Line
  17428. **************************************************************/
  17429. THREE.LineCurve = function ( v1, v2 ) {
  17430. this.v1 = v1;
  17431. this.v2 = v2;
  17432. };
  17433. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17434. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17435. var point = this.v2.clone().sub(this.v1);
  17436. point.multiplyScalar( t ).add( this.v1 );
  17437. return point;
  17438. };
  17439. // Line curve is linear, so we can overwrite default getPointAt
  17440. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17441. return this.getPoint( u );
  17442. };
  17443. THREE.LineCurve.prototype.getTangent = function( t ) {
  17444. var tangent = this.v2.clone().sub(this.v1);
  17445. return tangent.normalize();
  17446. };
  17447. /**************************************************************
  17448. * Quadratic Bezier curve
  17449. **************************************************************/
  17450. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17451. this.v0 = v0;
  17452. this.v1 = v1;
  17453. this.v2 = v2;
  17454. };
  17455. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17456. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17457. var tx, ty;
  17458. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17459. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17460. return new THREE.Vector2( tx, ty );
  17461. };
  17462. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17463. var tx, ty;
  17464. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17465. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17466. // returns unit vector
  17467. var tangent = new THREE.Vector2( tx, ty );
  17468. tangent.normalize();
  17469. return tangent;
  17470. };
  17471. /**************************************************************
  17472. * Cubic Bezier curve
  17473. **************************************************************/
  17474. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17475. this.v0 = v0;
  17476. this.v1 = v1;
  17477. this.v2 = v2;
  17478. this.v3 = v3;
  17479. };
  17480. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17481. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  17482. var tx, ty;
  17483. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17484. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17485. return new THREE.Vector2( tx, ty );
  17486. };
  17487. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  17488. var tx, ty;
  17489. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17490. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17491. var tangent = new THREE.Vector2( tx, ty );
  17492. tangent.normalize();
  17493. return tangent;
  17494. };
  17495. /**************************************************************
  17496. * Spline curve
  17497. **************************************************************/
  17498. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  17499. this.points = (points == undefined) ? [] : points;
  17500. };
  17501. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  17502. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  17503. var v = new THREE.Vector2();
  17504. var c = [];
  17505. var points = this.points, point, intPoint, weight;
  17506. point = ( points.length - 1 ) * t;
  17507. intPoint = Math.floor( point );
  17508. weight = point - intPoint;
  17509. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17510. c[ 1 ] = intPoint;
  17511. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  17512. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  17513. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17514. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17515. return v;
  17516. };
  17517. /**************************************************************
  17518. * Ellipse curve
  17519. **************************************************************/
  17520. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  17521. aStartAngle, aEndAngle,
  17522. aClockwise ) {
  17523. this.aX = aX;
  17524. this.aY = aY;
  17525. this.xRadius = xRadius;
  17526. this.yRadius = yRadius;
  17527. this.aStartAngle = aStartAngle;
  17528. this.aEndAngle = aEndAngle;
  17529. this.aClockwise = aClockwise;
  17530. };
  17531. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  17532. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  17533. var deltaAngle = this.aEndAngle - this.aStartAngle;
  17534. if ( !this.aClockwise ) {
  17535. t = 1 - t;
  17536. }
  17537. var angle = this.aStartAngle + t * deltaAngle;
  17538. var tx = this.aX + this.xRadius * Math.cos( angle );
  17539. var ty = this.aY + this.yRadius * Math.sin( angle );
  17540. return new THREE.Vector2( tx, ty );
  17541. };
  17542. /**************************************************************
  17543. * Arc curve
  17544. **************************************************************/
  17545. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17546. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  17547. };
  17548. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  17549. /**************************************************************
  17550. * Line3D
  17551. **************************************************************/
  17552. THREE.LineCurve3 = THREE.Curve.create(
  17553. function ( v1, v2 ) {
  17554. this.v1 = v1;
  17555. this.v2 = v2;
  17556. },
  17557. function ( t ) {
  17558. var r = new THREE.Vector3();
  17559. r.subVectors( this.v2, this.v1 ); // diff
  17560. r.multiplyScalar( t );
  17561. r.add( this.v1 );
  17562. return r;
  17563. }
  17564. );
  17565. /**************************************************************
  17566. * Quadratic Bezier 3D curve
  17567. **************************************************************/
  17568. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  17569. function ( v0, v1, v2 ) {
  17570. this.v0 = v0;
  17571. this.v1 = v1;
  17572. this.v2 = v2;
  17573. },
  17574. function ( t ) {
  17575. var tx, ty, tz;
  17576. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17577. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17578. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  17579. return new THREE.Vector3( tx, ty, tz );
  17580. }
  17581. );
  17582. /**************************************************************
  17583. * Cubic Bezier 3D curve
  17584. **************************************************************/
  17585. THREE.CubicBezierCurve3 = THREE.Curve.create(
  17586. function ( v0, v1, v2, v3 ) {
  17587. this.v0 = v0;
  17588. this.v1 = v1;
  17589. this.v2 = v2;
  17590. this.v3 = v3;
  17591. },
  17592. function ( t ) {
  17593. var tx, ty, tz;
  17594. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17595. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17596. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  17597. return new THREE.Vector3( tx, ty, tz );
  17598. }
  17599. );
  17600. /**************************************************************
  17601. * Spline 3D curve
  17602. **************************************************************/
  17603. THREE.SplineCurve3 = THREE.Curve.create(
  17604. function ( points /* array of Vector3 */) {
  17605. this.points = (points == undefined) ? [] : points;
  17606. },
  17607. function ( t ) {
  17608. var v = new THREE.Vector3();
  17609. var c = [];
  17610. var points = this.points, point, intPoint, weight;
  17611. point = ( points.length - 1 ) * t;
  17612. intPoint = Math.floor( point );
  17613. weight = point - intPoint;
  17614. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17615. c[ 1 ] = intPoint;
  17616. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17617. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17618. var pt0 = points[ c[0] ],
  17619. pt1 = points[ c[1] ],
  17620. pt2 = points[ c[2] ],
  17621. pt3 = points[ c[3] ];
  17622. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  17623. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  17624. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  17625. return v;
  17626. }
  17627. );
  17628. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  17629. // var v = new THREE.Vector3();
  17630. // var c = [];
  17631. // var points = this.points, point, intPoint, weight;
  17632. // point = ( points.length - 1 ) * t;
  17633. // intPoint = Math.floor( point );
  17634. // weight = point - intPoint;
  17635. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17636. // c[ 1 ] = intPoint;
  17637. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17638. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17639. // var pt0 = points[ c[0] ],
  17640. // pt1 = points[ c[1] ],
  17641. // pt2 = points[ c[2] ],
  17642. // pt3 = points[ c[3] ];
  17643. // // t = weight;
  17644. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  17645. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  17646. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  17647. // return v;
  17648. // }
  17649. /**************************************************************
  17650. * Closed Spline 3D curve
  17651. **************************************************************/
  17652. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  17653. function ( points /* array of Vector3 */) {
  17654. this.points = (points == undefined) ? [] : points;
  17655. },
  17656. function ( t ) {
  17657. var v = new THREE.Vector3();
  17658. var c = [];
  17659. var points = this.points, point, intPoint, weight;
  17660. point = ( points.length - 0 ) * t;
  17661. // This needs to be from 0-length +1
  17662. intPoint = Math.floor( point );
  17663. weight = point - intPoint;
  17664. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  17665. c[ 0 ] = ( intPoint - 1 ) % points.length;
  17666. c[ 1 ] = ( intPoint ) % points.length;
  17667. c[ 2 ] = ( intPoint + 1 ) % points.length;
  17668. c[ 3 ] = ( intPoint + 2 ) % points.length;
  17669. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17670. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17671. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  17672. return v;
  17673. }
  17674. );
  17675. /**
  17676. * @author mikael emtinger / http://gomo.se/
  17677. */
  17678. THREE.AnimationHandler = (function() {
  17679. var playing = [];
  17680. var library = {};
  17681. var that = {};
  17682. //--- update ---
  17683. that.update = function( deltaTimeMS ) {
  17684. for( var i = 0; i < playing.length; i ++ )
  17685. playing[ i ].update( deltaTimeMS );
  17686. };
  17687. //--- add ---
  17688. that.addToUpdate = function( animation ) {
  17689. if ( playing.indexOf( animation ) === -1 )
  17690. playing.push( animation );
  17691. };
  17692. //--- remove ---
  17693. that.removeFromUpdate = function( animation ) {
  17694. var index = playing.indexOf( animation );
  17695. if( index !== -1 )
  17696. playing.splice( index, 1 );
  17697. };
  17698. //--- add ---
  17699. that.add = function( data ) {
  17700. if ( library[ data.name ] !== undefined )
  17701. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17702. library[ data.name ] = data;
  17703. initData( data );
  17704. };
  17705. //--- get ---
  17706. that.get = function( name ) {
  17707. if ( typeof name === "string" ) {
  17708. if ( library[ name ] ) {
  17709. return library[ name ];
  17710. } else {
  17711. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17712. return null;
  17713. }
  17714. } else {
  17715. // todo: add simple tween library
  17716. }
  17717. };
  17718. //--- parse ---
  17719. that.parse = function( root ) {
  17720. // setup hierarchy
  17721. var hierarchy = [];
  17722. if ( root instanceof THREE.SkinnedMesh ) {
  17723. for( var b = 0; b < root.bones.length; b++ ) {
  17724. hierarchy.push( root.bones[ b ] );
  17725. }
  17726. } else {
  17727. parseRecurseHierarchy( root, hierarchy );
  17728. }
  17729. return hierarchy;
  17730. };
  17731. var parseRecurseHierarchy = function( root, hierarchy ) {
  17732. hierarchy.push( root );
  17733. for( var c = 0; c < root.children.length; c++ )
  17734. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17735. }
  17736. //--- init data ---
  17737. var initData = function( data ) {
  17738. if( data.initialized === true )
  17739. return;
  17740. // loop through all keys
  17741. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17742. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17743. // remove minus times
  17744. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17745. data.hierarchy[ h ].keys[ k ].time = 0;
  17746. // create quaternions
  17747. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17748. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17749. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17750. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17751. }
  17752. }
  17753. // prepare morph target keys
  17754. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17755. // get all used
  17756. var usedMorphTargets = {};
  17757. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17758. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17759. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17760. usedMorphTargets[ morphTargetName ] = -1;
  17761. }
  17762. }
  17763. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17764. // set all used on all frames
  17765. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17766. var influences = {};
  17767. for ( var morphTargetName in usedMorphTargets ) {
  17768. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17769. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17770. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17771. break;
  17772. }
  17773. }
  17774. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17775. influences[ morphTargetName ] = 0;
  17776. }
  17777. }
  17778. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17779. }
  17780. }
  17781. // remove all keys that are on the same time
  17782. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17783. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17784. data.hierarchy[ h ].keys.splice( k, 1 );
  17785. k --;
  17786. }
  17787. }
  17788. // set index
  17789. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17790. data.hierarchy[ h ].keys[ k ].index = k;
  17791. }
  17792. }
  17793. // JIT
  17794. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17795. data.JIT = {};
  17796. data.JIT.hierarchy = [];
  17797. for( var h = 0; h < data.hierarchy.length; h ++ )
  17798. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17799. // done
  17800. data.initialized = true;
  17801. };
  17802. // interpolation types
  17803. that.LINEAR = 0;
  17804. that.CATMULLROM = 1;
  17805. that.CATMULLROM_FORWARD = 2;
  17806. return that;
  17807. }());
  17808. /**
  17809. * @author mikael emtinger / http://gomo.se/
  17810. * @author mrdoob / http://mrdoob.com/
  17811. * @author alteredq / http://alteredqualia.com/
  17812. */
  17813. THREE.Animation = function ( root, name, interpolationType ) {
  17814. this.root = root;
  17815. this.data = THREE.AnimationHandler.get( name );
  17816. this.hierarchy = THREE.AnimationHandler.parse( root );
  17817. this.currentTime = 0;
  17818. this.timeScale = 1;
  17819. this.isPlaying = false;
  17820. this.isPaused = true;
  17821. this.loop = true;
  17822. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17823. this.points = [];
  17824. this.target = new THREE.Vector3();
  17825. };
  17826. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17827. if ( this.isPlaying === false ) {
  17828. this.isPlaying = true;
  17829. this.loop = loop !== undefined ? loop : true;
  17830. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17831. // reset key cache
  17832. var h, hl = this.hierarchy.length,
  17833. object;
  17834. for ( h = 0; h < hl; h ++ ) {
  17835. object = this.hierarchy[ h ];
  17836. object.matrixAutoUpdate = true;
  17837. if ( object.animationCache === undefined ) {
  17838. object.animationCache = {};
  17839. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17840. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17841. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17842. }
  17843. var prevKey = object.animationCache.prevKey;
  17844. var nextKey = object.animationCache.nextKey;
  17845. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17846. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17847. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17848. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17849. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17850. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17851. }
  17852. this.update( 0 );
  17853. }
  17854. this.isPaused = false;
  17855. THREE.AnimationHandler.addToUpdate( this );
  17856. };
  17857. THREE.Animation.prototype.pause = function() {
  17858. if ( this.isPaused === true ) {
  17859. THREE.AnimationHandler.addToUpdate( this );
  17860. } else {
  17861. THREE.AnimationHandler.removeFromUpdate( this );
  17862. }
  17863. this.isPaused = !this.isPaused;
  17864. };
  17865. THREE.Animation.prototype.stop = function() {
  17866. this.isPlaying = false;
  17867. this.isPaused = false;
  17868. THREE.AnimationHandler.removeFromUpdate( this );
  17869. };
  17870. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17871. // early out
  17872. if ( this.isPlaying === false ) return;
  17873. // vars
  17874. var types = [ "pos", "rot", "scl" ];
  17875. var type;
  17876. var scale;
  17877. var vector;
  17878. var prevXYZ, nextXYZ;
  17879. var prevKey, nextKey;
  17880. var object;
  17881. var animationCache;
  17882. var frame;
  17883. var JIThierarchy = this.data.JIT.hierarchy;
  17884. var currentTime, unloopedCurrentTime;
  17885. var currentPoint, forwardPoint, angle;
  17886. this.currentTime += deltaTimeMS * this.timeScale;
  17887. unloopedCurrentTime = this.currentTime;
  17888. currentTime = this.currentTime = this.currentTime % this.data.length;
  17889. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17890. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17891. object = this.hierarchy[ h ];
  17892. animationCache = object.animationCache;
  17893. // loop through pos/rot/scl
  17894. for ( var t = 0; t < 3; t ++ ) {
  17895. // get keys
  17896. type = types[ t ];
  17897. prevKey = animationCache.prevKey[ type ];
  17898. nextKey = animationCache.nextKey[ type ];
  17899. // switch keys?
  17900. if ( nextKey.time <= unloopedCurrentTime ) {
  17901. // did we loop?
  17902. if ( currentTime < unloopedCurrentTime ) {
  17903. if ( this.loop ) {
  17904. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17905. nextKey = this.getNextKeyWith( type, h, 1 );
  17906. while( nextKey.time < currentTime ) {
  17907. prevKey = nextKey;
  17908. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17909. }
  17910. } else {
  17911. this.stop();
  17912. return;
  17913. }
  17914. } else {
  17915. do {
  17916. prevKey = nextKey;
  17917. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17918. } while( nextKey.time < currentTime )
  17919. }
  17920. animationCache.prevKey[ type ] = prevKey;
  17921. animationCache.nextKey[ type ] = nextKey;
  17922. }
  17923. object.matrixAutoUpdate = true;
  17924. object.matrixWorldNeedsUpdate = true;
  17925. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  17926. prevXYZ = prevKey[ type ];
  17927. nextXYZ = nextKey[ type ];
  17928. // check scale error
  17929. if ( scale < 0 || scale > 1 ) {
  17930. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  17931. scale = scale < 0 ? 0 : 1;
  17932. }
  17933. // interpolate
  17934. if ( type === "pos" ) {
  17935. vector = object.position;
  17936. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  17937. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17938. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17939. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17940. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17941. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17942. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  17943. this.points[ 1 ] = prevXYZ;
  17944. this.points[ 2 ] = nextXYZ;
  17945. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  17946. scale = scale * 0.33 + 0.33;
  17947. currentPoint = this.interpolateCatmullRom( this.points, scale );
  17948. vector.x = currentPoint[ 0 ];
  17949. vector.y = currentPoint[ 1 ];
  17950. vector.z = currentPoint[ 2 ];
  17951. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17952. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  17953. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  17954. this.target.sub( vector );
  17955. this.target.y = 0;
  17956. this.target.normalize();
  17957. angle = Math.atan2( this.target.x, this.target.z );
  17958. object.rotation.set( 0, angle, 0 );
  17959. }
  17960. }
  17961. } else if ( type === "rot" ) {
  17962. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  17963. } else if ( type === "scl" ) {
  17964. vector = object.scale;
  17965. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17966. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17967. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17968. }
  17969. }
  17970. }
  17971. };
  17972. // Catmull-Rom spline
  17973. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  17974. var c = [], v3 = [],
  17975. point, intPoint, weight, w2, w3,
  17976. pa, pb, pc, pd;
  17977. point = ( points.length - 1 ) * scale;
  17978. intPoint = Math.floor( point );
  17979. weight = point - intPoint;
  17980. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  17981. c[ 1 ] = intPoint;
  17982. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  17983. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  17984. pa = points[ c[ 0 ] ];
  17985. pb = points[ c[ 1 ] ];
  17986. pc = points[ c[ 2 ] ];
  17987. pd = points[ c[ 3 ] ];
  17988. w2 = weight * weight;
  17989. w3 = weight * w2;
  17990. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  17991. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  17992. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  17993. return v3;
  17994. };
  17995. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  17996. var v0 = ( p2 - p0 ) * 0.5,
  17997. v1 = ( p3 - p1 ) * 0.5;
  17998. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17999. };
  18000. // Get next key with
  18001. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18002. var keys = this.data.hierarchy[ h ].keys;
  18003. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18004. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18005. key = key < keys.length - 1 ? key : keys.length - 1;
  18006. } else {
  18007. key = key % keys.length;
  18008. }
  18009. for ( ; key < keys.length; key++ ) {
  18010. if ( keys[ key ][ type ] !== undefined ) {
  18011. return keys[ key ];
  18012. }
  18013. }
  18014. return this.data.hierarchy[ h ].keys[ 0 ];
  18015. };
  18016. // Get previous key with
  18017. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18018. var keys = this.data.hierarchy[ h ].keys;
  18019. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18020. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18021. key = key > 0 ? key : 0;
  18022. } else {
  18023. key = key >= 0 ? key : key + keys.length;
  18024. }
  18025. for ( ; key >= 0; key -- ) {
  18026. if ( keys[ key ][ type ] !== undefined ) {
  18027. return keys[ key ];
  18028. }
  18029. }
  18030. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18031. };
  18032. /**
  18033. * @author mikael emtinger / http://gomo.se/
  18034. * @author mrdoob / http://mrdoob.com/
  18035. * @author alteredq / http://alteredqualia.com/
  18036. * @author khang duong
  18037. * @author erik kitson
  18038. */
  18039. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  18040. this.root = root;
  18041. this.data = THREE.AnimationHandler.get( data );
  18042. this.hierarchy = THREE.AnimationHandler.parse( root );
  18043. this.currentTime = 0;
  18044. this.timeScale = 0.001;
  18045. this.isPlaying = false;
  18046. this.isPaused = true;
  18047. this.loop = true;
  18048. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  18049. // initialize to first keyframes
  18050. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18051. var keys = this.data.hierarchy[h].keys,
  18052. sids = this.data.hierarchy[h].sids,
  18053. obj = this.hierarchy[h];
  18054. if ( keys.length && sids ) {
  18055. for ( var s = 0; s < sids.length; s++ ) {
  18056. var sid = sids[ s ],
  18057. next = this.getNextKeyWith( sid, h, 0 );
  18058. if ( next ) {
  18059. next.apply( sid );
  18060. }
  18061. }
  18062. obj.matrixAutoUpdate = false;
  18063. this.data.hierarchy[h].node.updateMatrix();
  18064. obj.matrixWorldNeedsUpdate = true;
  18065. }
  18066. }
  18067. };
  18068. // Play
  18069. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18070. if( !this.isPlaying ) {
  18071. this.isPlaying = true;
  18072. this.loop = loop !== undefined ? loop : true;
  18073. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18074. this.startTimeMs = startTimeMS;
  18075. this.startTime = 10000000;
  18076. this.endTime = -this.startTime;
  18077. // reset key cache
  18078. var h, hl = this.hierarchy.length,
  18079. object,
  18080. node;
  18081. for ( h = 0; h < hl; h++ ) {
  18082. object = this.hierarchy[ h ];
  18083. node = this.data.hierarchy[ h ];
  18084. if ( node.animationCache === undefined ) {
  18085. node.animationCache = {};
  18086. node.animationCache.prevKey = null;
  18087. node.animationCache.nextKey = null;
  18088. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18089. }
  18090. var keys = this.data.hierarchy[h].keys;
  18091. if (keys.length) {
  18092. node.animationCache.prevKey = keys[ 0 ];
  18093. node.animationCache.nextKey = keys[ 1 ];
  18094. this.startTime = Math.min( keys[0].time, this.startTime );
  18095. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18096. }
  18097. }
  18098. this.update( 0 );
  18099. }
  18100. this.isPaused = false;
  18101. THREE.AnimationHandler.addToUpdate( this );
  18102. };
  18103. // Pause
  18104. THREE.KeyFrameAnimation.prototype.pause = function() {
  18105. if( this.isPaused ) {
  18106. THREE.AnimationHandler.addToUpdate( this );
  18107. } else {
  18108. THREE.AnimationHandler.removeFromUpdate( this );
  18109. }
  18110. this.isPaused = !this.isPaused;
  18111. };
  18112. // Stop
  18113. THREE.KeyFrameAnimation.prototype.stop = function() {
  18114. this.isPlaying = false;
  18115. this.isPaused = false;
  18116. THREE.AnimationHandler.removeFromUpdate( this );
  18117. // reset JIT matrix and remove cache
  18118. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18119. var obj = this.hierarchy[ h ];
  18120. var node = this.data.hierarchy[ h ];
  18121. if ( node.animationCache !== undefined ) {
  18122. var original = node.animationCache.originalMatrix;
  18123. if( obj instanceof THREE.Bone ) {
  18124. original.copy( obj.skinMatrix );
  18125. obj.skinMatrix = original;
  18126. } else {
  18127. original.copy( obj.matrix );
  18128. obj.matrix = original;
  18129. }
  18130. delete node.animationCache;
  18131. }
  18132. }
  18133. };
  18134. // Update
  18135. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18136. // early out
  18137. if( !this.isPlaying ) return;
  18138. // vars
  18139. var prevKey, nextKey;
  18140. var object;
  18141. var node;
  18142. var frame;
  18143. var JIThierarchy = this.data.JIT.hierarchy;
  18144. var currentTime, unloopedCurrentTime;
  18145. var looped;
  18146. // update
  18147. this.currentTime += deltaTimeMS * this.timeScale;
  18148. unloopedCurrentTime = this.currentTime;
  18149. currentTime = this.currentTime = this.currentTime % this.data.length;
  18150. // if looped around, the current time should be based on the startTime
  18151. if ( currentTime < this.startTimeMs ) {
  18152. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18153. }
  18154. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18155. looped = currentTime < unloopedCurrentTime;
  18156. if ( looped && !this.loop ) {
  18157. // Set the animation to the last keyframes and stop
  18158. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18159. var keys = this.data.hierarchy[h].keys,
  18160. sids = this.data.hierarchy[h].sids,
  18161. end = keys.length-1,
  18162. obj = this.hierarchy[h];
  18163. if ( keys.length ) {
  18164. for ( var s = 0; s < sids.length; s++ ) {
  18165. var sid = sids[ s ],
  18166. prev = this.getPrevKeyWith( sid, h, end );
  18167. if ( prev ) {
  18168. prev.apply( sid );
  18169. }
  18170. }
  18171. this.data.hierarchy[h].node.updateMatrix();
  18172. obj.matrixWorldNeedsUpdate = true;
  18173. }
  18174. }
  18175. this.stop();
  18176. return;
  18177. }
  18178. // check pre-infinity
  18179. if ( currentTime < this.startTime ) {
  18180. return;
  18181. }
  18182. // update
  18183. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18184. object = this.hierarchy[ h ];
  18185. node = this.data.hierarchy[ h ];
  18186. var keys = node.keys,
  18187. animationCache = node.animationCache;
  18188. // use JIT?
  18189. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18190. if( object instanceof THREE.Bone ) {
  18191. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18192. object.matrixWorldNeedsUpdate = false;
  18193. } else {
  18194. object.matrix = JIThierarchy[ h ][ frame ];
  18195. object.matrixWorldNeedsUpdate = true;
  18196. }
  18197. // use interpolation
  18198. } else if ( keys.length ) {
  18199. // make sure so original matrix and not JIT matrix is set
  18200. if ( this.JITCompile && animationCache ) {
  18201. if( object instanceof THREE.Bone ) {
  18202. object.skinMatrix = animationCache.originalMatrix;
  18203. } else {
  18204. object.matrix = animationCache.originalMatrix;
  18205. }
  18206. }
  18207. prevKey = animationCache.prevKey;
  18208. nextKey = animationCache.nextKey;
  18209. if ( prevKey && nextKey ) {
  18210. // switch keys?
  18211. if ( nextKey.time <= unloopedCurrentTime ) {
  18212. // did we loop?
  18213. if ( looped && this.loop ) {
  18214. prevKey = keys[ 0 ];
  18215. nextKey = keys[ 1 ];
  18216. while ( nextKey.time < currentTime ) {
  18217. prevKey = nextKey;
  18218. nextKey = keys[ prevKey.index + 1 ];
  18219. }
  18220. } else if ( !looped ) {
  18221. var lastIndex = keys.length - 1;
  18222. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18223. prevKey = nextKey;
  18224. nextKey = keys[ prevKey.index + 1 ];
  18225. }
  18226. }
  18227. animationCache.prevKey = prevKey;
  18228. animationCache.nextKey = nextKey;
  18229. }
  18230. if(nextKey.time >= currentTime)
  18231. prevKey.interpolate( nextKey, currentTime );
  18232. else
  18233. prevKey.interpolate( nextKey, nextKey.time);
  18234. }
  18235. this.data.hierarchy[h].node.updateMatrix();
  18236. object.matrixWorldNeedsUpdate = true;
  18237. }
  18238. }
  18239. // update JIT?
  18240. if ( this.JITCompile ) {
  18241. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18242. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18243. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18244. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18245. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18246. } else {
  18247. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18248. }
  18249. }
  18250. }
  18251. }
  18252. };
  18253. // Get next key with
  18254. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18255. var keys = this.data.hierarchy[ h ].keys;
  18256. key = key % keys.length;
  18257. for ( ; key < keys.length; key++ ) {
  18258. if ( keys[ key ].hasTarget( sid ) ) {
  18259. return keys[ key ];
  18260. }
  18261. }
  18262. return keys[ 0 ];
  18263. };
  18264. // Get previous key with
  18265. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18266. var keys = this.data.hierarchy[ h ].keys;
  18267. key = key >= 0 ? key : key + keys.length;
  18268. for ( ; key >= 0; key-- ) {
  18269. if ( keys[ key ].hasTarget( sid ) ) {
  18270. return keys[ key ];
  18271. }
  18272. }
  18273. return keys[ keys.length - 1 ];
  18274. };
  18275. /**
  18276. * Camera for rendering cube maps
  18277. * - renders scene into axis-aligned cube
  18278. *
  18279. * @author alteredq / http://alteredqualia.com/
  18280. */
  18281. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18282. THREE.Object3D.call( this );
  18283. var fov = 90, aspect = 1;
  18284. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18285. cameraPX.up.set( 0, -1, 0 );
  18286. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18287. this.add( cameraPX );
  18288. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18289. cameraNX.up.set( 0, -1, 0 );
  18290. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18291. this.add( cameraNX );
  18292. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18293. cameraPY.up.set( 0, 0, 1 );
  18294. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18295. this.add( cameraPY );
  18296. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18297. cameraNY.up.set( 0, 0, -1 );
  18298. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18299. this.add( cameraNY );
  18300. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18301. cameraPZ.up.set( 0, -1, 0 );
  18302. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18303. this.add( cameraPZ );
  18304. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18305. cameraNZ.up.set( 0, -1, 0 );
  18306. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18307. this.add( cameraNZ );
  18308. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18309. this.updateCubeMap = function ( renderer, scene ) {
  18310. var renderTarget = this.renderTarget;
  18311. var generateMipmaps = renderTarget.generateMipmaps;
  18312. renderTarget.generateMipmaps = false;
  18313. renderTarget.activeCubeFace = 0;
  18314. renderer.render( scene, cameraPX, renderTarget );
  18315. renderTarget.activeCubeFace = 1;
  18316. renderer.render( scene, cameraNX, renderTarget );
  18317. renderTarget.activeCubeFace = 2;
  18318. renderer.render( scene, cameraPY, renderTarget );
  18319. renderTarget.activeCubeFace = 3;
  18320. renderer.render( scene, cameraNY, renderTarget );
  18321. renderTarget.activeCubeFace = 4;
  18322. renderer.render( scene, cameraPZ, renderTarget );
  18323. renderTarget.generateMipmaps = generateMipmaps;
  18324. renderTarget.activeCubeFace = 5;
  18325. renderer.render( scene, cameraNZ, renderTarget );
  18326. };
  18327. };
  18328. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18329. /*
  18330. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18331. *
  18332. * A general perpose camera, for setting FOV, Lens Focal Length,
  18333. * and switching between perspective and orthographic views easily.
  18334. * Use this only if you do not wish to manage
  18335. * both a Orthographic and Perspective Camera
  18336. *
  18337. */
  18338. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18339. THREE.Camera.call( this );
  18340. this.fov = fov;
  18341. this.left = -width / 2;
  18342. this.right = width / 2
  18343. this.top = height / 2;
  18344. this.bottom = -height / 2;
  18345. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18346. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18347. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18348. this.zoom = 1;
  18349. this.toPerspective();
  18350. var aspect = width/height;
  18351. };
  18352. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18353. THREE.CombinedCamera.prototype.toPerspective = function () {
  18354. // Switches to the Perspective Camera
  18355. this.near = this.cameraP.near;
  18356. this.far = this.cameraP.far;
  18357. this.cameraP.fov = this.fov / this.zoom ;
  18358. this.cameraP.updateProjectionMatrix();
  18359. this.projectionMatrix = this.cameraP.projectionMatrix;
  18360. this.inPerspectiveMode = true;
  18361. this.inOrthographicMode = false;
  18362. };
  18363. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18364. // Switches to the Orthographic camera estimating viewport from Perspective
  18365. var fov = this.fov;
  18366. var aspect = this.cameraP.aspect;
  18367. var near = this.cameraP.near;
  18368. var far = this.cameraP.far;
  18369. // The size that we set is the mid plane of the viewing frustum
  18370. var hyperfocus = ( near + far ) / 2;
  18371. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18372. var planeHeight = 2 * halfHeight;
  18373. var planeWidth = planeHeight * aspect;
  18374. var halfWidth = planeWidth / 2;
  18375. halfHeight /= this.zoom;
  18376. halfWidth /= this.zoom;
  18377. this.cameraO.left = -halfWidth;
  18378. this.cameraO.right = halfWidth;
  18379. this.cameraO.top = halfHeight;
  18380. this.cameraO.bottom = -halfHeight;
  18381. // this.cameraO.left = -farHalfWidth;
  18382. // this.cameraO.right = farHalfWidth;
  18383. // this.cameraO.top = farHalfHeight;
  18384. // this.cameraO.bottom = -farHalfHeight;
  18385. // this.cameraO.left = this.left / this.zoom;
  18386. // this.cameraO.right = this.right / this.zoom;
  18387. // this.cameraO.top = this.top / this.zoom;
  18388. // this.cameraO.bottom = this.bottom / this.zoom;
  18389. this.cameraO.updateProjectionMatrix();
  18390. this.near = this.cameraO.near;
  18391. this.far = this.cameraO.far;
  18392. this.projectionMatrix = this.cameraO.projectionMatrix;
  18393. this.inPerspectiveMode = false;
  18394. this.inOrthographicMode = true;
  18395. };
  18396. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18397. this.cameraP.aspect = width / height;
  18398. this.left = -width / 2;
  18399. this.right = width / 2
  18400. this.top = height / 2;
  18401. this.bottom = -height / 2;
  18402. };
  18403. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18404. this.fov = fov;
  18405. if ( this.inPerspectiveMode ) {
  18406. this.toPerspective();
  18407. } else {
  18408. this.toOrthographic();
  18409. }
  18410. };
  18411. // For mantaining similar API with PerspectiveCamera
  18412. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18413. if ( this.inPerspectiveMode ) {
  18414. this.toPerspective();
  18415. } else {
  18416. this.toPerspective();
  18417. this.toOrthographic();
  18418. }
  18419. };
  18420. /*
  18421. * Uses Focal Length (in mm) to estimate and set FOV
  18422. * 35mm (fullframe) camera is used if frame size is not specified;
  18423. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18424. */
  18425. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18426. if ( frameHeight === undefined ) frameHeight = 24;
  18427. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18428. this.setFov( fov );
  18429. return fov;
  18430. };
  18431. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18432. this.zoom = zoom;
  18433. if ( this.inPerspectiveMode ) {
  18434. this.toPerspective();
  18435. } else {
  18436. this.toOrthographic();
  18437. }
  18438. };
  18439. THREE.CombinedCamera.prototype.toFrontView = function() {
  18440. this.rotation.x = 0;
  18441. this.rotation.y = 0;
  18442. this.rotation.z = 0;
  18443. // should we be modifing the matrix instead?
  18444. this.rotationAutoUpdate = false;
  18445. };
  18446. THREE.CombinedCamera.prototype.toBackView = function() {
  18447. this.rotation.x = 0;
  18448. this.rotation.y = Math.PI;
  18449. this.rotation.z = 0;
  18450. this.rotationAutoUpdate = false;
  18451. };
  18452. THREE.CombinedCamera.prototype.toLeftView = function() {
  18453. this.rotation.x = 0;
  18454. this.rotation.y = - Math.PI / 2;
  18455. this.rotation.z = 0;
  18456. this.rotationAutoUpdate = false;
  18457. };
  18458. THREE.CombinedCamera.prototype.toRightView = function() {
  18459. this.rotation.x = 0;
  18460. this.rotation.y = Math.PI / 2;
  18461. this.rotation.z = 0;
  18462. this.rotationAutoUpdate = false;
  18463. };
  18464. THREE.CombinedCamera.prototype.toTopView = function() {
  18465. this.rotation.x = - Math.PI / 2;
  18466. this.rotation.y = 0;
  18467. this.rotation.z = 0;
  18468. this.rotationAutoUpdate = false;
  18469. };
  18470. THREE.CombinedCamera.prototype.toBottomView = function() {
  18471. this.rotation.x = Math.PI / 2;
  18472. this.rotation.y = 0;
  18473. this.rotation.z = 0;
  18474. this.rotationAutoUpdate = false;
  18475. };
  18476. /**
  18477. * @author hughes
  18478. */
  18479. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18480. THREE.Geometry.call( this );
  18481. radius = radius || 50;
  18482. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18483. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18484. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18485. var i, uvs = [],
  18486. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18487. this.vertices.push(center);
  18488. uvs.push( centerUV );
  18489. for ( i = 0; i <= segments; i ++ ) {
  18490. var vertex = new THREE.Vector3();
  18491. var segment = thetaStart + i / segments * thetaLength;
  18492. vertex.x = radius * Math.cos( segment );
  18493. vertex.y = radius * Math.sin( segment );
  18494. this.vertices.push( vertex );
  18495. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  18496. }
  18497. var n = new THREE.Vector3( 0, 0, 1 );
  18498. for ( i = 1; i <= segments; i ++ ) {
  18499. var v1 = i;
  18500. var v2 = i + 1 ;
  18501. var v3 = 0;
  18502. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  18503. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  18504. }
  18505. this.computeCentroids();
  18506. this.computeFaceNormals();
  18507. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18508. };
  18509. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18510. /**
  18511. * @author mrdoob / http://mrdoob.com/
  18512. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18513. */
  18514. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18515. THREE.Geometry.call( this );
  18516. var scope = this;
  18517. this.width = width;
  18518. this.height = height;
  18519. this.depth = depth;
  18520. this.widthSegments = widthSegments || 1;
  18521. this.heightSegments = heightSegments || 1;
  18522. this.depthSegments = depthSegments || 1;
  18523. var width_half = this.width / 2;
  18524. var height_half = this.height / 2;
  18525. var depth_half = this.depth / 2;
  18526. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18527. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18528. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18529. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18530. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18531. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18532. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18533. var w, ix, iy,
  18534. gridX = scope.widthSegments,
  18535. gridY = scope.heightSegments,
  18536. width_half = width / 2,
  18537. height_half = height / 2,
  18538. offset = scope.vertices.length;
  18539. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18540. w = 'z';
  18541. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18542. w = 'y';
  18543. gridY = scope.depthSegments;
  18544. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18545. w = 'x';
  18546. gridX = scope.depthSegments;
  18547. }
  18548. var gridX1 = gridX + 1,
  18549. gridY1 = gridY + 1,
  18550. segment_width = width / gridX,
  18551. segment_height = height / gridY,
  18552. normal = new THREE.Vector3();
  18553. normal[ w ] = depth > 0 ? 1 : - 1;
  18554. for ( iy = 0; iy < gridY1; iy ++ ) {
  18555. for ( ix = 0; ix < gridX1; ix ++ ) {
  18556. var vector = new THREE.Vector3();
  18557. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18558. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18559. vector[ w ] = depth;
  18560. scope.vertices.push( vector );
  18561. }
  18562. }
  18563. for ( iy = 0; iy < gridY; iy++ ) {
  18564. for ( ix = 0; ix < gridX; ix++ ) {
  18565. var a = ix + gridX1 * iy;
  18566. var b = ix + gridX1 * ( iy + 1 );
  18567. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18568. var d = ( ix + 1 ) + gridX1 * iy;
  18569. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  18570. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  18571. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  18572. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  18573. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  18574. face.normal.copy( normal );
  18575. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18576. face.materialIndex = materialIndex;
  18577. scope.faces.push( face );
  18578. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  18579. face = new THREE.Face3( b + offset, c + offset, d + offset );
  18580. face.normal.copy( normal );
  18581. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18582. face.materialIndex = materialIndex;
  18583. scope.faces.push( face );
  18584. scope.faceVertexUvs[ 0 ].push( [ uvb, uvc, uvd ] );
  18585. }
  18586. }
  18587. }
  18588. this.computeCentroids();
  18589. this.mergeVertices();
  18590. };
  18591. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18592. /**
  18593. * @author mrdoob / http://mrdoob.com/
  18594. */
  18595. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  18596. THREE.Geometry.call( this );
  18597. this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18598. this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18599. this.height = height = height !== undefined ? height : 100;
  18600. this.radialSegments = radialSegments = radialSegments || 8;
  18601. this.heightSegments = heightSegments = heightSegments || 1;
  18602. this.openEnded = openEnded = openEnded !== undefined ? openEnded : false;
  18603. var heightHalf = height / 2;
  18604. var x, y, vertices = [], uvs = [];
  18605. for ( y = 0; y <= heightSegments; y ++ ) {
  18606. var verticesRow = [];
  18607. var uvsRow = [];
  18608. var v = y / heightSegments;
  18609. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18610. for ( x = 0; x <= radialSegments; x ++ ) {
  18611. var u = x / radialSegments;
  18612. var vertex = new THREE.Vector3();
  18613. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18614. vertex.y = - v * height + heightHalf;
  18615. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18616. this.vertices.push( vertex );
  18617. verticesRow.push( this.vertices.length - 1 );
  18618. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18619. }
  18620. vertices.push( verticesRow );
  18621. uvs.push( uvsRow );
  18622. }
  18623. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18624. var na, nb;
  18625. for ( x = 0; x < radialSegments; x ++ ) {
  18626. if ( radiusTop !== 0 ) {
  18627. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18628. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18629. } else {
  18630. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18631. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18632. }
  18633. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18634. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18635. for ( y = 0; y < heightSegments; y ++ ) {
  18636. var v1 = vertices[ y ][ x ];
  18637. var v2 = vertices[ y + 1 ][ x ];
  18638. var v3 = vertices[ y + 1 ][ x + 1 ];
  18639. var v4 = vertices[ y ][ x + 1 ];
  18640. var n1 = na.clone();
  18641. var n2 = na.clone();
  18642. var n3 = nb.clone();
  18643. var n4 = nb.clone();
  18644. var uv1 = uvs[ y ][ x ].clone();
  18645. var uv2 = uvs[ y + 1 ][ x ].clone();
  18646. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18647. var uv4 = uvs[ y ][ x + 1 ].clone();
  18648. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  18649. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  18650. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2, n3, n4 ] ) );
  18651. this.faceVertexUvs[ 0 ].push( [ uv2, uv3, uv4 ] );
  18652. }
  18653. }
  18654. // top cap
  18655. if ( openEnded === false && radiusTop > 0 ) {
  18656. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18657. for ( x = 0; x < radialSegments; x ++ ) {
  18658. var v1 = vertices[ 0 ][ x ];
  18659. var v2 = vertices[ 0 ][ x + 1 ];
  18660. var v3 = this.vertices.length - 1;
  18661. var n1 = new THREE.Vector3( 0, 1, 0 );
  18662. var n2 = new THREE.Vector3( 0, 1, 0 );
  18663. var n3 = new THREE.Vector3( 0, 1, 0 );
  18664. var uv1 = uvs[ 0 ][ x ].clone();
  18665. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18666. var uv3 = new THREE.Vector2( uv2.u, 0 );
  18667. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18668. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18669. }
  18670. }
  18671. // bottom cap
  18672. if ( openEnded === false && radiusBottom > 0 ) {
  18673. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18674. for ( x = 0; x < radialSegments; x ++ ) {
  18675. var v1 = vertices[ y ][ x + 1 ];
  18676. var v2 = vertices[ y ][ x ];
  18677. var v3 = this.vertices.length - 1;
  18678. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18679. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18680. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18681. var uv1 = uvs[ y ][ x + 1 ].clone();
  18682. var uv2 = uvs[ y ][ x ].clone();
  18683. var uv3 = new THREE.Vector2( uv2.u, 1 );
  18684. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18685. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18686. }
  18687. }
  18688. this.computeCentroids();
  18689. this.computeFaceNormals();
  18690. }
  18691. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18692. /**
  18693. * @author zz85 / http://www.lab4games.net/zz85/blog
  18694. *
  18695. * Creates extruded geometry from a path shape.
  18696. *
  18697. * parameters = {
  18698. *
  18699. * size: <float>, // size of the text
  18700. * height: <float>, // thickness to extrude text
  18701. * curveSegments: <int>, // number of points on the curves
  18702. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18703. * amount: <int>, // Amount
  18704. *
  18705. * bevelEnabled: <bool>, // turn on bevel
  18706. * bevelThickness: <float>, // how deep into text bevel goes
  18707. * bevelSize: <float>, // how far from text outline is bevel
  18708. * bevelSegments: <int>, // number of bevel layers
  18709. *
  18710. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18711. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18712. *
  18713. * material: <int> // material index for front and back faces
  18714. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18715. * uvGenerator: <Object> // object that provides UV generator functions
  18716. *
  18717. * }
  18718. **/
  18719. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18720. if ( typeof( shapes ) === "undefined" ) {
  18721. shapes = [];
  18722. return;
  18723. }
  18724. THREE.Geometry.call( this );
  18725. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18726. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18727. this.addShapeList( shapes, options );
  18728. this.computeCentroids();
  18729. this.computeFaceNormals();
  18730. // can't really use automatic vertex normals
  18731. // as then front and back sides get smoothed too
  18732. // should do separate smoothing just for sides
  18733. //this.computeVertexNormals();
  18734. //console.log( "took", ( Date.now() - startTime ) );
  18735. };
  18736. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18737. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18738. var sl = shapes.length;
  18739. for ( var s = 0; s < sl; s ++ ) {
  18740. var shape = shapes[ s ];
  18741. this.addShape( shape, options );
  18742. }
  18743. };
  18744. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18745. var amount = options.amount !== undefined ? options.amount : 100;
  18746. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18747. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18748. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18749. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18750. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18751. var steps = options.steps !== undefined ? options.steps : 1;
  18752. var extrudePath = options.extrudePath;
  18753. var extrudePts, extrudeByPath = false;
  18754. var material = options.material;
  18755. var extrudeMaterial = options.extrudeMaterial;
  18756. // Use default WorldUVGenerator if no UV generators are specified.
  18757. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18758. var shapebb = this.shapebb;
  18759. //shapebb = shape.getBoundingBox();
  18760. var splineTube, binormal, normal, position2;
  18761. if ( extrudePath ) {
  18762. extrudePts = extrudePath.getSpacedPoints( steps );
  18763. extrudeByPath = true;
  18764. bevelEnabled = false; // bevels not supported for path extrusion
  18765. // SETUP TNB variables
  18766. // Reuse TNB from TubeGeomtry for now.
  18767. // TODO1 - have a .isClosed in spline?
  18768. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18769. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18770. binormal = new THREE.Vector3();
  18771. normal = new THREE.Vector3();
  18772. position2 = new THREE.Vector3();
  18773. }
  18774. // Safeguards if bevels are not enabled
  18775. if ( ! bevelEnabled ) {
  18776. bevelSegments = 0;
  18777. bevelThickness = 0;
  18778. bevelSize = 0;
  18779. }
  18780. // Variables initalization
  18781. var ahole, h, hl; // looping of holes
  18782. var scope = this;
  18783. var bevelPoints = [];
  18784. var shapesOffset = this.vertices.length;
  18785. var shapePoints = shape.extractPoints( curveSegments );
  18786. var vertices = shapePoints.shape;
  18787. var holes = shapePoints.holes;
  18788. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18789. if ( reverse ) {
  18790. vertices = vertices.reverse();
  18791. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18792. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18793. ahole = holes[ h ];
  18794. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18795. holes[ h ] = ahole.reverse();
  18796. }
  18797. }
  18798. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18799. }
  18800. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18801. /* Vertices */
  18802. var contour = vertices; // vertices has all points but contour has only points of circumference
  18803. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18804. ahole = holes[ h ];
  18805. vertices = vertices.concat( ahole );
  18806. }
  18807. function scalePt2 ( pt, vec, size ) {
  18808. if ( !vec ) console.log( "die" );
  18809. return vec.clone().multiplyScalar( size ).add( pt );
  18810. }
  18811. var b, bs, t, z,
  18812. vert, vlen = vertices.length,
  18813. face, flen = faces.length,
  18814. cont, clen = contour.length;
  18815. // Find directions for point movement
  18816. var RAD_TO_DEGREES = 180 / Math.PI;
  18817. function getBevelVec( pt_i, pt_j, pt_k ) {
  18818. // Algorithm 2
  18819. return getBevelVec2( pt_i, pt_j, pt_k );
  18820. }
  18821. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18822. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18823. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18824. if ( anglea > angleb ) {
  18825. angleb += Math.PI * 2;
  18826. }
  18827. var anglec = ( anglea + angleb ) / 2;
  18828. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18829. var x = - Math.cos( anglec );
  18830. var y = - Math.sin( anglec );
  18831. var vec = new THREE.Vector2( x, y ); //.normalize();
  18832. return vec;
  18833. }
  18834. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18835. var a = THREE.ExtrudeGeometry.__v1,
  18836. b = THREE.ExtrudeGeometry.__v2,
  18837. v_hat = THREE.ExtrudeGeometry.__v3,
  18838. w_hat = THREE.ExtrudeGeometry.__v4,
  18839. p = THREE.ExtrudeGeometry.__v5,
  18840. q = THREE.ExtrudeGeometry.__v6,
  18841. v, w,
  18842. v_dot_w_hat, q_sub_p_dot_w_hat,
  18843. s, intersection;
  18844. // good reading for line-line intersection
  18845. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18846. // define a as vector j->i
  18847. // define b as vectot k->i
  18848. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18849. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18850. // get unit vectors
  18851. v = a.normalize();
  18852. w = b.normalize();
  18853. // normals from pt i
  18854. v_hat.set( -v.y, v.x );
  18855. w_hat.set( w.y, -w.x );
  18856. // pts from i
  18857. p.copy( pt_i ).add( v_hat );
  18858. q.copy( pt_i ).add( w_hat );
  18859. if ( p.equals( q ) ) {
  18860. //console.log("Warning: lines are straight");
  18861. return w_hat.clone();
  18862. }
  18863. // Points from j, k. helps prevents points cross overover most of the time
  18864. p.copy( pt_j ).add( v_hat );
  18865. q.copy( pt_k ).add( w_hat );
  18866. v_dot_w_hat = v.dot( w_hat );
  18867. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  18868. // We should not reach these conditions
  18869. if ( v_dot_w_hat === 0 ) {
  18870. console.log( "Either infinite or no solutions!" );
  18871. if ( q_sub_p_dot_w_hat === 0 ) {
  18872. console.log( "Its finite solutions." );
  18873. } else {
  18874. console.log( "Too bad, no solutions." );
  18875. }
  18876. }
  18877. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18878. if ( s < 0 ) {
  18879. // in case of emergecy, revert to algorithm 1.
  18880. return getBevelVec1( pt_i, pt_j, pt_k );
  18881. }
  18882. intersection = v.multiplyScalar( s ).add( p );
  18883. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18884. }
  18885. var contourMovements = [];
  18886. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18887. if ( j === il ) j = 0;
  18888. if ( k === il ) k = 0;
  18889. // (j)---(i)---(k)
  18890. // console.log('i,j,k', i, j , k)
  18891. var pt_i = contour[ i ];
  18892. var pt_j = contour[ j ];
  18893. var pt_k = contour[ k ];
  18894. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18895. }
  18896. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18897. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18898. ahole = holes[ h ];
  18899. oneHoleMovements = [];
  18900. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18901. if ( j === il ) j = 0;
  18902. if ( k === il ) k = 0;
  18903. // (j)---(i)---(k)
  18904. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18905. }
  18906. holesMovements.push( oneHoleMovements );
  18907. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18908. }
  18909. // Loop bevelSegments, 1 for the front, 1 for the back
  18910. for ( b = 0; b < bevelSegments; b ++ ) {
  18911. //for ( b = bevelSegments; b > 0; b -- ) {
  18912. t = b / bevelSegments;
  18913. z = bevelThickness * ( 1 - t );
  18914. //z = bevelThickness * t;
  18915. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18916. //bs = bevelSize * t ; // linear
  18917. // contract shape
  18918. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18919. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18920. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18921. v( vert.x, vert.y, - z );
  18922. }
  18923. // expand holes
  18924. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18925. ahole = holes[ h ];
  18926. oneHoleMovements = holesMovements[ h ];
  18927. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18928. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18929. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18930. v( vert.x, vert.y, -z );
  18931. }
  18932. }
  18933. }
  18934. bs = bevelSize;
  18935. // Back facing vertices
  18936. for ( i = 0; i < vlen; i ++ ) {
  18937. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18938. if ( !extrudeByPath ) {
  18939. v( vert.x, vert.y, 0 );
  18940. } else {
  18941. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18942. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18943. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18944. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  18945. v( position2.x, position2.y, position2.z );
  18946. }
  18947. }
  18948. // Add stepped vertices...
  18949. // Including front facing vertices
  18950. var s;
  18951. for ( s = 1; s <= steps; s ++ ) {
  18952. for ( i = 0; i < vlen; i ++ ) {
  18953. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18954. if ( !extrudeByPath ) {
  18955. v( vert.x, vert.y, amount / steps * s );
  18956. } else {
  18957. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18958. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18959. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18960. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  18961. v( position2.x, position2.y, position2.z );
  18962. }
  18963. }
  18964. }
  18965. // Add bevel segments planes
  18966. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18967. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18968. t = b / bevelSegments;
  18969. z = bevelThickness * ( 1 - t );
  18970. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18971. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18972. // contract shape
  18973. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18974. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18975. v( vert.x, vert.y, amount + z );
  18976. }
  18977. // expand holes
  18978. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18979. ahole = holes[ h ];
  18980. oneHoleMovements = holesMovements[ h ];
  18981. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18982. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18983. if ( !extrudeByPath ) {
  18984. v( vert.x, vert.y, amount + z );
  18985. } else {
  18986. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18987. }
  18988. }
  18989. }
  18990. }
  18991. /* Faces */
  18992. // Top and bottom faces
  18993. buildLidFaces();
  18994. // Sides faces
  18995. buildSideFaces();
  18996. ///// Internal functions
  18997. function buildLidFaces() {
  18998. if ( bevelEnabled ) {
  18999. var layer = 0 ; // steps + 1
  19000. var offset = vlen * layer;
  19001. // Bottom faces
  19002. for ( i = 0; i < flen; i ++ ) {
  19003. face = faces[ i ];
  19004. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19005. }
  19006. layer = steps + bevelSegments * 2;
  19007. offset = vlen * layer;
  19008. // Top faces
  19009. for ( i = 0; i < flen; i ++ ) {
  19010. face = faces[ i ];
  19011. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19012. }
  19013. } else {
  19014. // Bottom faces
  19015. for ( i = 0; i < flen; i++ ) {
  19016. face = faces[ i ];
  19017. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19018. }
  19019. // Top faces
  19020. for ( i = 0; i < flen; i ++ ) {
  19021. face = faces[ i ];
  19022. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19023. }
  19024. }
  19025. }
  19026. // Create faces for the z-sides of the shape
  19027. function buildSideFaces() {
  19028. var layeroffset = 0;
  19029. sidewalls( contour, layeroffset );
  19030. layeroffset += contour.length;
  19031. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19032. ahole = holes[ h ];
  19033. sidewalls( ahole, layeroffset );
  19034. //, true
  19035. layeroffset += ahole.length;
  19036. }
  19037. }
  19038. function sidewalls( contour, layeroffset ) {
  19039. var j, k;
  19040. i = contour.length;
  19041. while ( --i >= 0 ) {
  19042. j = i;
  19043. k = i - 1;
  19044. if ( k < 0 ) k = contour.length - 1;
  19045. //console.log('b', i,j, i-1, k,vertices.length);
  19046. var s = 0, sl = steps + bevelSegments * 2;
  19047. for ( s = 0; s < sl; s ++ ) {
  19048. var slen1 = vlen * s;
  19049. var slen2 = vlen * ( s + 1 );
  19050. var a = layeroffset + j + slen1,
  19051. b = layeroffset + k + slen1,
  19052. c = layeroffset + k + slen2,
  19053. d = layeroffset + j + slen2;
  19054. f4( a, b, c, d, contour, s, sl, j, k );
  19055. }
  19056. }
  19057. }
  19058. function v( x, y, z ) {
  19059. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19060. }
  19061. function f3( a, b, c, isBottom ) {
  19062. a += shapesOffset;
  19063. b += shapesOffset;
  19064. c += shapesOffset;
  19065. // normal, color, material
  19066. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19067. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19068. scope.faceVertexUvs[ 0 ].push( uvs );
  19069. }
  19070. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19071. a += shapesOffset;
  19072. b += shapesOffset;
  19073. c += shapesOffset;
  19074. d += shapesOffset;
  19075. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  19076. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  19077. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19078. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19079. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  19080. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  19081. }
  19082. };
  19083. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19084. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19085. var ax = geometry.vertices[ indexA ].x,
  19086. ay = geometry.vertices[ indexA ].y,
  19087. bx = geometry.vertices[ indexB ].x,
  19088. by = geometry.vertices[ indexB ].y,
  19089. cx = geometry.vertices[ indexC ].x,
  19090. cy = geometry.vertices[ indexC ].y;
  19091. return [
  19092. new THREE.Vector2( ax, ay ),
  19093. new THREE.Vector2( bx, by ),
  19094. new THREE.Vector2( cx, cy )
  19095. ];
  19096. },
  19097. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19098. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19099. },
  19100. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19101. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19102. contourIndex1, contourIndex2 ) {
  19103. var ax = geometry.vertices[ indexA ].x,
  19104. ay = geometry.vertices[ indexA ].y,
  19105. az = geometry.vertices[ indexA ].z,
  19106. bx = geometry.vertices[ indexB ].x,
  19107. by = geometry.vertices[ indexB ].y,
  19108. bz = geometry.vertices[ indexB ].z,
  19109. cx = geometry.vertices[ indexC ].x,
  19110. cy = geometry.vertices[ indexC ].y,
  19111. cz = geometry.vertices[ indexC ].z,
  19112. dx = geometry.vertices[ indexD ].x,
  19113. dy = geometry.vertices[ indexD ].y,
  19114. dz = geometry.vertices[ indexD ].z;
  19115. if ( Math.abs( ay - by ) < 0.01 ) {
  19116. return [
  19117. new THREE.Vector2( ax, 1 - az ),
  19118. new THREE.Vector2( bx, 1 - bz ),
  19119. new THREE.Vector2( cx, 1 - cz ),
  19120. new THREE.Vector2( dx, 1 - dz )
  19121. ];
  19122. } else {
  19123. return [
  19124. new THREE.Vector2( ay, 1 - az ),
  19125. new THREE.Vector2( by, 1 - bz ),
  19126. new THREE.Vector2( cy, 1 - cz ),
  19127. new THREE.Vector2( dy, 1 - dz )
  19128. ];
  19129. }
  19130. }
  19131. };
  19132. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19133. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19134. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19135. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19136. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19137. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19138. /**
  19139. * @author jonobr1 / http://jonobr1.com
  19140. *
  19141. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19142. * ExtrudeGeometry.
  19143. *
  19144. * parameters = {
  19145. *
  19146. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19147. *
  19148. * material: <int> // material index for front and back faces
  19149. * uvGenerator: <Object> // object that provides UV generator functions
  19150. *
  19151. * }
  19152. **/
  19153. THREE.ShapeGeometry = function ( shapes, options ) {
  19154. THREE.Geometry.call( this );
  19155. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19156. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19157. this.addShapeList( shapes, options );
  19158. this.computeCentroids();
  19159. this.computeFaceNormals();
  19160. };
  19161. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19162. /**
  19163. * Add an array of shapes to THREE.ShapeGeometry.
  19164. */
  19165. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19166. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19167. this.addShape( shapes[ i ], options );
  19168. }
  19169. return this;
  19170. };
  19171. /**
  19172. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19173. */
  19174. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19175. if ( options === undefined ) options = {};
  19176. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19177. var material = options.material;
  19178. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19179. var shapebb = this.shapebb;
  19180. //
  19181. var i, l, hole, s;
  19182. var shapesOffset = this.vertices.length;
  19183. var shapePoints = shape.extractPoints( curveSegments );
  19184. var vertices = shapePoints.shape;
  19185. var holes = shapePoints.holes;
  19186. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19187. if ( reverse ) {
  19188. vertices = vertices.reverse();
  19189. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19190. for ( i = 0, l = holes.length; i < l; i++ ) {
  19191. hole = holes[ i ];
  19192. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19193. holes[ i ] = hole.reverse();
  19194. }
  19195. }
  19196. reverse = false;
  19197. }
  19198. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19199. // Vertices
  19200. var contour = vertices;
  19201. for ( i = 0, l = holes.length; i < l; i++ ) {
  19202. hole = holes[ i ];
  19203. vertices = vertices.concat( hole );
  19204. }
  19205. //
  19206. var vert, vlen = vertices.length;
  19207. var face, flen = faces.length;
  19208. var cont, clen = contour.length;
  19209. for ( i = 0; i < vlen; i++ ) {
  19210. vert = vertices[ i ];
  19211. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19212. }
  19213. for ( i = 0; i < flen; i++ ) {
  19214. face = faces[ i ];
  19215. var a = face[ 0 ] + shapesOffset;
  19216. var b = face[ 1 ] + shapesOffset;
  19217. var c = face[ 2 ] + shapesOffset;
  19218. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19219. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19220. }
  19221. };
  19222. /**
  19223. * @author astrodud / http://astrodud.isgreat.org/
  19224. * @author zz85 / https://github.com/zz85
  19225. * @author bhouston / http://exocortex.com
  19226. */
  19227. // points - to create a closed torus, one must use a set of points
  19228. // like so: [ a, b, c, d, a ], see first is the same as last.
  19229. // segments - the number of circumference segments to create
  19230. // phiStart - the starting radian
  19231. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19232. // 2*pi is a closed lathe, less than 2PI is a portion.
  19233. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19234. THREE.Geometry.call( this );
  19235. segments = segments || 12;
  19236. phiStart = phiStart || 0;
  19237. phiLength = phiLength || 2 * Math.PI;
  19238. var inversePointLength = 1.0 / ( points.length - 1 );
  19239. var inverseSegments = 1.0 / segments;
  19240. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19241. var phi = phiStart + i * inverseSegments * phiLength;
  19242. var c = Math.cos( phi ),
  19243. s = Math.sin( phi );
  19244. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19245. var pt = points[ j ];
  19246. var vertex = new THREE.Vector3();
  19247. vertex.x = c * pt.x - s * pt.y;
  19248. vertex.y = s * pt.x + c * pt.y;
  19249. vertex.z = pt.z;
  19250. this.vertices.push( vertex );
  19251. }
  19252. }
  19253. var np = points.length;
  19254. for ( var i = 0, il = segments; i < il; i ++ ) {
  19255. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19256. var base = j + np * i;
  19257. var a = base;
  19258. var b = base + np;
  19259. var c = base + 1 + np;
  19260. var d = base + 1;
  19261. var u0 = i * inverseSegments;
  19262. var v0 = j * inversePointLength;
  19263. var u1 = u0 + inverseSegments;
  19264. var v1 = v0 + inversePointLength;
  19265. this.faces.push( new THREE.Face3( a, b, d ) );
  19266. this.faceVertexUvs[ 0 ].push( [
  19267. new THREE.Vector2( u0, v0 ),
  19268. new THREE.Vector2( u1, v0 ),
  19269. new THREE.Vector2( u0, v1 )
  19270. ] );
  19271. this.faces.push( new THREE.Face3( b, c, d ) );
  19272. this.faceVertexUvs[ 0 ].push( [
  19273. new THREE.Vector2( u1, v0 ),
  19274. new THREE.Vector2( u1, v1 ),
  19275. new THREE.Vector2( u0, v1 )
  19276. ] );
  19277. }
  19278. }
  19279. this.mergeVertices();
  19280. this.computeCentroids();
  19281. this.computeFaceNormals();
  19282. this.computeVertexNormals();
  19283. };
  19284. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19285. /**
  19286. * @author mrdoob / http://mrdoob.com/
  19287. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19288. */
  19289. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19290. THREE.Geometry.call( this );
  19291. this.width = width;
  19292. this.height = height;
  19293. this.widthSegments = widthSegments || 1;
  19294. this.heightSegments = heightSegments || 1;
  19295. var ix, iz;
  19296. var width_half = width / 2;
  19297. var height_half = height / 2;
  19298. var gridX = this.widthSegments;
  19299. var gridZ = this.heightSegments;
  19300. var gridX1 = gridX + 1;
  19301. var gridZ1 = gridZ + 1;
  19302. var segment_width = this.width / gridX;
  19303. var segment_height = this.height / gridZ;
  19304. var normal = new THREE.Vector3( 0, 0, 1 );
  19305. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19306. for ( ix = 0; ix < gridX1; ix ++ ) {
  19307. var x = ix * segment_width - width_half;
  19308. var y = iz * segment_height - height_half;
  19309. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19310. }
  19311. }
  19312. for ( iz = 0; iz < gridZ; iz ++ ) {
  19313. for ( ix = 0; ix < gridX; ix ++ ) {
  19314. var a = ix + gridX1 * iz;
  19315. var b = ix + gridX1 * ( iz + 1 );
  19316. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19317. var d = ( ix + 1 ) + gridX1 * iz;
  19318. var uva = new THREE.Vector2( ix / gridX, 1 - iz / gridZ );
  19319. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ );
  19320. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ );
  19321. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ );
  19322. var face = new THREE.Face3( a, b, d );
  19323. face.normal.copy( normal );
  19324. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19325. this.faces.push( face );
  19326. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19327. face = new THREE.Face3( b, c, d );
  19328. face.normal.copy( normal );
  19329. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19330. this.faces.push( face );
  19331. this.faceVertexUvs[ 0 ].push( [ uvb, uvc, uvd ] );
  19332. }
  19333. }
  19334. this.computeCentroids();
  19335. };
  19336. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19337. /**
  19338. * @author Kaleb Murphy
  19339. */
  19340. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19341. THREE.Geometry.call( this );
  19342. innerRadius = innerRadius || 0;
  19343. outerRadius = outerRadius || 50;
  19344. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19345. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19346. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19347. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19348. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19349. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19350. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19351. var vertex = new THREE.Vector3();
  19352. var segment = thetaStart + o / thetaSegments * thetaLength;
  19353. vertex.x = radius * Math.cos( segment );
  19354. vertex.y = radius * Math.sin( segment );
  19355. this.vertices.push( vertex );
  19356. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  19357. }
  19358. radius += radiusStep;
  19359. }
  19360. var n = new THREE.Vector3( 0, 0, 1 );
  19361. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19362. var thetaSegment = i * thetaSegments;
  19363. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19364. var segment = o + thetaSegment;
  19365. var v1 = segment + i;
  19366. var v2 = segment + thetaSegments + i;
  19367. var v3 = segment + thetaSegments + 1 + i;
  19368. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19369. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19370. v1 = segment + i;
  19371. v2 = segment + thetaSegments + 1 + i;
  19372. v3 = segment + 1 + i;
  19373. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19374. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19375. }
  19376. }
  19377. this.computeCentroids();
  19378. this.computeFaceNormals();
  19379. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19380. };
  19381. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19382. /**
  19383. * @author mrdoob / http://mrdoob.com/
  19384. */
  19385. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19386. THREE.Geometry.call( this );
  19387. this.radius = radius = radius || 50;
  19388. this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19389. this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19390. this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0;
  19391. this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19392. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19393. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19394. var x, y, vertices = [], uvs = [];
  19395. for ( y = 0; y <= heightSegments; y ++ ) {
  19396. var verticesRow = [];
  19397. var uvsRow = [];
  19398. for ( x = 0; x <= widthSegments; x ++ ) {
  19399. var u = x / widthSegments;
  19400. var v = y / heightSegments;
  19401. var vertex = new THREE.Vector3();
  19402. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19403. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19404. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19405. this.vertices.push( vertex );
  19406. verticesRow.push( this.vertices.length - 1 );
  19407. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19408. }
  19409. vertices.push( verticesRow );
  19410. uvs.push( uvsRow );
  19411. }
  19412. for ( y = 0; y < this.heightSegments; y ++ ) {
  19413. for ( x = 0; x < this.widthSegments; x ++ ) {
  19414. var v1 = vertices[ y ][ x + 1 ];
  19415. var v2 = vertices[ y ][ x ];
  19416. var v3 = vertices[ y + 1 ][ x ];
  19417. var v4 = vertices[ y + 1 ][ x + 1 ];
  19418. var n1 = this.vertices[ v1 ].clone().normalize();
  19419. var n2 = this.vertices[ v2 ].clone().normalize();
  19420. var n3 = this.vertices[ v3 ].clone().normalize();
  19421. var n4 = this.vertices[ v4 ].clone().normalize();
  19422. var uv1 = uvs[ y ][ x + 1 ].clone();
  19423. var uv2 = uvs[ y ][ x ].clone();
  19424. var uv3 = uvs[ y + 1 ][ x ].clone();
  19425. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19426. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19427. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19428. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19429. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19430. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19431. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19432. } else {
  19433. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19434. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19435. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2, n3, n4 ] ) );
  19436. this.faceVertexUvs[ 0 ].push( [ uv2, uv3, uv4 ] );
  19437. }
  19438. }
  19439. }
  19440. this.computeCentroids();
  19441. this.computeFaceNormals();
  19442. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19443. };
  19444. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19445. /**
  19446. * @author zz85 / http://www.lab4games.net/zz85/blog
  19447. * @author alteredq / http://alteredqualia.com/
  19448. *
  19449. * For creating 3D text geometry in three.js
  19450. *
  19451. * Text = 3D Text
  19452. *
  19453. * parameters = {
  19454. * size: <float>, // size of the text
  19455. * height: <float>, // thickness to extrude text
  19456. * curveSegments: <int>, // number of points on the curves
  19457. *
  19458. * font: <string>, // font name
  19459. * weight: <string>, // font weight (normal, bold)
  19460. * style: <string>, // font style (normal, italics)
  19461. *
  19462. * bevelEnabled: <bool>, // turn on bevel
  19463. * bevelThickness: <float>, // how deep into text bevel goes
  19464. * bevelSize: <float>, // how far from text outline is bevel
  19465. * }
  19466. *
  19467. */
  19468. /* Usage Examples
  19469. // TextGeometry wrapper
  19470. var text3d = new TextGeometry( text, options );
  19471. // Complete manner
  19472. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19473. var text3d = new ExtrudeGeometry( textShapes, options );
  19474. */
  19475. THREE.TextGeometry = function ( text, parameters ) {
  19476. parameters = parameters || {};
  19477. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19478. // translate parameters to ExtrudeGeometry API
  19479. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19480. // defaults
  19481. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19482. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19483. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19484. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19485. };
  19486. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19487. /**
  19488. * @author oosmoxiecode
  19489. * @author mrdoob / http://mrdoob.com/
  19490. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19491. */
  19492. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19493. THREE.Geometry.call( this );
  19494. var scope = this;
  19495. this.radius = radius || 100;
  19496. this.tube = tube || 40;
  19497. this.radialSegments = radialSegments || 8;
  19498. this.tubularSegments = tubularSegments || 6;
  19499. this.arc = arc || Math.PI * 2;
  19500. var center = new THREE.Vector3(), uvs = [], normals = [];
  19501. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19502. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19503. var u = i / this.tubularSegments * this.arc;
  19504. var v = j / this.radialSegments * Math.PI * 2;
  19505. center.x = this.radius * Math.cos( u );
  19506. center.y = this.radius * Math.sin( u );
  19507. var vertex = new THREE.Vector3();
  19508. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19509. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19510. vertex.z = this.tube * Math.sin( v );
  19511. this.vertices.push( vertex );
  19512. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19513. normals.push( vertex.clone().sub( center ).normalize() );
  19514. }
  19515. }
  19516. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19517. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19518. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19519. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19520. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19521. var d = ( this.tubularSegments + 1 ) * j + i;
  19522. var face = new THREE.Face3( a, b, d, [ normals[ a ], normals[ b ], normals[ d ] ] );
  19523. face.normal.add( normals[ a ] );
  19524. face.normal.add( normals[ b ] );
  19525. face.normal.add( normals[ d ] );
  19526. face.normal.normalize();
  19527. this.faces.push( face );
  19528. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  19529. face = new THREE.Face3( b, c, d, [ normals[ b ], normals[ c ], normals[ d ] ] );
  19530. face.normal.add( normals[ b ] );
  19531. face.normal.add( normals[ c ] );
  19532. face.normal.add( normals[ d ] );
  19533. face.normal.normalize();
  19534. this.faces.push( face );
  19535. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19536. }
  19537. }
  19538. this.computeCentroids();
  19539. };
  19540. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19541. /**
  19542. * @author oosmoxiecode
  19543. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19544. */
  19545. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19546. THREE.Geometry.call( this );
  19547. var scope = this;
  19548. this.radius = radius || 100;
  19549. this.tube = tube || 40;
  19550. this.radialSegments = radialSegments || 64;
  19551. this.tubularSegments = tubularSegments || 8;
  19552. this.p = p || 2;
  19553. this.q = q || 3;
  19554. this.heightScale = heightScale || 1;
  19555. this.grid = new Array( this.radialSegments );
  19556. var tang = new THREE.Vector3();
  19557. var n = new THREE.Vector3();
  19558. var bitan = new THREE.Vector3();
  19559. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19560. this.grid[ i ] = new Array( this.tubularSegments );
  19561. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19562. var p1 = getPos( u, this.q, this.p, this.radius, this.heightScale );
  19563. var p2 = getPos( u + 0.01, this.q, this.p, this.radius, this.heightScale );
  19564. tang.subVectors( p2, p1 );
  19565. n.addVectors( p2, p1 );
  19566. bitan.crossVectors( tang, n );
  19567. n.crossVectors( bitan, tang );
  19568. bitan.normalize();
  19569. n.normalize();
  19570. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19571. var v = j / this.tubularSegments * 2 * Math.PI;
  19572. var cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19573. var cy = this.tube * Math.sin( v );
  19574. var pos = new THREE.Vector3();
  19575. pos.x = p1.x + cx * n.x + cy * bitan.x;
  19576. pos.y = p1.y + cx * n.y + cy * bitan.y;
  19577. pos.z = p1.z + cx * n.z + cy * bitan.z;
  19578. this.grid[ i ][ j ] = scope.vertices.push( pos ) - 1;
  19579. }
  19580. }
  19581. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19582. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19583. var ip = ( i + 1 ) % this.radialSegments;
  19584. var jp = ( j + 1 ) % this.tubularSegments;
  19585. var a = this.grid[ i ][ j ];
  19586. var b = this.grid[ ip ][ j ];
  19587. var c = this.grid[ ip ][ jp ];
  19588. var d = this.grid[ i ][ jp ];
  19589. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19590. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19591. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19592. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19593. this.faces.push( new THREE.Face3( a, b, d ) );
  19594. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19595. this.faces.push( new THREE.Face3( b, c, d ) );
  19596. this.faceVertexUvs[ 0 ].push( [ uvb, uvc, uvd ] );
  19597. }
  19598. }
  19599. this.computeCentroids();
  19600. this.computeFaceNormals();
  19601. this.computeVertexNormals();
  19602. function getPos( u, in_q, in_p, radius, heightScale ) {
  19603. var cu = Math.cos( u );
  19604. var su = Math.sin( u );
  19605. var quOverP = in_q / in_p * u;
  19606. var cs = Math.cos( quOverP );
  19607. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19608. var ty = radius * ( 2 + cs ) * su * 0.5;
  19609. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19610. return new THREE.Vector3( tx, ty, tz );
  19611. }
  19612. };
  19613. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19614. /**
  19615. * @author WestLangley / https://github.com/WestLangley
  19616. * @author zz85 / https://github.com/zz85
  19617. * @author miningold / https://github.com/miningold
  19618. *
  19619. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19620. *
  19621. * Creates a tube which extrudes along a 3d spline
  19622. *
  19623. * Uses parallel transport frames as described in
  19624. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19625. */
  19626. THREE.TubeGeometry = function( path, segments, radius, radialSegments, closed ) {
  19627. THREE.Geometry.call( this );
  19628. this.path = path;
  19629. this.segments = segments || 64;
  19630. this.radius = radius || 1;
  19631. this.radialSegments = radialSegments || 8;
  19632. this.closed = closed || false;
  19633. this.grid = [];
  19634. var scope = this,
  19635. tangent,
  19636. normal,
  19637. binormal,
  19638. numpoints = this.segments + 1,
  19639. x, y, z,
  19640. tx, ty, tz,
  19641. u, v,
  19642. cx, cy,
  19643. pos, pos2 = new THREE.Vector3(),
  19644. i, j,
  19645. ip, jp,
  19646. a, b, c, d,
  19647. uva, uvb, uvc, uvd;
  19648. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19649. tangents = frames.tangents,
  19650. normals = frames.normals,
  19651. binormals = frames.binormals;
  19652. // proxy internals
  19653. this.tangents = tangents;
  19654. this.normals = normals;
  19655. this.binormals = binormals;
  19656. function vert( x, y, z ) {
  19657. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19658. }
  19659. // consruct the grid
  19660. for ( i = 0; i < numpoints; i++ ) {
  19661. this.grid[ i ] = [];
  19662. u = i / ( numpoints - 1 );
  19663. pos = path.getPointAt( u );
  19664. tangent = tangents[ i ];
  19665. normal = normals[ i ];
  19666. binormal = binormals[ i ];
  19667. for ( j = 0; j < this.radialSegments; j++ ) {
  19668. v = j / this.radialSegments * 2 * Math.PI;
  19669. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19670. cy = this.radius * Math.sin( v );
  19671. pos2.copy( pos );
  19672. pos2.x += cx * normal.x + cy * binormal.x;
  19673. pos2.y += cx * normal.y + cy * binormal.y;
  19674. pos2.z += cx * normal.z + cy * binormal.z;
  19675. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19676. }
  19677. }
  19678. // construct the mesh
  19679. for ( i = 0; i < this.segments; i++ ) {
  19680. for ( j = 0; j < this.radialSegments; j++ ) {
  19681. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  19682. jp = (j + 1) % this.radialSegments;
  19683. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19684. b = this.grid[ ip ][ j ];
  19685. c = this.grid[ ip ][ jp ];
  19686. d = this.grid[ i ][ jp ];
  19687. uva = new THREE.Vector2( i / this.segments, j / this.radialSegments );
  19688. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radialSegments );
  19689. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radialSegments );
  19690. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radialSegments );
  19691. this.faces.push( new THREE.Face3( a, b, d ) );
  19692. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19693. this.faces.push( new THREE.Face3( b, c, d ) );
  19694. this.faceVertexUvs[ 0 ].push( [ uvb, uvc, uvd ] );
  19695. }
  19696. }
  19697. this.computeCentroids();
  19698. this.computeFaceNormals();
  19699. this.computeVertexNormals();
  19700. };
  19701. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19702. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19703. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19704. var tangent = new THREE.Vector3(),
  19705. normal = new THREE.Vector3(),
  19706. binormal = new THREE.Vector3(),
  19707. tangents = [],
  19708. normals = [],
  19709. binormals = [],
  19710. vec = new THREE.Vector3(),
  19711. mat = new THREE.Matrix4(),
  19712. numpoints = segments + 1,
  19713. theta,
  19714. epsilon = 0.0001,
  19715. smallest,
  19716. tx, ty, tz,
  19717. i, u, v;
  19718. // expose internals
  19719. this.tangents = tangents;
  19720. this.normals = normals;
  19721. this.binormals = binormals;
  19722. // compute the tangent vectors for each segment on the path
  19723. for ( i = 0; i < numpoints; i++ ) {
  19724. u = i / ( numpoints - 1 );
  19725. tangents[ i ] = path.getTangentAt( u );
  19726. tangents[ i ].normalize();
  19727. }
  19728. initialNormal3();
  19729. function initialNormal1(lastBinormal) {
  19730. // fixed start binormal. Has dangers of 0 vectors
  19731. normals[ 0 ] = new THREE.Vector3();
  19732. binormals[ 0 ] = new THREE.Vector3();
  19733. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19734. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19735. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19736. }
  19737. function initialNormal2() {
  19738. // This uses the Frenet-Serret formula for deriving binormal
  19739. var t2 = path.getTangentAt( epsilon );
  19740. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19741. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19742. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19743. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19744. }
  19745. function initialNormal3() {
  19746. // select an initial normal vector perpenicular to the first tangent vector,
  19747. // and in the direction of the smallest tangent xyz component
  19748. normals[ 0 ] = new THREE.Vector3();
  19749. binormals[ 0 ] = new THREE.Vector3();
  19750. smallest = Number.MAX_VALUE;
  19751. tx = Math.abs( tangents[ 0 ].x );
  19752. ty = Math.abs( tangents[ 0 ].y );
  19753. tz = Math.abs( tangents[ 0 ].z );
  19754. if ( tx <= smallest ) {
  19755. smallest = tx;
  19756. normal.set( 1, 0, 0 );
  19757. }
  19758. if ( ty <= smallest ) {
  19759. smallest = ty;
  19760. normal.set( 0, 1, 0 );
  19761. }
  19762. if ( tz <= smallest ) {
  19763. normal.set( 0, 0, 1 );
  19764. }
  19765. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19766. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19767. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19768. }
  19769. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19770. for ( i = 1; i < numpoints; i++ ) {
  19771. normals[ i ] = normals[ i-1 ].clone();
  19772. binormals[ i ] = binormals[ i-1 ].clone();
  19773. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  19774. if ( vec.length() > epsilon ) {
  19775. vec.normalize();
  19776. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  19777. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19778. }
  19779. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19780. }
  19781. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19782. if ( closed ) {
  19783. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  19784. theta /= ( numpoints - 1 );
  19785. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19786. theta = -theta;
  19787. }
  19788. for ( i = 1; i < numpoints; i++ ) {
  19789. // twist a little...
  19790. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19791. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19792. }
  19793. }
  19794. };
  19795. /**
  19796. * @author clockworkgeek / https://github.com/clockworkgeek
  19797. * @author timothypratley / https://github.com/timothypratley
  19798. * @author WestLangley / http://github.com/WestLangley
  19799. */
  19800. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19801. THREE.Geometry.call( this );
  19802. radius = radius || 1;
  19803. detail = detail || 0;
  19804. var that = this;
  19805. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19806. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19807. }
  19808. var midpoints = [], p = this.vertices;
  19809. var f = [];
  19810. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19811. var v1 = p[ faces[ i ][ 0 ] ];
  19812. var v2 = p[ faces[ i ][ 1 ] ];
  19813. var v3 = p[ faces[ i ][ 2 ] ];
  19814. f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19815. }
  19816. for ( var i = 0, l = f.length; i < l; i ++ ) {
  19817. subdivide(f[ i ], detail);
  19818. }
  19819. // Handle case when face straddles the seam
  19820. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  19821. var uvs = this.faceVertexUvs[ 0 ][ i ];
  19822. var x0 = uvs[ 0 ].x;
  19823. var x1 = uvs[ 1 ].x;
  19824. var x2 = uvs[ 2 ].x;
  19825. var max = Math.max( x0, Math.max( x1, x2 ) );
  19826. var min = Math.min( x0, Math.min( x1, x2 ) );
  19827. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  19828. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  19829. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  19830. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  19831. }
  19832. }
  19833. // Apply radius
  19834. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19835. this.vertices[ i ].multiplyScalar( radius );
  19836. }
  19837. // Merge vertices
  19838. this.mergeVertices();
  19839. this.computeCentroids();
  19840. this.computeFaceNormals();
  19841. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19842. // Project vector onto sphere's surface
  19843. function prepare( vector ) {
  19844. var vertex = vector.normalize().clone();
  19845. vertex.index = that.vertices.push( vertex ) - 1;
  19846. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19847. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19848. var v = inclination( vector ) / Math.PI + 0.5;
  19849. vertex.uv = new THREE.Vector2( u, 1 - v );
  19850. return vertex;
  19851. }
  19852. // Approximate a curved face with recursively sub-divided triangles.
  19853. function make( v1, v2, v3 ) {
  19854. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19855. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19856. that.faces.push( face );
  19857. var azi = azimuth( face.centroid );
  19858. that.faceVertexUvs[ 0 ].push( [
  19859. correctUV( v1.uv, v1, azi ),
  19860. correctUV( v2.uv, v2, azi ),
  19861. correctUV( v3.uv, v3, azi )
  19862. ] );
  19863. }
  19864. // Analytically subdivide a face to the required detail level.
  19865. function subdivide(face, detail ) {
  19866. var cols = Math.pow(2, detail);
  19867. var cells = Math.pow(4, detail);
  19868. var a = prepare( that.vertices[ face.a ] );
  19869. var b = prepare( that.vertices[ face.b ] );
  19870. var c = prepare( that.vertices[ face.c ] );
  19871. var v = [];
  19872. // Construct all of the vertices for this subdivision.
  19873. for ( var i = 0 ; i <= cols; i ++ ) {
  19874. v[ i ] = [];
  19875. var aj = prepare( a.clone().lerp( c, i / cols ) );
  19876. var bj = prepare( b.clone().lerp( c, i / cols ) );
  19877. var rows = cols - i;
  19878. for ( var j = 0; j <= rows; j ++) {
  19879. if ( j == 0 && i == cols ) {
  19880. v[ i ][ j ] = aj;
  19881. } else {
  19882. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  19883. }
  19884. }
  19885. }
  19886. // Construct all of the faces.
  19887. for ( var i = 0; i < cols ; i ++ ) {
  19888. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  19889. var k = Math.floor( j / 2 );
  19890. if ( j % 2 == 0 ) {
  19891. make(
  19892. v[ i ][ k + 1],
  19893. v[ i + 1 ][ k ],
  19894. v[ i ][ k ]
  19895. );
  19896. } else {
  19897. make(
  19898. v[ i ][ k + 1 ],
  19899. v[ i + 1][ k + 1],
  19900. v[ i + 1 ][ k ]
  19901. );
  19902. }
  19903. }
  19904. }
  19905. }
  19906. // Angle around the Y axis, counter-clockwise when looking from above.
  19907. function azimuth( vector ) {
  19908. return Math.atan2( vector.z, -vector.x );
  19909. }
  19910. // Angle above the XZ plane.
  19911. function inclination( vector ) {
  19912. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19913. }
  19914. // Texture fixing helper. Spheres have some odd behaviours.
  19915. function correctUV( uv, vector, azimuth ) {
  19916. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19917. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19918. return uv.clone();
  19919. }
  19920. };
  19921. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19922. /**
  19923. * @author timothypratley / https://github.com/timothypratley
  19924. */
  19925. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19926. this.radius = radius;
  19927. this.detail = detail;
  19928. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19929. var vertices = [
  19930. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19931. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19932. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19933. ];
  19934. var faces = [
  19935. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19936. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19937. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19938. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19939. ];
  19940. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19941. };
  19942. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19943. /**
  19944. * @author timothypratley / https://github.com/timothypratley
  19945. */
  19946. THREE.OctahedronGeometry = function ( radius, detail ) {
  19947. var vertices = [
  19948. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19949. ];
  19950. var faces = [
  19951. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19952. ];
  19953. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19954. };
  19955. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19956. /**
  19957. * @author timothypratley / https://github.com/timothypratley
  19958. */
  19959. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19960. var vertices = [
  19961. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19962. ];
  19963. var faces = [
  19964. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19965. ];
  19966. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19967. };
  19968. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19969. /**
  19970. * @author zz85 / https://github.com/zz85
  19971. * Parametric Surfaces Geometry
  19972. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19973. *
  19974. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  19975. *
  19976. */
  19977. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  19978. THREE.Geometry.call( this );
  19979. var verts = this.vertices;
  19980. var faces = this.faces;
  19981. var uvs = this.faceVertexUvs[ 0 ];
  19982. var i, il, j, p;
  19983. var u, v;
  19984. var stackCount = stacks + 1;
  19985. var sliceCount = slices + 1;
  19986. for ( i = 0; i <= stacks; i ++ ) {
  19987. v = i / stacks;
  19988. for ( j = 0; j <= slices; j ++ ) {
  19989. u = j / slices;
  19990. p = func( u, v );
  19991. verts.push( p );
  19992. }
  19993. }
  19994. var a, b, c, d;
  19995. var uva, uvb, uvc, uvd;
  19996. for ( i = 0; i < stacks; i ++ ) {
  19997. for ( j = 0; j < slices; j ++ ) {
  19998. a = i * sliceCount + j;
  19999. b = i * sliceCount + j + 1;
  20000. c = (i + 1) * sliceCount + j + 1;
  20001. d = (i + 1) * sliceCount + j;
  20002. uva = new THREE.Vector2( j / slices, i / stacks );
  20003. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20004. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20005. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20006. faces.push( new THREE.Face3( a, b, d ) );
  20007. uvs.push( [ uva, uvb, uvd ] );
  20008. faces.push( new THREE.Face3( b, c, d ) );
  20009. uvs.push( [ uvb, uvc, uvd ] );
  20010. }
  20011. }
  20012. // console.log(this);
  20013. // magic bullet
  20014. // var diff = this.mergeVertices();
  20015. // console.log('removed ', diff, ' vertices by merging');
  20016. this.computeCentroids();
  20017. this.computeFaceNormals();
  20018. this.computeVertexNormals();
  20019. };
  20020. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20021. /**
  20022. * @author sroucheray / http://sroucheray.org/
  20023. * @author mrdoob / http://mrdoob.com/
  20024. */
  20025. THREE.AxisHelper = function ( size ) {
  20026. size = size || 1;
  20027. var geometry = new THREE.Geometry();
  20028. geometry.vertices.push(
  20029. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  20030. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  20031. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  20032. );
  20033. geometry.colors.push(
  20034. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20035. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20036. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20037. );
  20038. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20039. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20040. };
  20041. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20042. /**
  20043. * @author WestLangley / http://github.com/WestLangley
  20044. * @author zz85 / http://github.com/zz85
  20045. * @author bhouston / http://exocortex.com
  20046. *
  20047. * Creates an arrow for visualizing directions
  20048. *
  20049. * Parameters:
  20050. * dir - Vector3
  20051. * origin - Vector3
  20052. * length - Number
  20053. * hex - color in hex value
  20054. */
  20055. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  20056. // dir is assumed to be normalized
  20057. THREE.Object3D.call( this );
  20058. if ( hex === undefined ) hex = 0xffff00;
  20059. if ( length === undefined ) length = 1;
  20060. this.position = origin;
  20061. var lineGeometry = new THREE.Geometry();
  20062. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20063. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20064. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20065. this.line.matrixAutoUpdate = false;
  20066. this.add( this.line );
  20067. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  20068. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, 0.875, 0 ) );
  20069. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20070. this.cone.matrixAutoUpdate = false;
  20071. this.add( this.cone );
  20072. this.setDirection( dir );
  20073. this.setLength( length );
  20074. };
  20075. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20076. THREE.ArrowHelper.prototype.setDirection = function () {
  20077. var axis = new THREE.Vector3();
  20078. var radians;
  20079. return function ( dir ) {
  20080. // dir is assumed to be normalized
  20081. if ( dir.y > 0.99999 ) {
  20082. this.quaternion.set( 0, 0, 0, 1 );
  20083. } else if ( dir.y < - 0.99999 ) {
  20084. this.quaternion.set( 1, 0, 0, 0 );
  20085. } else {
  20086. axis.set( dir.z, 0, - dir.x ).normalize();
  20087. radians = Math.acos( dir.y );
  20088. this.quaternion.setFromAxisAngle( axis, radians );
  20089. }
  20090. };
  20091. }();
  20092. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20093. this.scale.set( length, length, length );
  20094. };
  20095. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20096. this.line.material.color.setHex( hex );
  20097. this.cone.material.color.setHex( hex );
  20098. };
  20099. /**
  20100. * @author mrdoob / http://mrdoob.com/
  20101. */
  20102. THREE.BoxHelper = function ( object ) {
  20103. // 5____4
  20104. // 1/___0/|
  20105. // | 6__|_7
  20106. // 2/___3/
  20107. var vertices = [
  20108. new THREE.Vector3( 1, 1, 1 ),
  20109. new THREE.Vector3( - 1, 1, 1 ),
  20110. new THREE.Vector3( - 1, - 1, 1 ),
  20111. new THREE.Vector3( 1, - 1, 1 ),
  20112. new THREE.Vector3( 1, 1, - 1 ),
  20113. new THREE.Vector3( - 1, 1, - 1 ),
  20114. new THREE.Vector3( - 1, - 1, - 1 ),
  20115. new THREE.Vector3( 1, - 1, - 1 )
  20116. ];
  20117. this.vertices = vertices;
  20118. // TODO: Wouldn't be nice if Line had .segments?
  20119. var geometry = new THREE.Geometry();
  20120. geometry.vertices.push(
  20121. vertices[ 0 ], vertices[ 1 ],
  20122. vertices[ 1 ], vertices[ 2 ],
  20123. vertices[ 2 ], vertices[ 3 ],
  20124. vertices[ 3 ], vertices[ 0 ],
  20125. vertices[ 4 ], vertices[ 5 ],
  20126. vertices[ 5 ], vertices[ 6 ],
  20127. vertices[ 6 ], vertices[ 7 ],
  20128. vertices[ 7 ], vertices[ 4 ],
  20129. vertices[ 0 ], vertices[ 4 ],
  20130. vertices[ 1 ], vertices[ 5 ],
  20131. vertices[ 2 ], vertices[ 6 ],
  20132. vertices[ 3 ], vertices[ 7 ]
  20133. );
  20134. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20135. if ( object !== undefined ) {
  20136. this.update( object );
  20137. }
  20138. };
  20139. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20140. THREE.BoxHelper.prototype.update = function ( object ) {
  20141. var geometry = object.geometry;
  20142. if ( geometry.boundingBox === null ) {
  20143. geometry.computeBoundingBox();
  20144. }
  20145. var min = geometry.boundingBox.min;
  20146. var max = geometry.boundingBox.max;
  20147. var vertices = this.vertices;
  20148. vertices[ 0 ].set( max.x, max.y, max.z );
  20149. vertices[ 1 ].set( min.x, max.y, max.z );
  20150. vertices[ 2 ].set( min.x, min.y, max.z );
  20151. vertices[ 3 ].set( max.x, min.y, max.z );
  20152. vertices[ 4 ].set( max.x, max.y, min.z );
  20153. vertices[ 5 ].set( min.x, max.y, min.z );
  20154. vertices[ 6 ].set( min.x, min.y, min.z );
  20155. vertices[ 7 ].set( max.x, min.y, min.z );
  20156. this.geometry.computeBoundingSphere();
  20157. this.geometry.verticesNeedUpdate = true;
  20158. this.matrixAutoUpdate = false;
  20159. this.matrixWorld = object.matrixWorld;
  20160. };
  20161. /**
  20162. * @author WestLangley / http://github.com/WestLangley
  20163. */
  20164. // a helper to show the world-axis-aligned bounding box for an object
  20165. THREE.BoundingBoxHelper = function ( object, hex ) {
  20166. var color = hex || 0x888888;
  20167. this.object = object;
  20168. this.box = new THREE.Box3();
  20169. THREE.Mesh.call( this, new THREE.CubeGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20170. };
  20171. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20172. THREE.BoundingBoxHelper.prototype.update = function () {
  20173. this.box.setFromObject( this.object );
  20174. this.box.size( this.scale );
  20175. this.box.center( this.position );
  20176. };
  20177. /**
  20178. * @author alteredq / http://alteredqualia.com/
  20179. *
  20180. * - shows frustum, line of sight and up of the camera
  20181. * - suitable for fast updates
  20182. * - based on frustum visualization in lightgl.js shadowmap example
  20183. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20184. */
  20185. THREE.CameraHelper = function ( camera ) {
  20186. var geometry = new THREE.Geometry();
  20187. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20188. var pointMap = {};
  20189. // colors
  20190. var hexFrustum = 0xffaa00;
  20191. var hexCone = 0xff0000;
  20192. var hexUp = 0x00aaff;
  20193. var hexTarget = 0xffffff;
  20194. var hexCross = 0x333333;
  20195. // near
  20196. addLine( "n1", "n2", hexFrustum );
  20197. addLine( "n2", "n4", hexFrustum );
  20198. addLine( "n4", "n3", hexFrustum );
  20199. addLine( "n3", "n1", hexFrustum );
  20200. // far
  20201. addLine( "f1", "f2", hexFrustum );
  20202. addLine( "f2", "f4", hexFrustum );
  20203. addLine( "f4", "f3", hexFrustum );
  20204. addLine( "f3", "f1", hexFrustum );
  20205. // sides
  20206. addLine( "n1", "f1", hexFrustum );
  20207. addLine( "n2", "f2", hexFrustum );
  20208. addLine( "n3", "f3", hexFrustum );
  20209. addLine( "n4", "f4", hexFrustum );
  20210. // cone
  20211. addLine( "p", "n1", hexCone );
  20212. addLine( "p", "n2", hexCone );
  20213. addLine( "p", "n3", hexCone );
  20214. addLine( "p", "n4", hexCone );
  20215. // up
  20216. addLine( "u1", "u2", hexUp );
  20217. addLine( "u2", "u3", hexUp );
  20218. addLine( "u3", "u1", hexUp );
  20219. // target
  20220. addLine( "c", "t", hexTarget );
  20221. addLine( "p", "c", hexCross );
  20222. // cross
  20223. addLine( "cn1", "cn2", hexCross );
  20224. addLine( "cn3", "cn4", hexCross );
  20225. addLine( "cf1", "cf2", hexCross );
  20226. addLine( "cf3", "cf4", hexCross );
  20227. function addLine( a, b, hex ) {
  20228. addPoint( a, hex );
  20229. addPoint( b, hex );
  20230. }
  20231. function addPoint( id, hex ) {
  20232. geometry.vertices.push( new THREE.Vector3() );
  20233. geometry.colors.push( new THREE.Color( hex ) );
  20234. if ( pointMap[ id ] === undefined ) {
  20235. pointMap[ id ] = [];
  20236. }
  20237. pointMap[ id ].push( geometry.vertices.length - 1 );
  20238. }
  20239. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20240. this.camera = camera;
  20241. this.matrixWorld = camera.matrixWorld;
  20242. this.matrixAutoUpdate = false;
  20243. this.pointMap = pointMap;
  20244. this.update();
  20245. };
  20246. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20247. THREE.CameraHelper.prototype.update = function () {
  20248. var vector = new THREE.Vector3();
  20249. var camera = new THREE.Camera();
  20250. var projector = new THREE.Projector();
  20251. return function () {
  20252. var scope = this;
  20253. var w = 1, h = 1;
  20254. // we need just camera projection matrix
  20255. // world matrix must be identity
  20256. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20257. // center / target
  20258. setPoint( "c", 0, 0, -1 );
  20259. setPoint( "t", 0, 0, 1 );
  20260. // near
  20261. setPoint( "n1", -w, -h, -1 );
  20262. setPoint( "n2", w, -h, -1 );
  20263. setPoint( "n3", -w, h, -1 );
  20264. setPoint( "n4", w, h, -1 );
  20265. // far
  20266. setPoint( "f1", -w, -h, 1 );
  20267. setPoint( "f2", w, -h, 1 );
  20268. setPoint( "f3", -w, h, 1 );
  20269. setPoint( "f4", w, h, 1 );
  20270. // up
  20271. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20272. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20273. setPoint( "u3", 0, h * 2, -1 );
  20274. // cross
  20275. setPoint( "cf1", -w, 0, 1 );
  20276. setPoint( "cf2", w, 0, 1 );
  20277. setPoint( "cf3", 0, -h, 1 );
  20278. setPoint( "cf4", 0, h, 1 );
  20279. setPoint( "cn1", -w, 0, -1 );
  20280. setPoint( "cn2", w, 0, -1 );
  20281. setPoint( "cn3", 0, -h, -1 );
  20282. setPoint( "cn4", 0, h, -1 );
  20283. function setPoint( point, x, y, z ) {
  20284. vector.set( x, y, z );
  20285. projector.unprojectVector( vector, camera );
  20286. var points = scope.pointMap[ point ];
  20287. if ( points !== undefined ) {
  20288. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20289. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20290. }
  20291. }
  20292. }
  20293. this.geometry.verticesNeedUpdate = true;
  20294. };
  20295. }();
  20296. /**
  20297. * @author alteredq / http://alteredqualia.com/
  20298. * @author mrdoob / http://mrdoob.com/
  20299. */
  20300. THREE.DirectionalLightHelper = function ( light, size ) {
  20301. THREE.Object3D.call( this );
  20302. this.light = light;
  20303. this.light.updateMatrixWorld();
  20304. this.matrixWorld = light.matrixWorld;
  20305. this.matrixAutoUpdate = false;
  20306. var geometry = new THREE.PlaneGeometry( size, size );
  20307. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20308. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20309. this.lightPlane = new THREE.Mesh( geometry, material );
  20310. this.add( this.lightPlane );
  20311. geometry = new THREE.Geometry();
  20312. geometry.vertices.push( new THREE.Vector3() );
  20313. geometry.vertices.push( new THREE.Vector3() );
  20314. geometry.computeLineDistances();
  20315. material = new THREE.LineBasicMaterial( { fog: false } );
  20316. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20317. this.targetLine = new THREE.Line( geometry, material );
  20318. this.add( this.targetLine );
  20319. this.update();
  20320. };
  20321. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20322. THREE.DirectionalLightHelper.prototype.update = function () {
  20323. var vector = new THREE.Vector3();
  20324. return function () {
  20325. vector.getPositionFromMatrix( this.light.matrixWorld ).negate();
  20326. this.lightPlane.lookAt( vector );
  20327. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20328. this.targetLine.geometry.vertices[ 1 ].copy( vector );
  20329. this.targetLine.geometry.verticesNeedUpdate = true;
  20330. this.targetLine.material.color.copy( this.lightPlane.material.color );
  20331. }
  20332. }();
  20333. /**
  20334. * @author mrdoob / http://mrdoob.com/
  20335. * @author WestLangley / http://github.com/WestLangley
  20336. */
  20337. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20338. this.object = object;
  20339. this.size = size || 1;
  20340. var color = hex || 0xffff00;
  20341. var width = linewidth || 1;
  20342. var geometry = new THREE.Geometry();
  20343. var faces = this.object.geometry.faces;
  20344. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20345. geometry.vertices.push( new THREE.Vector3() );
  20346. geometry.vertices.push( new THREE.Vector3() );
  20347. }
  20348. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20349. this.matrixAutoUpdate = false;
  20350. this.normalMatrix = new THREE.Matrix3();
  20351. this.update();
  20352. };
  20353. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20354. THREE.FaceNormalsHelper.prototype.update = ( function ( object ) {
  20355. var v1 = new THREE.Vector3();
  20356. return function ( object ) {
  20357. this.object.updateMatrixWorld( true );
  20358. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20359. var vertices = this.geometry.vertices;
  20360. var faces = this.object.geometry.faces;
  20361. var worldMatrix = this.object.matrixWorld;
  20362. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20363. var face = faces[ i ];
  20364. v1.copy( face.normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20365. var idx = 2 * i;
  20366. vertices[ idx ].copy( face.centroid ).applyMatrix4( worldMatrix );
  20367. vertices[ idx + 1 ].addVectors( vertices[ idx ], v1 );
  20368. }
  20369. this.geometry.verticesNeedUpdate = true;
  20370. return this;
  20371. }
  20372. }());
  20373. /**
  20374. * @author mrdoob / http://mrdoob.com/
  20375. */
  20376. THREE.GridHelper = function ( size, step ) {
  20377. var geometry = new THREE.Geometry();
  20378. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20379. this.color1 = new THREE.Color( 0x444444 );
  20380. this.color2 = new THREE.Color( 0x888888 );
  20381. for ( var i = - size; i <= size; i += step ) {
  20382. geometry.vertices.push(
  20383. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  20384. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  20385. );
  20386. var color = i === 0 ? this.color1 : this.color2;
  20387. geometry.colors.push( color, color, color, color );
  20388. }
  20389. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20390. };
  20391. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  20392. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  20393. this.color1.set( colorCenterLine );
  20394. this.color2.set( colorGrid );
  20395. this.geometry.colorsNeedUpdate = true;
  20396. }
  20397. /**
  20398. * @author alteredq / http://alteredqualia.com/
  20399. * @author mrdoob / http://mrdoob.com/
  20400. */
  20401. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20402. THREE.Object3D.call( this );
  20403. this.light = light;
  20404. this.light.updateMatrixWorld();
  20405. this.matrixWorld = light.matrixWorld;
  20406. this.matrixAutoUpdate = false;
  20407. this.colors = [ new THREE.Color(), new THREE.Color() ];
  20408. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20409. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20410. for ( var i = 0, il = 8; i < il; i ++ ) {
  20411. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  20412. }
  20413. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  20414. this.lightSphere = new THREE.Mesh( geometry, material );
  20415. this.add( this.lightSphere );
  20416. this.update();
  20417. };
  20418. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20419. THREE.HemisphereLightHelper.prototype.update = function () {
  20420. var vector = new THREE.Vector3();
  20421. return function () {
  20422. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  20423. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  20424. this.lightSphere.lookAt( vector.getPositionFromMatrix( this.light.matrixWorld ).negate() );
  20425. this.lightSphere.geometry.colorsNeedUpdate = true;
  20426. }
  20427. }();
  20428. /**
  20429. * @author alteredq / http://alteredqualia.com/
  20430. * @author mrdoob / http://mrdoob.com/
  20431. */
  20432. THREE.PointLightHelper = function ( light, sphereSize ) {
  20433. this.light = light;
  20434. this.light.updateMatrixWorld();
  20435. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20436. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20437. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20438. THREE.Mesh.call( this, geometry, material );
  20439. this.matrixWorld = this.light.matrixWorld;
  20440. this.matrixAutoUpdate = false;
  20441. /*
  20442. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20443. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20444. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20445. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20446. var d = light.distance;
  20447. if ( d === 0.0 ) {
  20448. this.lightDistance.visible = false;
  20449. } else {
  20450. this.lightDistance.scale.set( d, d, d );
  20451. }
  20452. this.add( this.lightDistance );
  20453. */
  20454. };
  20455. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  20456. THREE.PointLightHelper.prototype.update = function () {
  20457. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20458. /*
  20459. var d = this.light.distance;
  20460. if ( d === 0.0 ) {
  20461. this.lightDistance.visible = false;
  20462. } else {
  20463. this.lightDistance.visible = true;
  20464. this.lightDistance.scale.set( d, d, d );
  20465. }
  20466. */
  20467. };
  20468. /**
  20469. * @author alteredq / http://alteredqualia.com/
  20470. * @author mrdoob / http://mrdoob.com/
  20471. * @author WestLangley / http://github.com/WestLangley
  20472. */
  20473. THREE.SpotLightHelper = function ( light ) {
  20474. THREE.Object3D.call( this );
  20475. this.light = light;
  20476. this.light.updateMatrixWorld();
  20477. this.matrixWorld = light.matrixWorld;
  20478. this.matrixAutoUpdate = false;
  20479. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  20480. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  20481. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20482. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20483. this.cone = new THREE.Mesh( geometry, material );
  20484. this.add( this.cone );
  20485. this.update();
  20486. };
  20487. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20488. THREE.SpotLightHelper.prototype.update = function () {
  20489. var vector = new THREE.Vector3();
  20490. return function () {
  20491. var coneLength = this.light.distance ? this.light.distance : 10000;
  20492. var coneWidth = coneLength * Math.tan( this.light.angle );
  20493. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20494. this.cone.lookAt( vector.getPositionFromMatrix( this.light.matrixWorld ).negate() );
  20495. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20496. }
  20497. }();
  20498. /**
  20499. * @author mrdoob / http://mrdoob.com/
  20500. * @author WestLangley / http://github.com/WestLangley
  20501. */
  20502. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  20503. this.object = object;
  20504. this.size = size || 1;
  20505. var color = hex || 0xff0000;
  20506. var width = linewidth || 1;
  20507. var geometry = new THREE.Geometry();
  20508. var vertices = object.geometry.vertices;
  20509. var faces = object.geometry.faces;
  20510. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20511. var face = faces[ i ];
  20512. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20513. geometry.vertices.push( new THREE.Vector3() );
  20514. geometry.vertices.push( new THREE.Vector3() );
  20515. }
  20516. }
  20517. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20518. this.matrixAutoUpdate = false;
  20519. this.normalMatrix = new THREE.Matrix3();
  20520. this.update();
  20521. };
  20522. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20523. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  20524. var v1 = new THREE.Vector3();
  20525. return function( object ) {
  20526. var keys = [ 'a', 'b', 'c', 'd' ];
  20527. this.object.updateMatrixWorld( true );
  20528. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20529. var vertices = this.geometry.vertices;
  20530. var verts = this.object.geometry.vertices;
  20531. var faces = this.object.geometry.faces;
  20532. var worldMatrix = this.object.matrixWorld;
  20533. var idx = 0;
  20534. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20535. var face = faces[ i ];
  20536. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20537. var vertexId = face[ keys[ j ] ];
  20538. var vertex = verts[ vertexId ];
  20539. var normal = face.vertexNormals[ j ];
  20540. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20541. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20542. v1.add( vertices[ idx ] );
  20543. idx = idx + 1;
  20544. vertices[ idx ].copy( v1 );
  20545. idx = idx + 1;
  20546. }
  20547. }
  20548. this.geometry.verticesNeedUpdate = true;
  20549. return this;
  20550. }
  20551. }());
  20552. /**
  20553. * @author mrdoob / http://mrdoob.com/
  20554. * @author WestLangley / http://github.com/WestLangley
  20555. */
  20556. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  20557. this.object = object;
  20558. this.size = size || 1;
  20559. var color = hex || 0x0000ff;
  20560. var width = linewidth || 1;
  20561. var geometry = new THREE.Geometry();
  20562. var vertices = object.geometry.vertices;
  20563. var faces = object.geometry.faces;
  20564. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20565. var face = faces[ i ];
  20566. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20567. geometry.vertices.push( new THREE.Vector3() );
  20568. geometry.vertices.push( new THREE.Vector3() );
  20569. }
  20570. }
  20571. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20572. this.matrixAutoUpdate = false;
  20573. this.update();
  20574. };
  20575. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  20576. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  20577. var v1 = new THREE.Vector3();
  20578. return function( object ) {
  20579. var keys = [ 'a', 'b', 'c', 'd' ];
  20580. this.object.updateMatrixWorld( true );
  20581. var vertices = this.geometry.vertices;
  20582. var verts = this.object.geometry.vertices;
  20583. var faces = this.object.geometry.faces;
  20584. var worldMatrix = this.object.matrixWorld;
  20585. var idx = 0;
  20586. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20587. var face = faces[ i ];
  20588. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20589. var vertexId = face[ keys[ j ] ];
  20590. var vertex = verts[ vertexId ];
  20591. var tangent = face.vertexTangents[ j ];
  20592. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20593. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  20594. v1.add( vertices[ idx ] );
  20595. idx = idx + 1;
  20596. vertices[ idx ].copy( v1 );
  20597. idx = idx + 1;
  20598. }
  20599. }
  20600. this.geometry.verticesNeedUpdate = true;
  20601. return this;
  20602. }
  20603. }());
  20604. /**
  20605. * @author mrdoob / http://mrdoob.com/
  20606. */
  20607. THREE.WireframeHelper = function ( object ) {
  20608. var edge = [ 0, 0 ], hash = {};
  20609. var sortFunction = function ( a, b ) { return a - b };
  20610. var keys = [ 'a', 'b', 'c', 'd' ];
  20611. var geometry = new THREE.Geometry();
  20612. var vertices = object.geometry.vertices;
  20613. var faces = object.geometry.faces;
  20614. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20615. var face = faces[ i ];
  20616. for ( var j = 0; j < 3; j ++ ) {
  20617. edge[ 0 ] = face[ keys[ j ] ];
  20618. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20619. edge.sort( sortFunction );
  20620. var key = edge.toString();
  20621. if ( hash[ key ] === undefined ) {
  20622. geometry.vertices.push( vertices[ edge[ 0 ] ] );
  20623. geometry.vertices.push( vertices[ edge[ 1 ] ] );
  20624. hash[ key ] = true;
  20625. }
  20626. }
  20627. }
  20628. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffffff } ), THREE.LinePieces );
  20629. this.matrixAutoUpdate = false;
  20630. this.matrixWorld = object.matrixWorld;
  20631. };
  20632. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  20633. /**
  20634. * @author alteredq / http://alteredqualia.com/
  20635. */
  20636. THREE.ImmediateRenderObject = function () {
  20637. THREE.Object3D.call( this );
  20638. this.render = function ( renderCallback ) { };
  20639. };
  20640. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20641. /**
  20642. * @author mikael emtinger / http://gomo.se/
  20643. * @author alteredq / http://alteredqualia.com/
  20644. */
  20645. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20646. THREE.Object3D.call( this );
  20647. this.lensFlares = [];
  20648. this.positionScreen = new THREE.Vector3();
  20649. this.customUpdateCallback = undefined;
  20650. if( texture !== undefined ) {
  20651. this.add( texture, size, distance, blending, color );
  20652. }
  20653. };
  20654. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20655. /*
  20656. * Add: adds another flare
  20657. */
  20658. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20659. if( size === undefined ) size = -1;
  20660. if( distance === undefined ) distance = 0;
  20661. if( opacity === undefined ) opacity = 1;
  20662. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20663. if( blending === undefined ) blending = THREE.NormalBlending;
  20664. distance = Math.min( distance, Math.max( 0, distance ) );
  20665. this.lensFlares.push( { texture: texture, // THREE.Texture
  20666. size: size, // size in pixels (-1 = use texture.width)
  20667. distance: distance, // distance (0-1) from light source (0=at light source)
  20668. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20669. scale: 1, // scale
  20670. rotation: 1, // rotation
  20671. opacity: opacity, // opacity
  20672. color: color, // color
  20673. blending: blending } ); // blending
  20674. };
  20675. /*
  20676. * Update lens flares update positions on all flares based on the screen position
  20677. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20678. */
  20679. THREE.LensFlare.prototype.updateLensFlares = function () {
  20680. var f, fl = this.lensFlares.length;
  20681. var flare;
  20682. var vecX = -this.positionScreen.x * 2;
  20683. var vecY = -this.positionScreen.y * 2;
  20684. for( f = 0; f < fl; f ++ ) {
  20685. flare = this.lensFlares[ f ];
  20686. flare.x = this.positionScreen.x + vecX * flare.distance;
  20687. flare.y = this.positionScreen.y + vecY * flare.distance;
  20688. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20689. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20690. }
  20691. };
  20692. /**
  20693. * @author alteredq / http://alteredqualia.com/
  20694. */
  20695. THREE.MorphBlendMesh = function( geometry, material ) {
  20696. THREE.Mesh.call( this, geometry, material );
  20697. this.animationsMap = {};
  20698. this.animationsList = [];
  20699. // prepare default animation
  20700. // (all frames played together in 1 second)
  20701. var numFrames = this.geometry.morphTargets.length;
  20702. var name = "__default";
  20703. var startFrame = 0;
  20704. var endFrame = numFrames - 1;
  20705. var fps = numFrames / 1;
  20706. this.createAnimation( name, startFrame, endFrame, fps );
  20707. this.setAnimationWeight( name, 1 );
  20708. };
  20709. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20710. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20711. var animation = {
  20712. startFrame: start,
  20713. endFrame: end,
  20714. length: end - start + 1,
  20715. fps: fps,
  20716. duration: ( end - start ) / fps,
  20717. lastFrame: 0,
  20718. currentFrame: 0,
  20719. active: false,
  20720. time: 0,
  20721. direction: 1,
  20722. weight: 1,
  20723. directionBackwards: false,
  20724. mirroredLoop: false
  20725. };
  20726. this.animationsMap[ name ] = animation;
  20727. this.animationsList.push( animation );
  20728. };
  20729. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20730. var pattern = /([a-z]+)(\d+)/;
  20731. var firstAnimation, frameRanges = {};
  20732. var geometry = this.geometry;
  20733. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20734. var morph = geometry.morphTargets[ i ];
  20735. var chunks = morph.name.match( pattern );
  20736. if ( chunks && chunks.length > 1 ) {
  20737. var name = chunks[ 1 ];
  20738. var num = chunks[ 2 ];
  20739. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20740. var range = frameRanges[ name ];
  20741. if ( i < range.start ) range.start = i;
  20742. if ( i > range.end ) range.end = i;
  20743. if ( ! firstAnimation ) firstAnimation = name;
  20744. }
  20745. }
  20746. for ( var name in frameRanges ) {
  20747. var range = frameRanges[ name ];
  20748. this.createAnimation( name, range.start, range.end, fps );
  20749. }
  20750. this.firstAnimation = firstAnimation;
  20751. };
  20752. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20753. var animation = this.animationsMap[ name ];
  20754. if ( animation ) {
  20755. animation.direction = 1;
  20756. animation.directionBackwards = false;
  20757. }
  20758. };
  20759. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20760. var animation = this.animationsMap[ name ];
  20761. if ( animation ) {
  20762. animation.direction = -1;
  20763. animation.directionBackwards = true;
  20764. }
  20765. };
  20766. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20767. var animation = this.animationsMap[ name ];
  20768. if ( animation ) {
  20769. animation.fps = fps;
  20770. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20771. }
  20772. };
  20773. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20774. var animation = this.animationsMap[ name ];
  20775. if ( animation ) {
  20776. animation.duration = duration;
  20777. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20778. }
  20779. };
  20780. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20781. var animation = this.animationsMap[ name ];
  20782. if ( animation ) {
  20783. animation.weight = weight;
  20784. }
  20785. };
  20786. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20787. var animation = this.animationsMap[ name ];
  20788. if ( animation ) {
  20789. animation.time = time;
  20790. }
  20791. };
  20792. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20793. var time = 0;
  20794. var animation = this.animationsMap[ name ];
  20795. if ( animation ) {
  20796. time = animation.time;
  20797. }
  20798. return time;
  20799. };
  20800. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20801. var duration = -1;
  20802. var animation = this.animationsMap[ name ];
  20803. if ( animation ) {
  20804. duration = animation.duration;
  20805. }
  20806. return duration;
  20807. };
  20808. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20809. var animation = this.animationsMap[ name ];
  20810. if ( animation ) {
  20811. animation.time = 0;
  20812. animation.active = true;
  20813. } else {
  20814. console.warn( "animation[" + name + "] undefined" );
  20815. }
  20816. };
  20817. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20818. var animation = this.animationsMap[ name ];
  20819. if ( animation ) {
  20820. animation.active = false;
  20821. }
  20822. };
  20823. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20824. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20825. var animation = this.animationsList[ i ];
  20826. if ( ! animation.active ) continue;
  20827. var frameTime = animation.duration / animation.length;
  20828. animation.time += animation.direction * delta;
  20829. if ( animation.mirroredLoop ) {
  20830. if ( animation.time > animation.duration || animation.time < 0 ) {
  20831. animation.direction *= -1;
  20832. if ( animation.time > animation.duration ) {
  20833. animation.time = animation.duration;
  20834. animation.directionBackwards = true;
  20835. }
  20836. if ( animation.time < 0 ) {
  20837. animation.time = 0;
  20838. animation.directionBackwards = false;
  20839. }
  20840. }
  20841. } else {
  20842. animation.time = animation.time % animation.duration;
  20843. if ( animation.time < 0 ) animation.time += animation.duration;
  20844. }
  20845. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20846. var weight = animation.weight;
  20847. if ( keyframe !== animation.currentFrame ) {
  20848. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20849. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20850. this.morphTargetInfluences[ keyframe ] = 0;
  20851. animation.lastFrame = animation.currentFrame;
  20852. animation.currentFrame = keyframe;
  20853. }
  20854. var mix = ( animation.time % frameTime ) / frameTime;
  20855. if ( animation.directionBackwards ) mix = 1 - mix;
  20856. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20857. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20858. }
  20859. };
  20860. /**
  20861. * @author mikael emtinger / http://gomo.se/
  20862. * @author alteredq / http://alteredqualia.com/
  20863. */
  20864. THREE.LensFlarePlugin = function () {
  20865. var _gl, _renderer, _precision, _lensFlare = {};
  20866. this.init = function ( renderer ) {
  20867. _gl = renderer.context;
  20868. _renderer = renderer;
  20869. _precision = renderer.getPrecision();
  20870. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20871. _lensFlare.faces = new Uint16Array( 6 );
  20872. var i = 0;
  20873. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20874. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20875. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20876. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20877. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20878. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20879. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20880. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20881. i = 0;
  20882. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20883. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20884. // buffers
  20885. _lensFlare.vertexBuffer = _gl.createBuffer();
  20886. _lensFlare.elementBuffer = _gl.createBuffer();
  20887. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20888. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20889. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20890. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20891. // textures
  20892. _lensFlare.tempTexture = _gl.createTexture();
  20893. _lensFlare.occlusionTexture = _gl.createTexture();
  20894. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20895. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20896. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20897. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20898. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20899. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20900. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20901. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20902. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20903. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20904. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20905. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20906. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20907. _lensFlare.hasVertexTexture = false;
  20908. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  20909. } else {
  20910. _lensFlare.hasVertexTexture = true;
  20911. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  20912. }
  20913. _lensFlare.attributes = {};
  20914. _lensFlare.uniforms = {};
  20915. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20916. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20917. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20918. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20919. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20920. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20921. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20922. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20923. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20924. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20925. };
  20926. /*
  20927. * Render lens flares
  20928. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20929. * reads these back and calculates occlusion.
  20930. * Then _lensFlare.update_lensFlares() is called to re-position and
  20931. * update transparency of flares. Then they are rendered.
  20932. *
  20933. */
  20934. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20935. var flares = scene.__webglFlares,
  20936. nFlares = flares.length;
  20937. if ( ! nFlares ) return;
  20938. var tempPosition = new THREE.Vector3();
  20939. var invAspect = viewportHeight / viewportWidth,
  20940. halfViewportWidth = viewportWidth * 0.5,
  20941. halfViewportHeight = viewportHeight * 0.5;
  20942. var size = 16 / viewportHeight,
  20943. scale = new THREE.Vector2( size * invAspect, size );
  20944. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20945. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20946. var uniforms = _lensFlare.uniforms,
  20947. attributes = _lensFlare.attributes;
  20948. // set _lensFlare program and reset blending
  20949. _gl.useProgram( _lensFlare.program );
  20950. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20951. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20952. // loop through all lens flares to update their occlusion and positions
  20953. // setup gl and common used attribs/unforms
  20954. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20955. _gl.uniform1i( uniforms.map, 1 );
  20956. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20957. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20958. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20959. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20960. _gl.disable( _gl.CULL_FACE );
  20961. _gl.depthMask( false );
  20962. var i, j, jl, flare, sprite;
  20963. for ( i = 0; i < nFlares; i ++ ) {
  20964. size = 16 / viewportHeight;
  20965. scale.set( size * invAspect, size );
  20966. // calc object screen position
  20967. flare = flares[ i ];
  20968. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20969. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  20970. tempPosition.applyProjection( camera.projectionMatrix );
  20971. // setup arrays for gl programs
  20972. screenPosition.copy( tempPosition )
  20973. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20974. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20975. // screen cull
  20976. if ( _lensFlare.hasVertexTexture || (
  20977. screenPositionPixels.x > 0 &&
  20978. screenPositionPixels.x < viewportWidth &&
  20979. screenPositionPixels.y > 0 &&
  20980. screenPositionPixels.y < viewportHeight ) ) {
  20981. // save current RGB to temp texture
  20982. _gl.activeTexture( _gl.TEXTURE1 );
  20983. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20984. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20985. // render pink quad
  20986. _gl.uniform1i( uniforms.renderType, 0 );
  20987. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20988. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20989. _gl.disable( _gl.BLEND );
  20990. _gl.enable( _gl.DEPTH_TEST );
  20991. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20992. // copy result to occlusionMap
  20993. _gl.activeTexture( _gl.TEXTURE0 );
  20994. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20995. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20996. // restore graphics
  20997. _gl.uniform1i( uniforms.renderType, 1 );
  20998. _gl.disable( _gl.DEPTH_TEST );
  20999. _gl.activeTexture( _gl.TEXTURE1 );
  21000. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21001. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21002. // update object positions
  21003. flare.positionScreen.copy( screenPosition )
  21004. if ( flare.customUpdateCallback ) {
  21005. flare.customUpdateCallback( flare );
  21006. } else {
  21007. flare.updateLensFlares();
  21008. }
  21009. // render flares
  21010. _gl.uniform1i( uniforms.renderType, 2 );
  21011. _gl.enable( _gl.BLEND );
  21012. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21013. sprite = flare.lensFlares[ j ];
  21014. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21015. screenPosition.x = sprite.x;
  21016. screenPosition.y = sprite.y;
  21017. screenPosition.z = sprite.z;
  21018. size = sprite.size * sprite.scale / viewportHeight;
  21019. scale.x = size * invAspect;
  21020. scale.y = size;
  21021. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21022. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21023. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21024. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21025. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21026. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21027. _renderer.setTexture( sprite.texture, 1 );
  21028. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21029. }
  21030. }
  21031. }
  21032. }
  21033. // restore gl
  21034. _gl.enable( _gl.CULL_FACE );
  21035. _gl.enable( _gl.DEPTH_TEST );
  21036. _gl.depthMask( true );
  21037. };
  21038. function createProgram ( shader, precision ) {
  21039. var program = _gl.createProgram();
  21040. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21041. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21042. var prefix = "precision " + precision + " float;\n";
  21043. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21044. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21045. _gl.compileShader( fragmentShader );
  21046. _gl.compileShader( vertexShader );
  21047. _gl.attachShader( program, fragmentShader );
  21048. _gl.attachShader( program, vertexShader );
  21049. _gl.linkProgram( program );
  21050. return program;
  21051. };
  21052. };
  21053. /**
  21054. * @author alteredq / http://alteredqualia.com/
  21055. */
  21056. THREE.ShadowMapPlugin = function () {
  21057. var _gl,
  21058. _renderer,
  21059. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21060. _frustum = new THREE.Frustum(),
  21061. _projScreenMatrix = new THREE.Matrix4(),
  21062. _min = new THREE.Vector3(),
  21063. _max = new THREE.Vector3(),
  21064. _matrixPosition = new THREE.Vector3();
  21065. this.init = function ( renderer ) {
  21066. _gl = renderer.context;
  21067. _renderer = renderer;
  21068. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21069. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21070. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21071. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21072. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21073. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21074. _depthMaterial._shadowPass = true;
  21075. _depthMaterialMorph._shadowPass = true;
  21076. _depthMaterialSkin._shadowPass = true;
  21077. _depthMaterialMorphSkin._shadowPass = true;
  21078. };
  21079. this.render = function ( scene, camera ) {
  21080. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21081. this.update( scene, camera );
  21082. };
  21083. this.update = function ( scene, camera ) {
  21084. var i, il, j, jl, n,
  21085. shadowMap, shadowMatrix, shadowCamera,
  21086. program, buffer, material,
  21087. webglObject, object, light,
  21088. renderList,
  21089. lights = [],
  21090. k = 0,
  21091. fog = null;
  21092. // set GL state for depth map
  21093. _gl.clearColor( 1, 1, 1, 1 );
  21094. _gl.disable( _gl.BLEND );
  21095. _gl.enable( _gl.CULL_FACE );
  21096. _gl.frontFace( _gl.CCW );
  21097. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21098. _gl.cullFace( _gl.FRONT );
  21099. } else {
  21100. _gl.cullFace( _gl.BACK );
  21101. }
  21102. _renderer.setDepthTest( true );
  21103. // preprocess lights
  21104. // - skip lights that are not casting shadows
  21105. // - create virtual lights for cascaded shadow maps
  21106. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21107. light = scene.__lights[ i ];
  21108. if ( ! light.castShadow ) continue;
  21109. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21110. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21111. var virtualLight;
  21112. if ( ! light.shadowCascadeArray[ n ] ) {
  21113. virtualLight = createVirtualLight( light, n );
  21114. virtualLight.originalCamera = camera;
  21115. var gyro = new THREE.Gyroscope();
  21116. gyro.position = light.shadowCascadeOffset;
  21117. gyro.add( virtualLight );
  21118. gyro.add( virtualLight.target );
  21119. camera.add( gyro );
  21120. light.shadowCascadeArray[ n ] = virtualLight;
  21121. console.log( "Created virtualLight", virtualLight );
  21122. } else {
  21123. virtualLight = light.shadowCascadeArray[ n ];
  21124. }
  21125. updateVirtualLight( light, n );
  21126. lights[ k ] = virtualLight;
  21127. k ++;
  21128. }
  21129. } else {
  21130. lights[ k ] = light;
  21131. k ++;
  21132. }
  21133. }
  21134. // render depth map
  21135. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21136. light = lights[ i ];
  21137. if ( ! light.shadowMap ) {
  21138. var shadowFilter = THREE.LinearFilter;
  21139. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21140. shadowFilter = THREE.NearestFilter;
  21141. }
  21142. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21143. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21144. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21145. light.shadowMatrix = new THREE.Matrix4();
  21146. }
  21147. if ( ! light.shadowCamera ) {
  21148. if ( light instanceof THREE.SpotLight ) {
  21149. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21150. } else if ( light instanceof THREE.DirectionalLight ) {
  21151. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21152. } else {
  21153. console.error( "Unsupported light type for shadow" );
  21154. continue;
  21155. }
  21156. scene.add( light.shadowCamera );
  21157. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21158. }
  21159. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21160. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21161. light.shadowCamera.add( light.cameraHelper );
  21162. }
  21163. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21164. updateShadowCamera( camera, light );
  21165. }
  21166. shadowMap = light.shadowMap;
  21167. shadowMatrix = light.shadowMatrix;
  21168. shadowCamera = light.shadowCamera;
  21169. shadowCamera.position.getPositionFromMatrix( light.matrixWorld );
  21170. _matrixPosition.getPositionFromMatrix( light.target.matrixWorld );
  21171. shadowCamera.lookAt( _matrixPosition );
  21172. shadowCamera.updateMatrixWorld();
  21173. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21174. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21175. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21176. // compute shadow matrix
  21177. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21178. 0.0, 0.5, 0.0, 0.5,
  21179. 0.0, 0.0, 0.5, 0.5,
  21180. 0.0, 0.0, 0.0, 1.0 );
  21181. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21182. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21183. // update camera matrices and frustum
  21184. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21185. _frustum.setFromMatrix( _projScreenMatrix );
  21186. // render shadow map
  21187. _renderer.setRenderTarget( shadowMap );
  21188. _renderer.clear();
  21189. // set object matrices & frustum culling
  21190. renderList = scene.__webglObjects;
  21191. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21192. webglObject = renderList[ j ];
  21193. object = webglObject.object;
  21194. webglObject.render = false;
  21195. if ( object.visible && object.castShadow ) {
  21196. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21197. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21198. webglObject.render = true;
  21199. }
  21200. }
  21201. }
  21202. // render regular objects
  21203. var objectMaterial, useMorphing, useSkinning;
  21204. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21205. webglObject = renderList[ j ];
  21206. if ( webglObject.render ) {
  21207. object = webglObject.object;
  21208. buffer = webglObject.buffer;
  21209. // culling is overriden globally for all objects
  21210. // while rendering depth map
  21211. // need to deal with MeshFaceMaterial somehow
  21212. // in that case just use the first of material.materials for now
  21213. // (proper solution would require to break objects by materials
  21214. // similarly to regular rendering and then set corresponding
  21215. // depth materials per each chunk instead of just once per object)
  21216. objectMaterial = getObjectMaterial( object );
  21217. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21218. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21219. if ( object.customDepthMaterial ) {
  21220. material = object.customDepthMaterial;
  21221. } else if ( useSkinning ) {
  21222. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21223. } else if ( useMorphing ) {
  21224. material = _depthMaterialMorph;
  21225. } else {
  21226. material = _depthMaterial;
  21227. }
  21228. if ( buffer instanceof THREE.BufferGeometry ) {
  21229. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21230. } else {
  21231. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21232. }
  21233. }
  21234. }
  21235. // set matrices and render immediate objects
  21236. renderList = scene.__webglObjectsImmediate;
  21237. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21238. webglObject = renderList[ j ];
  21239. object = webglObject.object;
  21240. if ( object.visible && object.castShadow ) {
  21241. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21242. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21243. }
  21244. }
  21245. }
  21246. // restore GL state
  21247. var clearColor = _renderer.getClearColor(),
  21248. clearAlpha = _renderer.getClearAlpha();
  21249. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21250. _gl.enable( _gl.BLEND );
  21251. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21252. _gl.cullFace( _gl.BACK );
  21253. }
  21254. };
  21255. function createVirtualLight( light, cascade ) {
  21256. var virtualLight = new THREE.DirectionalLight();
  21257. virtualLight.isVirtual = true;
  21258. virtualLight.onlyShadow = true;
  21259. virtualLight.castShadow = true;
  21260. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21261. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21262. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21263. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21264. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21265. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21266. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21267. virtualLight.shadowDarkness = light.shadowDarkness;
  21268. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21269. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21270. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21271. virtualLight.pointsWorld = [];
  21272. virtualLight.pointsFrustum = [];
  21273. var pointsWorld = virtualLight.pointsWorld,
  21274. pointsFrustum = virtualLight.pointsFrustum;
  21275. for ( var i = 0; i < 8; i ++ ) {
  21276. pointsWorld[ i ] = new THREE.Vector3();
  21277. pointsFrustum[ i ] = new THREE.Vector3();
  21278. }
  21279. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21280. var farZ = light.shadowCascadeFarZ[ cascade ];
  21281. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21282. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21283. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21284. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21285. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21286. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21287. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21288. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21289. return virtualLight;
  21290. }
  21291. // Synchronize virtual light with the original light
  21292. function updateVirtualLight( light, cascade ) {
  21293. var virtualLight = light.shadowCascadeArray[ cascade ];
  21294. virtualLight.position.copy( light.position );
  21295. virtualLight.target.position.copy( light.target.position );
  21296. virtualLight.lookAt( virtualLight.target );
  21297. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21298. virtualLight.shadowDarkness = light.shadowDarkness;
  21299. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21300. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21301. var farZ = light.shadowCascadeFarZ[ cascade ];
  21302. var pointsFrustum = virtualLight.pointsFrustum;
  21303. pointsFrustum[ 0 ].z = nearZ;
  21304. pointsFrustum[ 1 ].z = nearZ;
  21305. pointsFrustum[ 2 ].z = nearZ;
  21306. pointsFrustum[ 3 ].z = nearZ;
  21307. pointsFrustum[ 4 ].z = farZ;
  21308. pointsFrustum[ 5 ].z = farZ;
  21309. pointsFrustum[ 6 ].z = farZ;
  21310. pointsFrustum[ 7 ].z = farZ;
  21311. }
  21312. // Fit shadow camera's ortho frustum to camera frustum
  21313. function updateShadowCamera( camera, light ) {
  21314. var shadowCamera = light.shadowCamera,
  21315. pointsFrustum = light.pointsFrustum,
  21316. pointsWorld = light.pointsWorld;
  21317. _min.set( Infinity, Infinity, Infinity );
  21318. _max.set( -Infinity, -Infinity, -Infinity );
  21319. for ( var i = 0; i < 8; i ++ ) {
  21320. var p = pointsWorld[ i ];
  21321. p.copy( pointsFrustum[ i ] );
  21322. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21323. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21324. if ( p.x < _min.x ) _min.x = p.x;
  21325. if ( p.x > _max.x ) _max.x = p.x;
  21326. if ( p.y < _min.y ) _min.y = p.y;
  21327. if ( p.y > _max.y ) _max.y = p.y;
  21328. if ( p.z < _min.z ) _min.z = p.z;
  21329. if ( p.z > _max.z ) _max.z = p.z;
  21330. }
  21331. shadowCamera.left = _min.x;
  21332. shadowCamera.right = _max.x;
  21333. shadowCamera.top = _max.y;
  21334. shadowCamera.bottom = _min.y;
  21335. // can't really fit near/far
  21336. //shadowCamera.near = _min.z;
  21337. //shadowCamera.far = _max.z;
  21338. shadowCamera.updateProjectionMatrix();
  21339. }
  21340. // For the moment just ignore objects that have multiple materials with different animation methods
  21341. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21342. function getObjectMaterial( object ) {
  21343. return object.material instanceof THREE.MeshFaceMaterial
  21344. ? object.material.materials[ 0 ]
  21345. : object.material;
  21346. };
  21347. };
  21348. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21349. /**
  21350. * @author mikael emtinger / http://gomo.se/
  21351. * @author alteredq / http://alteredqualia.com/
  21352. */
  21353. THREE.SpritePlugin = function () {
  21354. var _gl, _renderer, _precision, _sprite = {};
  21355. this.init = function ( renderer ) {
  21356. _gl = renderer.context;
  21357. _renderer = renderer;
  21358. _precision = renderer.getPrecision();
  21359. _sprite.vertices = new Float32Array( 8 + 8 );
  21360. _sprite.faces = new Uint16Array( 6 );
  21361. var i = 0;
  21362. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21363. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21364. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21365. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21366. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21367. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21368. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21369. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21370. i = 0;
  21371. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21372. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21373. _sprite.vertexBuffer = _gl.createBuffer();
  21374. _sprite.elementBuffer = _gl.createBuffer();
  21375. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21376. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21377. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21378. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21379. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ], _precision );
  21380. _sprite.attributes = {};
  21381. _sprite.uniforms = {};
  21382. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21383. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21384. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21385. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21386. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21387. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21388. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21389. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21390. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21391. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21392. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21393. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  21394. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21395. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21396. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21397. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21398. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21399. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21400. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21401. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21402. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21403. };
  21404. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21405. var sprites = scene.__webglSprites,
  21406. nSprites = sprites.length;
  21407. if ( ! nSprites ) return;
  21408. var attributes = _sprite.attributes,
  21409. uniforms = _sprite.uniforms;
  21410. var invAspect = viewportHeight / viewportWidth;
  21411. var halfViewportWidth = viewportWidth * 0.5,
  21412. halfViewportHeight = viewportHeight * 0.5;
  21413. // setup gl
  21414. _gl.useProgram( _sprite.program );
  21415. _gl.enableVertexAttribArray( attributes.position );
  21416. _gl.enableVertexAttribArray( attributes.uv );
  21417. _gl.disable( _gl.CULL_FACE );
  21418. _gl.enable( _gl.BLEND );
  21419. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21420. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21421. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21422. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21423. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21424. _gl.activeTexture( _gl.TEXTURE0 );
  21425. _gl.uniform1i( uniforms.map, 0 );
  21426. var oldFogType = 0;
  21427. var sceneFogType = 0;
  21428. var fog = scene.fog;
  21429. if ( fog ) {
  21430. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21431. if ( fog instanceof THREE.Fog ) {
  21432. _gl.uniform1f( uniforms.fogNear, fog.near );
  21433. _gl.uniform1f( uniforms.fogFar, fog.far );
  21434. _gl.uniform1i( uniforms.fogType, 1 );
  21435. oldFogType = 1;
  21436. sceneFogType = 1;
  21437. } else if ( fog instanceof THREE.FogExp2 ) {
  21438. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21439. _gl.uniform1i( uniforms.fogType, 2 );
  21440. oldFogType = 2;
  21441. sceneFogType = 2;
  21442. }
  21443. } else {
  21444. _gl.uniform1i( uniforms.fogType, 0 );
  21445. oldFogType = 0;
  21446. sceneFogType = 0;
  21447. }
  21448. // update positions and sort
  21449. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21450. for( i = 0; i < nSprites; i ++ ) {
  21451. sprite = sprites[ i ];
  21452. material = sprite.material;
  21453. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21454. if ( ! material.useScreenCoordinates ) {
  21455. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21456. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21457. } else {
  21458. sprite.z = - sprite.position.z;
  21459. }
  21460. }
  21461. sprites.sort( painterSortStable );
  21462. // render all sprites
  21463. for( i = 0; i < nSprites; i ++ ) {
  21464. sprite = sprites[ i ];
  21465. material = sprite.material;
  21466. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21467. if ( material.map && material.map.image && material.map.image.width ) {
  21468. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21469. if ( material.useScreenCoordinates === true ) {
  21470. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21471. _gl.uniform3f(
  21472. uniforms.screenPosition,
  21473. ( ( sprite.position.x * _renderer.devicePixelRatio ) - halfViewportWidth ) / halfViewportWidth,
  21474. ( halfViewportHeight - ( sprite.position.y * _renderer.devicePixelRatio ) ) / halfViewportHeight,
  21475. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21476. );
  21477. scale[ 0 ] = _renderer.devicePixelRatio;
  21478. scale[ 1 ] = _renderer.devicePixelRatio;
  21479. } else {
  21480. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21481. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21482. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21483. scale[ 0 ] = 1;
  21484. scale[ 1 ] = 1;
  21485. }
  21486. if ( scene.fog && material.fog ) {
  21487. fogType = sceneFogType;
  21488. } else {
  21489. fogType = 0;
  21490. }
  21491. if ( oldFogType !== fogType ) {
  21492. _gl.uniform1i( uniforms.fogType, fogType );
  21493. oldFogType = fogType;
  21494. }
  21495. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21496. scale[ 0 ] *= size * invAspect * sprite.scale.x
  21497. scale[ 1 ] *= size * sprite.scale.y;
  21498. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21499. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21500. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21501. _gl.uniform1f( uniforms.opacity, material.opacity );
  21502. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21503. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21504. _gl.uniform2fv( uniforms.scale, scale );
  21505. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21506. _renderer.setDepthTest( material.depthTest );
  21507. _renderer.setDepthWrite( material.depthWrite );
  21508. _renderer.setTexture( material.map, 0 );
  21509. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21510. }
  21511. }
  21512. // restore gl
  21513. _gl.enable( _gl.CULL_FACE );
  21514. };
  21515. function createProgram ( shader, precision ) {
  21516. var program = _gl.createProgram();
  21517. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21518. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21519. var prefix = "precision " + precision + " float;\n";
  21520. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21521. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21522. _gl.compileShader( fragmentShader );
  21523. _gl.compileShader( vertexShader );
  21524. _gl.attachShader( program, fragmentShader );
  21525. _gl.attachShader( program, vertexShader );
  21526. _gl.linkProgram( program );
  21527. return program;
  21528. };
  21529. function painterSortStable ( a, b ) {
  21530. if ( a.z !== b.z ) {
  21531. return b.z - a.z;
  21532. } else {
  21533. return b.id - a.id;
  21534. }
  21535. };
  21536. };
  21537. /**
  21538. * @author alteredq / http://alteredqualia.com/
  21539. */
  21540. THREE.DepthPassPlugin = function () {
  21541. this.enabled = false;
  21542. this.renderTarget = null;
  21543. var _gl,
  21544. _renderer,
  21545. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21546. _frustum = new THREE.Frustum(),
  21547. _projScreenMatrix = new THREE.Matrix4();
  21548. this.init = function ( renderer ) {
  21549. _gl = renderer.context;
  21550. _renderer = renderer;
  21551. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21552. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21553. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21554. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21555. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21556. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21557. _depthMaterial._shadowPass = true;
  21558. _depthMaterialMorph._shadowPass = true;
  21559. _depthMaterialSkin._shadowPass = true;
  21560. _depthMaterialMorphSkin._shadowPass = true;
  21561. };
  21562. this.render = function ( scene, camera ) {
  21563. if ( ! this.enabled ) return;
  21564. this.update( scene, camera );
  21565. };
  21566. this.update = function ( scene, camera ) {
  21567. var i, il, j, jl, n,
  21568. program, buffer, material,
  21569. webglObject, object, light,
  21570. renderList,
  21571. fog = null;
  21572. // set GL state for depth map
  21573. _gl.clearColor( 1, 1, 1, 1 );
  21574. _gl.disable( _gl.BLEND );
  21575. _renderer.setDepthTest( true );
  21576. // update scene
  21577. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21578. // update camera matrices and frustum
  21579. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21580. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21581. _frustum.setFromMatrix( _projScreenMatrix );
  21582. // render depth map
  21583. _renderer.setRenderTarget( this.renderTarget );
  21584. _renderer.clear();
  21585. // set object matrices & frustum culling
  21586. renderList = scene.__webglObjects;
  21587. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21588. webglObject = renderList[ j ];
  21589. object = webglObject.object;
  21590. webglObject.render = false;
  21591. if ( object.visible ) {
  21592. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21593. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21594. webglObject.render = true;
  21595. }
  21596. }
  21597. }
  21598. // render regular objects
  21599. var objectMaterial, useMorphing, useSkinning;
  21600. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21601. webglObject = renderList[ j ];
  21602. if ( webglObject.render ) {
  21603. object = webglObject.object;
  21604. buffer = webglObject.buffer;
  21605. // todo: create proper depth material for particles
  21606. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21607. objectMaterial = getObjectMaterial( object );
  21608. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21609. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21610. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21611. if ( object.customDepthMaterial ) {
  21612. material = object.customDepthMaterial;
  21613. } else if ( useSkinning ) {
  21614. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21615. } else if ( useMorphing ) {
  21616. material = _depthMaterialMorph;
  21617. } else {
  21618. material = _depthMaterial;
  21619. }
  21620. if ( buffer instanceof THREE.BufferGeometry ) {
  21621. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21622. } else {
  21623. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21624. }
  21625. }
  21626. }
  21627. // set matrices and render immediate objects
  21628. renderList = scene.__webglObjectsImmediate;
  21629. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21630. webglObject = renderList[ j ];
  21631. object = webglObject.object;
  21632. if ( object.visible ) {
  21633. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21634. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21635. }
  21636. }
  21637. // restore GL state
  21638. var clearColor = _renderer.getClearColor(),
  21639. clearAlpha = _renderer.getClearAlpha();
  21640. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21641. _gl.enable( _gl.BLEND );
  21642. };
  21643. // For the moment just ignore objects that have multiple materials with different animation methods
  21644. // Only the first material will be taken into account for deciding which depth material to use
  21645. function getObjectMaterial( object ) {
  21646. return object.material instanceof THREE.MeshFaceMaterial
  21647. ? object.material.materials[ 0 ]
  21648. : object.material;
  21649. };
  21650. };
  21651. /**
  21652. * @author mikael emtinger / http://gomo.se/
  21653. */
  21654. THREE.ShaderFlares = {
  21655. 'lensFlareVertexTexture': {
  21656. vertexShader: [
  21657. "uniform lowp int renderType;",
  21658. "uniform vec3 screenPosition;",
  21659. "uniform vec2 scale;",
  21660. "uniform float rotation;",
  21661. "uniform sampler2D occlusionMap;",
  21662. "attribute vec2 position;",
  21663. "attribute vec2 uv;",
  21664. "varying vec2 vUV;",
  21665. "varying float vVisibility;",
  21666. "void main() {",
  21667. "vUV = uv;",
  21668. "vec2 pos = position;",
  21669. "if( renderType == 2 ) {",
  21670. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  21671. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  21672. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  21673. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  21674. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  21675. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  21676. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  21677. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  21678. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21679. "vVisibility = visibility.r / 9.0;",
  21680. "vVisibility *= 1.0 - visibility.g / 9.0;",
  21681. "vVisibility *= visibility.b / 9.0;",
  21682. "vVisibility *= 1.0 - visibility.a / 9.0;",
  21683. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21684. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21685. "}",
  21686. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21687. "}"
  21688. ].join( "\n" ),
  21689. fragmentShader: [
  21690. "uniform lowp int renderType;",
  21691. "uniform sampler2D map;",
  21692. "uniform float opacity;",
  21693. "uniform vec3 color;",
  21694. "varying vec2 vUV;",
  21695. "varying float vVisibility;",
  21696. "void main() {",
  21697. // pink square
  21698. "if( renderType == 0 ) {",
  21699. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21700. // restore
  21701. "} else if( renderType == 1 ) {",
  21702. "gl_FragColor = texture2D( map, vUV );",
  21703. // flare
  21704. "} else {",
  21705. "vec4 texture = texture2D( map, vUV );",
  21706. "texture.a *= opacity * vVisibility;",
  21707. "gl_FragColor = texture;",
  21708. "gl_FragColor.rgb *= color;",
  21709. "}",
  21710. "}"
  21711. ].join( "\n" )
  21712. },
  21713. 'lensFlare': {
  21714. vertexShader: [
  21715. "uniform lowp int renderType;",
  21716. "uniform vec3 screenPosition;",
  21717. "uniform vec2 scale;",
  21718. "uniform float rotation;",
  21719. "attribute vec2 position;",
  21720. "attribute vec2 uv;",
  21721. "varying vec2 vUV;",
  21722. "void main() {",
  21723. "vUV = uv;",
  21724. "vec2 pos = position;",
  21725. "if( renderType == 2 ) {",
  21726. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21727. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21728. "}",
  21729. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21730. "}"
  21731. ].join( "\n" ),
  21732. fragmentShader: [
  21733. "precision mediump float;",
  21734. "uniform lowp int renderType;",
  21735. "uniform sampler2D map;",
  21736. "uniform sampler2D occlusionMap;",
  21737. "uniform float opacity;",
  21738. "uniform vec3 color;",
  21739. "varying vec2 vUV;",
  21740. "void main() {",
  21741. // pink square
  21742. "if( renderType == 0 ) {",
  21743. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21744. // restore
  21745. "} else if( renderType == 1 ) {",
  21746. "gl_FragColor = texture2D( map, vUV );",
  21747. // flare
  21748. "} else {",
  21749. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  21750. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  21751. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  21752. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21753. "visibility = ( 1.0 - visibility / 4.0 );",
  21754. "vec4 texture = texture2D( map, vUV );",
  21755. "texture.a *= opacity * visibility;",
  21756. "gl_FragColor = texture;",
  21757. "gl_FragColor.rgb *= color;",
  21758. "}",
  21759. "}"
  21760. ].join( "\n" )
  21761. }
  21762. };
  21763. /**
  21764. * @author mikael emtinger / http://gomo.se/
  21765. * @author alteredq / http://alteredqualia.com/
  21766. *
  21767. */
  21768. THREE.ShaderSprite = {
  21769. 'sprite': {
  21770. vertexShader: [
  21771. "uniform int useScreenCoordinates;",
  21772. "uniform int sizeAttenuation;",
  21773. "uniform vec3 screenPosition;",
  21774. "uniform mat4 modelViewMatrix;",
  21775. "uniform mat4 projectionMatrix;",
  21776. "uniform float rotation;",
  21777. "uniform vec2 scale;",
  21778. "uniform vec2 alignment;",
  21779. "uniform vec2 uvOffset;",
  21780. "uniform vec2 uvScale;",
  21781. "attribute vec2 position;",
  21782. "attribute vec2 uv;",
  21783. "varying vec2 vUV;",
  21784. "void main() {",
  21785. "vUV = uvOffset + uv * uvScale;",
  21786. "vec2 alignedPosition = position + alignment;",
  21787. "vec2 rotatedPosition;",
  21788. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21789. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21790. "vec4 finalPosition;",
  21791. "if( useScreenCoordinates != 0 ) {",
  21792. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21793. "} else {",
  21794. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21795. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  21796. "}",
  21797. "gl_Position = finalPosition;",
  21798. "}"
  21799. ].join( "\n" ),
  21800. fragmentShader: [
  21801. "uniform vec3 color;",
  21802. "uniform sampler2D map;",
  21803. "uniform float opacity;",
  21804. "uniform int fogType;",
  21805. "uniform vec3 fogColor;",
  21806. "uniform float fogDensity;",
  21807. "uniform float fogNear;",
  21808. "uniform float fogFar;",
  21809. "uniform float alphaTest;",
  21810. "varying vec2 vUV;",
  21811. "void main() {",
  21812. "vec4 texture = texture2D( map, vUV );",
  21813. "if ( texture.a < alphaTest ) discard;",
  21814. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21815. "if ( fogType > 0 ) {",
  21816. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  21817. "float fogFactor = 0.0;",
  21818. "if ( fogType == 1 ) {",
  21819. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  21820. "} else {",
  21821. "const float LOG2 = 1.442695;",
  21822. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  21823. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  21824. "}",
  21825. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  21826. "}",
  21827. "}"
  21828. ].join( "\n" )
  21829. }
  21830. };