three.js 815 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. * @author bhouston / http://exocortex.com
  5. */
  6. var THREE = { REVISION: '66dev' };
  7. self.console = self.console || {
  8. info: function () {},
  9. log: function () {},
  10. debug: function () {},
  11. warn: function () {},
  12. error: function () {}
  13. };
  14. // based on https://github.com/documentcloud/underscore/blob/bf657be243a075b5e72acc8a83e6f12a564d8f55/underscore.js#L767
  15. THREE.extend = function ( obj, source ) {
  16. // ECMAScript5 compatibility based on: http://www.nczonline.net/blog/2012/12/11/are-your-mixins-ecmascript-5-compatible/
  17. if ( Object.keys ) {
  18. var keys = Object.keys( source );
  19. for (var i = 0, il = keys.length; i < il; i++) {
  20. var prop = keys[i];
  21. Object.defineProperty( obj, prop, Object.getOwnPropertyDescriptor( source, prop ) );
  22. }
  23. } else {
  24. var safeHasOwnProperty = {}.hasOwnProperty;
  25. for ( var prop in source ) {
  26. if ( safeHasOwnProperty.call( source, prop ) ) {
  27. obj[prop] = source[prop];
  28. }
  29. }
  30. }
  31. return obj;
  32. };
  33. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  34. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  35. // requestAnimationFrame polyfill by Erik Möller
  36. // fixes from Paul Irish and Tino Zijdel
  37. // using 'self' instead of 'window' for compatibility with both NodeJS and IE10.
  38. ( function () {
  39. var lastTime = 0;
  40. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  41. for ( var x = 0; x < vendors.length && !self.requestAnimationFrame; ++ x ) {
  42. self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ];
  43. self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  44. }
  45. if ( self.requestAnimationFrame === undefined && self['setTimeout'] !== undefined ) {
  46. self.requestAnimationFrame = function ( callback ) {
  47. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  48. var id = self.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  49. lastTime = currTime + timeToCall;
  50. return id;
  51. };
  52. }
  53. if( self.cancelAnimationFrame === undefined && self['clearTimeout'] !== undefined ) {
  54. self.cancelAnimationFrame = function ( id ) { self.clearTimeout( id ) };
  55. }
  56. }() );
  57. // GL STATE CONSTANTS
  58. THREE.CullFaceNone = 0;
  59. THREE.CullFaceBack = 1;
  60. THREE.CullFaceFront = 2;
  61. THREE.CullFaceFrontBack = 3;
  62. THREE.FrontFaceDirectionCW = 0;
  63. THREE.FrontFaceDirectionCCW = 1;
  64. // SHADOWING TYPES
  65. THREE.BasicShadowMap = 0;
  66. THREE.PCFShadowMap = 1;
  67. THREE.PCFSoftShadowMap = 2;
  68. // MATERIAL CONSTANTS
  69. // side
  70. THREE.FrontSide = 0;
  71. THREE.BackSide = 1;
  72. THREE.DoubleSide = 2;
  73. // shading
  74. THREE.NoShading = 0;
  75. THREE.FlatShading = 1;
  76. THREE.SmoothShading = 2;
  77. // colors
  78. THREE.NoColors = 0;
  79. THREE.FaceColors = 1;
  80. THREE.VertexColors = 2;
  81. // blending modes
  82. THREE.NoBlending = 0;
  83. THREE.NormalBlending = 1;
  84. THREE.AdditiveBlending = 2;
  85. THREE.SubtractiveBlending = 3;
  86. THREE.MultiplyBlending = 4;
  87. THREE.CustomBlending = 5;
  88. // custom blending equations
  89. // (numbers start from 100 not to clash with other
  90. // mappings to OpenGL constants defined in Texture.js)
  91. THREE.AddEquation = 100;
  92. THREE.SubtractEquation = 101;
  93. THREE.ReverseSubtractEquation = 102;
  94. // custom blending destination factors
  95. THREE.ZeroFactor = 200;
  96. THREE.OneFactor = 201;
  97. THREE.SrcColorFactor = 202;
  98. THREE.OneMinusSrcColorFactor = 203;
  99. THREE.SrcAlphaFactor = 204;
  100. THREE.OneMinusSrcAlphaFactor = 205;
  101. THREE.DstAlphaFactor = 206;
  102. THREE.OneMinusDstAlphaFactor = 207;
  103. // custom blending source factors
  104. //THREE.ZeroFactor = 200;
  105. //THREE.OneFactor = 201;
  106. //THREE.SrcAlphaFactor = 204;
  107. //THREE.OneMinusSrcAlphaFactor = 205;
  108. //THREE.DstAlphaFactor = 206;
  109. //THREE.OneMinusDstAlphaFactor = 207;
  110. THREE.DstColorFactor = 208;
  111. THREE.OneMinusDstColorFactor = 209;
  112. THREE.SrcAlphaSaturateFactor = 210;
  113. // TEXTURE CONSTANTS
  114. THREE.MultiplyOperation = 0;
  115. THREE.MixOperation = 1;
  116. THREE.AddOperation = 2;
  117. // Mapping modes
  118. THREE.UVMapping = function () {};
  119. THREE.CubeReflectionMapping = function () {};
  120. THREE.CubeRefractionMapping = function () {};
  121. THREE.SphericalReflectionMapping = function () {};
  122. THREE.SphericalRefractionMapping = function () {};
  123. // Wrapping modes
  124. THREE.RepeatWrapping = 1000;
  125. THREE.ClampToEdgeWrapping = 1001;
  126. THREE.MirroredRepeatWrapping = 1002;
  127. // Filters
  128. THREE.NearestFilter = 1003;
  129. THREE.NearestMipMapNearestFilter = 1004;
  130. THREE.NearestMipMapLinearFilter = 1005;
  131. THREE.LinearFilter = 1006;
  132. THREE.LinearMipMapNearestFilter = 1007;
  133. THREE.LinearMipMapLinearFilter = 1008;
  134. // Data types
  135. THREE.UnsignedByteType = 1009;
  136. THREE.ByteType = 1010;
  137. THREE.ShortType = 1011;
  138. THREE.UnsignedShortType = 1012;
  139. THREE.IntType = 1013;
  140. THREE.UnsignedIntType = 1014;
  141. THREE.FloatType = 1015;
  142. // Pixel types
  143. //THREE.UnsignedByteType = 1009;
  144. THREE.UnsignedShort4444Type = 1016;
  145. THREE.UnsignedShort5551Type = 1017;
  146. THREE.UnsignedShort565Type = 1018;
  147. // Pixel formats
  148. THREE.AlphaFormat = 1019;
  149. THREE.RGBFormat = 1020;
  150. THREE.RGBAFormat = 1021;
  151. THREE.LuminanceFormat = 1022;
  152. THREE.LuminanceAlphaFormat = 1023;
  153. // Compressed texture formats
  154. THREE.RGB_S3TC_DXT1_Format = 2001;
  155. THREE.RGBA_S3TC_DXT1_Format = 2002;
  156. THREE.RGBA_S3TC_DXT3_Format = 2003;
  157. THREE.RGBA_S3TC_DXT5_Format = 2004;
  158. /*
  159. // Potential future PVRTC compressed texture formats
  160. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  161. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  162. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  163. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  164. */
  165. /**
  166. * @author mrdoob / http://mrdoob.com/
  167. */
  168. THREE.Color = function ( color ) {
  169. if ( arguments.length === 3 ) {
  170. return this.setRGB( arguments[ 0 ], arguments[ 1 ], arguments[ 2 ] );
  171. }
  172. return this.set( color )
  173. };
  174. THREE.Color.prototype = {
  175. constructor: THREE.Color,
  176. r: 1, g: 1, b: 1,
  177. set: function ( value ) {
  178. if ( value instanceof THREE.Color ) {
  179. this.copy( value );
  180. } else if ( typeof value === 'number' ) {
  181. this.setHex( value );
  182. } else if ( typeof value === 'string' ) {
  183. this.setStyle( value );
  184. }
  185. return this;
  186. },
  187. setHex: function ( hex ) {
  188. hex = Math.floor( hex );
  189. this.r = ( hex >> 16 & 255 ) / 255;
  190. this.g = ( hex >> 8 & 255 ) / 255;
  191. this.b = ( hex & 255 ) / 255;
  192. return this;
  193. },
  194. setRGB: function ( r, g, b ) {
  195. this.r = r;
  196. this.g = g;
  197. this.b = b;
  198. return this;
  199. },
  200. setHSL: function ( h, s, l ) {
  201. // h,s,l ranges are in 0.0 - 1.0
  202. if ( s === 0 ) {
  203. this.r = this.g = this.b = l;
  204. } else {
  205. var hue2rgb = function ( p, q, t ) {
  206. if ( t < 0 ) t += 1;
  207. if ( t > 1 ) t -= 1;
  208. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  209. if ( t < 1 / 2 ) return q;
  210. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  211. return p;
  212. };
  213. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  214. var q = ( 2 * l ) - p;
  215. this.r = hue2rgb( q, p, h + 1 / 3 );
  216. this.g = hue2rgb( q, p, h );
  217. this.b = hue2rgb( q, p, h - 1 / 3 );
  218. }
  219. return this;
  220. },
  221. setStyle: function ( style ) {
  222. // rgb(255,0,0)
  223. if ( /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test( style ) ) {
  224. var color = /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec( style );
  225. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  226. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  227. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  228. return this;
  229. }
  230. // rgb(100%,0%,0%)
  231. if ( /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test( style ) ) {
  232. var color = /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec( style );
  233. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  234. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  235. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  236. return this;
  237. }
  238. // #ff0000
  239. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  240. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  241. this.setHex( parseInt( color[ 1 ], 16 ) );
  242. return this;
  243. }
  244. // #f00
  245. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  246. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  247. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  248. return this;
  249. }
  250. // red
  251. if ( /^(\w+)$/i.test( style ) ) {
  252. this.setHex( THREE.ColorKeywords[ style ] );
  253. return this;
  254. }
  255. },
  256. copy: function ( color ) {
  257. this.r = color.r;
  258. this.g = color.g;
  259. this.b = color.b;
  260. return this;
  261. },
  262. copyGammaToLinear: function ( color ) {
  263. this.r = color.r * color.r;
  264. this.g = color.g * color.g;
  265. this.b = color.b * color.b;
  266. return this;
  267. },
  268. copyLinearToGamma: function ( color ) {
  269. this.r = Math.sqrt( color.r );
  270. this.g = Math.sqrt( color.g );
  271. this.b = Math.sqrt( color.b );
  272. return this;
  273. },
  274. convertGammaToLinear: function () {
  275. var r = this.r, g = this.g, b = this.b;
  276. this.r = r * r;
  277. this.g = g * g;
  278. this.b = b * b;
  279. return this;
  280. },
  281. convertLinearToGamma: function () {
  282. this.r = Math.sqrt( this.r );
  283. this.g = Math.sqrt( this.g );
  284. this.b = Math.sqrt( this.b );
  285. return this;
  286. },
  287. getHex: function () {
  288. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  289. },
  290. getHexString: function () {
  291. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  292. },
  293. getHSL: function ( optionalTarget ) {
  294. // h,s,l ranges are in 0.0 - 1.0
  295. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  296. var r = this.r, g = this.g, b = this.b;
  297. var max = Math.max( r, g, b );
  298. var min = Math.min( r, g, b );
  299. var hue, saturation;
  300. var lightness = ( min + max ) / 2.0;
  301. if ( min === max ) {
  302. hue = 0;
  303. saturation = 0;
  304. } else {
  305. var delta = max - min;
  306. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  307. switch ( max ) {
  308. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  309. case g: hue = ( b - r ) / delta + 2; break;
  310. case b: hue = ( r - g ) / delta + 4; break;
  311. }
  312. hue /= 6;
  313. }
  314. hsl.h = hue;
  315. hsl.s = saturation;
  316. hsl.l = lightness;
  317. return hsl;
  318. },
  319. getStyle: function () {
  320. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  321. },
  322. offsetHSL: function ( h, s, l ) {
  323. var hsl = this.getHSL();
  324. hsl.h += h; hsl.s += s; hsl.l += l;
  325. this.setHSL( hsl.h, hsl.s, hsl.l );
  326. return this;
  327. },
  328. add: function ( color ) {
  329. this.r += color.r;
  330. this.g += color.g;
  331. this.b += color.b;
  332. return this;
  333. },
  334. addColors: function ( color1, color2 ) {
  335. this.r = color1.r + color2.r;
  336. this.g = color1.g + color2.g;
  337. this.b = color1.b + color2.b;
  338. return this;
  339. },
  340. addScalar: function ( s ) {
  341. this.r += s;
  342. this.g += s;
  343. this.b += s;
  344. return this;
  345. },
  346. multiply: function ( color ) {
  347. this.r *= color.r;
  348. this.g *= color.g;
  349. this.b *= color.b;
  350. return this;
  351. },
  352. multiplyScalar: function ( s ) {
  353. this.r *= s;
  354. this.g *= s;
  355. this.b *= s;
  356. return this;
  357. },
  358. lerp: function ( color, alpha ) {
  359. this.r += ( color.r - this.r ) * alpha;
  360. this.g += ( color.g - this.g ) * alpha;
  361. this.b += ( color.b - this.b ) * alpha;
  362. return this;
  363. },
  364. equals: function ( c ) {
  365. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  366. },
  367. fromArray: function ( array ) {
  368. this.r = array[ 0 ];
  369. this.g = array[ 1 ];
  370. this.b = array[ 2 ];
  371. return this;
  372. },
  373. toArray: function () {
  374. return [ this.r, this.g, this.b ];
  375. },
  376. clone: function () {
  377. return new THREE.Color().setRGB( this.r, this.g, this.b );
  378. }
  379. };
  380. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  381. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  382. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  383. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  384. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  385. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  386. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  387. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  388. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  389. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  390. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  391. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  392. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  393. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  394. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  395. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  396. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  397. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  398. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  399. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  400. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  401. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  402. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  403. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  404. /**
  405. * @author mikael emtinger / http://gomo.se/
  406. * @author alteredq / http://alteredqualia.com/
  407. * @author WestLangley / http://github.com/WestLangley
  408. * @author bhouston / http://exocortex.com
  409. */
  410. THREE.Quaternion = function ( x, y, z, w ) {
  411. this._x = x || 0;
  412. this._y = y || 0;
  413. this._z = z || 0;
  414. this._w = ( w !== undefined ) ? w : 1;
  415. };
  416. THREE.Quaternion.prototype = {
  417. constructor: THREE.Quaternion,
  418. _x: 0,_y: 0, _z: 0, _w: 0,
  419. _euler: undefined,
  420. _updateEuler: function ( callback ) {
  421. if ( this._euler !== undefined ) {
  422. this._euler.setFromQuaternion( this, undefined, false );
  423. }
  424. },
  425. get x () {
  426. return this._x;
  427. },
  428. set x ( value ) {
  429. this._x = value;
  430. this._updateEuler();
  431. },
  432. get y () {
  433. return this._y;
  434. },
  435. set y ( value ) {
  436. this._y = value;
  437. this._updateEuler();
  438. },
  439. get z () {
  440. return this._z;
  441. },
  442. set z ( value ) {
  443. this._z = value;
  444. this._updateEuler();
  445. },
  446. get w () {
  447. return this._w;
  448. },
  449. set w ( value ) {
  450. this._w = value;
  451. this._updateEuler();
  452. },
  453. set: function ( x, y, z, w ) {
  454. this._x = x;
  455. this._y = y;
  456. this._z = z;
  457. this._w = w;
  458. this._updateEuler();
  459. return this;
  460. },
  461. copy: function ( quaternion ) {
  462. this._x = quaternion._x;
  463. this._y = quaternion._y;
  464. this._z = quaternion._z;
  465. this._w = quaternion._w;
  466. this._updateEuler();
  467. return this;
  468. },
  469. setFromEuler: function ( euler, update ) {
  470. if ( euler instanceof THREE.Euler === false ) {
  471. throw new Error( 'ERROR: Quaternion\'s .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  472. }
  473. // http://www.mathworks.com/matlabcentral/fileexchange/
  474. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  475. // content/SpinCalc.m
  476. var c1 = Math.cos( euler._x / 2 );
  477. var c2 = Math.cos( euler._y / 2 );
  478. var c3 = Math.cos( euler._z / 2 );
  479. var s1 = Math.sin( euler._x / 2 );
  480. var s2 = Math.sin( euler._y / 2 );
  481. var s3 = Math.sin( euler._z / 2 );
  482. if ( euler.order === 'XYZ' ) {
  483. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  484. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  485. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  486. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  487. } else if ( euler.order === 'YXZ' ) {
  488. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  489. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  490. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  491. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  492. } else if ( euler.order === 'ZXY' ) {
  493. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  494. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  495. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  496. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  497. } else if ( euler.order === 'ZYX' ) {
  498. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  499. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  500. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  501. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  502. } else if ( euler.order === 'YZX' ) {
  503. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  504. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  505. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  506. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  507. } else if ( euler.order === 'XZY' ) {
  508. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  509. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  510. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  511. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  512. }
  513. if ( update !== false ) this._updateEuler();
  514. return this;
  515. },
  516. setFromAxisAngle: function ( axis, angle ) {
  517. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  518. // axis have to be normalized
  519. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  520. this._x = axis.x * s;
  521. this._y = axis.y * s;
  522. this._z = axis.z * s;
  523. this._w = Math.cos( halfAngle );
  524. this._updateEuler();
  525. return this;
  526. },
  527. setFromRotationMatrix: function ( m ) {
  528. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  529. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  530. var te = m.elements,
  531. m11 = te[0], m12 = te[4], m13 = te[8],
  532. m21 = te[1], m22 = te[5], m23 = te[9],
  533. m31 = te[2], m32 = te[6], m33 = te[10],
  534. trace = m11 + m22 + m33,
  535. s;
  536. if ( trace > 0 ) {
  537. s = 0.5 / Math.sqrt( trace + 1.0 );
  538. this._w = 0.25 / s;
  539. this._x = ( m32 - m23 ) * s;
  540. this._y = ( m13 - m31 ) * s;
  541. this._z = ( m21 - m12 ) * s;
  542. } else if ( m11 > m22 && m11 > m33 ) {
  543. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  544. this._w = (m32 - m23 ) / s;
  545. this._x = 0.25 * s;
  546. this._y = (m12 + m21 ) / s;
  547. this._z = (m13 + m31 ) / s;
  548. } else if ( m22 > m33 ) {
  549. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  550. this._w = (m13 - m31 ) / s;
  551. this._x = (m12 + m21 ) / s;
  552. this._y = 0.25 * s;
  553. this._z = (m23 + m32 ) / s;
  554. } else {
  555. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  556. this._w = ( m21 - m12 ) / s;
  557. this._x = ( m13 + m31 ) / s;
  558. this._y = ( m23 + m32 ) / s;
  559. this._z = 0.25 * s;
  560. }
  561. this._updateEuler();
  562. return this;
  563. },
  564. inverse: function () {
  565. this.conjugate().normalize();
  566. return this;
  567. },
  568. conjugate: function () {
  569. this._x *= -1;
  570. this._y *= -1;
  571. this._z *= -1;
  572. this._updateEuler();
  573. return this;
  574. },
  575. lengthSq: function () {
  576. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  577. },
  578. length: function () {
  579. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  580. },
  581. normalize: function () {
  582. var l = this.length();
  583. if ( l === 0 ) {
  584. this._x = 0;
  585. this._y = 0;
  586. this._z = 0;
  587. this._w = 1;
  588. } else {
  589. l = 1 / l;
  590. this._x = this._x * l;
  591. this._y = this._y * l;
  592. this._z = this._z * l;
  593. this._w = this._w * l;
  594. }
  595. return this;
  596. },
  597. multiply: function ( q, p ) {
  598. if ( p !== undefined ) {
  599. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  600. return this.multiplyQuaternions( q, p );
  601. }
  602. return this.multiplyQuaternions( this, q );
  603. },
  604. multiplyQuaternions: function ( a, b ) {
  605. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  606. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  607. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  608. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  609. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  610. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  611. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  612. this._updateEuler();
  613. return this;
  614. },
  615. multiplyVector3: function ( vector ) {
  616. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  617. return vector.applyQuaternion( this );
  618. },
  619. slerp: function ( qb, t ) {
  620. var x = this._x, y = this._y, z = this._z, w = this._w;
  621. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  622. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  623. if ( cosHalfTheta < 0 ) {
  624. this._w = -qb._w;
  625. this._x = -qb._x;
  626. this._y = -qb._y;
  627. this._z = -qb._z;
  628. cosHalfTheta = -cosHalfTheta;
  629. } else {
  630. this.copy( qb );
  631. }
  632. if ( cosHalfTheta >= 1.0 ) {
  633. this._w = w;
  634. this._x = x;
  635. this._y = y;
  636. this._z = z;
  637. return this;
  638. }
  639. var halfTheta = Math.acos( cosHalfTheta );
  640. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  641. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  642. this._w = 0.5 * ( w + this._w );
  643. this._x = 0.5 * ( x + this._x );
  644. this._y = 0.5 * ( y + this._y );
  645. this._z = 0.5 * ( z + this._z );
  646. return this;
  647. }
  648. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  649. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  650. this._w = ( w * ratioA + this._w * ratioB );
  651. this._x = ( x * ratioA + this._x * ratioB );
  652. this._y = ( y * ratioA + this._y * ratioB );
  653. this._z = ( z * ratioA + this._z * ratioB );
  654. this._updateEuler();
  655. return this;
  656. },
  657. equals: function ( quaternion ) {
  658. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  659. },
  660. fromArray: function ( array ) {
  661. this._x = array[ 0 ];
  662. this._y = array[ 1 ];
  663. this._z = array[ 2 ];
  664. this._w = array[ 3 ];
  665. this._updateEuler();
  666. return this;
  667. },
  668. toArray: function () {
  669. return [ this._x, this._y, this._z, this._w ];
  670. },
  671. clone: function () {
  672. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  673. }
  674. };
  675. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  676. return qm.copy( qa ).slerp( qb, t );
  677. }
  678. /**
  679. * @author mrdoob / http://mrdoob.com/
  680. * @author philogb / http://blog.thejit.org/
  681. * @author egraether / http://egraether.com/
  682. * @author zz85 / http://www.lab4games.net/zz85/blog
  683. */
  684. THREE.Vector2 = function ( x, y ) {
  685. this.x = x || 0;
  686. this.y = y || 0;
  687. };
  688. THREE.Vector2.prototype = {
  689. constructor: THREE.Vector2,
  690. set: function ( x, y ) {
  691. this.x = x;
  692. this.y = y;
  693. return this;
  694. },
  695. setX: function ( x ) {
  696. this.x = x;
  697. return this;
  698. },
  699. setY: function ( y ) {
  700. this.y = y;
  701. return this;
  702. },
  703. setComponent: function ( index, value ) {
  704. switch ( index ) {
  705. case 0: this.x = value; break;
  706. case 1: this.y = value; break;
  707. default: throw new Error( "index is out of range: " + index );
  708. }
  709. },
  710. getComponent: function ( index ) {
  711. switch ( index ) {
  712. case 0: return this.x;
  713. case 1: return this.y;
  714. default: throw new Error( "index is out of range: " + index );
  715. }
  716. },
  717. copy: function ( v ) {
  718. this.x = v.x;
  719. this.y = v.y;
  720. return this;
  721. },
  722. add: function ( v, w ) {
  723. if ( w !== undefined ) {
  724. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  725. return this.addVectors( v, w );
  726. }
  727. this.x += v.x;
  728. this.y += v.y;
  729. return this;
  730. },
  731. addVectors: function ( a, b ) {
  732. this.x = a.x + b.x;
  733. this.y = a.y + b.y;
  734. return this;
  735. },
  736. addScalar: function ( s ) {
  737. this.x += s;
  738. this.y += s;
  739. return this;
  740. },
  741. sub: function ( v, w ) {
  742. if ( w !== undefined ) {
  743. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  744. return this.subVectors( v, w );
  745. }
  746. this.x -= v.x;
  747. this.y -= v.y;
  748. return this;
  749. },
  750. subVectors: function ( a, b ) {
  751. this.x = a.x - b.x;
  752. this.y = a.y - b.y;
  753. return this;
  754. },
  755. multiplyScalar: function ( s ) {
  756. this.x *= s;
  757. this.y *= s;
  758. return this;
  759. },
  760. divideScalar: function ( scalar ) {
  761. if ( scalar !== 0 ) {
  762. var invScalar = 1 / scalar;
  763. this.x *= invScalar;
  764. this.y *= invScalar;
  765. } else {
  766. this.x = 0;
  767. this.y = 0;
  768. }
  769. return this;
  770. },
  771. min: function ( v ) {
  772. if ( this.x > v.x ) {
  773. this.x = v.x;
  774. }
  775. if ( this.y > v.y ) {
  776. this.y = v.y;
  777. }
  778. return this;
  779. },
  780. max: function ( v ) {
  781. if ( this.x < v.x ) {
  782. this.x = v.x;
  783. }
  784. if ( this.y < v.y ) {
  785. this.y = v.y;
  786. }
  787. return this;
  788. },
  789. clamp: function ( min, max ) {
  790. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  791. if ( this.x < min.x ) {
  792. this.x = min.x;
  793. } else if ( this.x > max.x ) {
  794. this.x = max.x;
  795. }
  796. if ( this.y < min.y ) {
  797. this.y = min.y;
  798. } else if ( this.y > max.y ) {
  799. this.y = max.y;
  800. }
  801. return this;
  802. },
  803. negate: function() {
  804. return this.multiplyScalar( - 1 );
  805. },
  806. dot: function ( v ) {
  807. return this.x * v.x + this.y * v.y;
  808. },
  809. lengthSq: function () {
  810. return this.x * this.x + this.y * this.y;
  811. },
  812. length: function () {
  813. return Math.sqrt( this.x * this.x + this.y * this.y );
  814. },
  815. normalize: function () {
  816. return this.divideScalar( this.length() );
  817. },
  818. distanceTo: function ( v ) {
  819. return Math.sqrt( this.distanceToSquared( v ) );
  820. },
  821. distanceToSquared: function ( v ) {
  822. var dx = this.x - v.x, dy = this.y - v.y;
  823. return dx * dx + dy * dy;
  824. },
  825. setLength: function ( l ) {
  826. var oldLength = this.length();
  827. if ( oldLength !== 0 && l !== oldLength ) {
  828. this.multiplyScalar( l / oldLength );
  829. }
  830. return this;
  831. },
  832. lerp: function ( v, alpha ) {
  833. this.x += ( v.x - this.x ) * alpha;
  834. this.y += ( v.y - this.y ) * alpha;
  835. return this;
  836. },
  837. equals: function( v ) {
  838. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  839. },
  840. fromArray: function ( array ) {
  841. this.x = array[ 0 ];
  842. this.y = array[ 1 ];
  843. return this;
  844. },
  845. toArray: function () {
  846. return [ this.x, this.y ];
  847. },
  848. clone: function () {
  849. return new THREE.Vector2( this.x, this.y );
  850. }
  851. };
  852. /**
  853. * @author mrdoob / http://mrdoob.com/
  854. * @author *kile / http://kile.stravaganza.org/
  855. * @author philogb / http://blog.thejit.org/
  856. * @author mikael emtinger / http://gomo.se/
  857. * @author egraether / http://egraether.com/
  858. * @author WestLangley / http://github.com/WestLangley
  859. */
  860. THREE.Vector3 = function ( x, y, z ) {
  861. this.x = x || 0;
  862. this.y = y || 0;
  863. this.z = z || 0;
  864. };
  865. THREE.Vector3.prototype = {
  866. constructor: THREE.Vector3,
  867. set: function ( x, y, z ) {
  868. this.x = x;
  869. this.y = y;
  870. this.z = z;
  871. return this;
  872. },
  873. setX: function ( x ) {
  874. this.x = x;
  875. return this;
  876. },
  877. setY: function ( y ) {
  878. this.y = y;
  879. return this;
  880. },
  881. setZ: function ( z ) {
  882. this.z = z;
  883. return this;
  884. },
  885. setComponent: function ( index, value ) {
  886. switch ( index ) {
  887. case 0: this.x = value; break;
  888. case 1: this.y = value; break;
  889. case 2: this.z = value; break;
  890. default: throw new Error( "index is out of range: " + index );
  891. }
  892. },
  893. getComponent: function ( index ) {
  894. switch ( index ) {
  895. case 0: return this.x;
  896. case 1: return this.y;
  897. case 2: return this.z;
  898. default: throw new Error( "index is out of range: " + index );
  899. }
  900. },
  901. copy: function ( v ) {
  902. this.x = v.x;
  903. this.y = v.y;
  904. this.z = v.z;
  905. return this;
  906. },
  907. add: function ( v, w ) {
  908. if ( w !== undefined ) {
  909. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  910. return this.addVectors( v, w );
  911. }
  912. this.x += v.x;
  913. this.y += v.y;
  914. this.z += v.z;
  915. return this;
  916. },
  917. addScalar: function ( s ) {
  918. this.x += s;
  919. this.y += s;
  920. this.z += s;
  921. return this;
  922. },
  923. addVectors: function ( a, b ) {
  924. this.x = a.x + b.x;
  925. this.y = a.y + b.y;
  926. this.z = a.z + b.z;
  927. return this;
  928. },
  929. sub: function ( v, w ) {
  930. if ( w !== undefined ) {
  931. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  932. return this.subVectors( v, w );
  933. }
  934. this.x -= v.x;
  935. this.y -= v.y;
  936. this.z -= v.z;
  937. return this;
  938. },
  939. subVectors: function ( a, b ) {
  940. this.x = a.x - b.x;
  941. this.y = a.y - b.y;
  942. this.z = a.z - b.z;
  943. return this;
  944. },
  945. multiply: function ( v, w ) {
  946. if ( w !== undefined ) {
  947. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  948. return this.multiplyVectors( v, w );
  949. }
  950. this.x *= v.x;
  951. this.y *= v.y;
  952. this.z *= v.z;
  953. return this;
  954. },
  955. multiplyScalar: function ( scalar ) {
  956. this.x *= scalar;
  957. this.y *= scalar;
  958. this.z *= scalar;
  959. return this;
  960. },
  961. multiplyVectors: function ( a, b ) {
  962. this.x = a.x * b.x;
  963. this.y = a.y * b.y;
  964. this.z = a.z * b.z;
  965. return this;
  966. },
  967. applyMatrix3: function ( m ) {
  968. var x = this.x;
  969. var y = this.y;
  970. var z = this.z;
  971. var e = m.elements;
  972. this.x = e[0] * x + e[3] * y + e[6] * z;
  973. this.y = e[1] * x + e[4] * y + e[7] * z;
  974. this.z = e[2] * x + e[5] * y + e[8] * z;
  975. return this;
  976. },
  977. applyMatrix4: function ( m ) {
  978. // input: THREE.Matrix4 affine matrix
  979. var x = this.x, y = this.y, z = this.z;
  980. var e = m.elements;
  981. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  982. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  983. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  984. return this;
  985. },
  986. applyProjection: function ( m ) {
  987. // input: THREE.Matrix4 projection matrix
  988. var x = this.x, y = this.y, z = this.z;
  989. var e = m.elements;
  990. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  991. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  992. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  993. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  994. return this;
  995. },
  996. applyQuaternion: function ( q ) {
  997. var x = this.x;
  998. var y = this.y;
  999. var z = this.z;
  1000. var qx = q.x;
  1001. var qy = q.y;
  1002. var qz = q.z;
  1003. var qw = q.w;
  1004. // calculate quat * vector
  1005. var ix = qw * x + qy * z - qz * y;
  1006. var iy = qw * y + qz * x - qx * z;
  1007. var iz = qw * z + qx * y - qy * x;
  1008. var iw = -qx * x - qy * y - qz * z;
  1009. // calculate result * inverse quat
  1010. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1011. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1012. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1013. return this;
  1014. },
  1015. transformDirection: function ( m ) {
  1016. // input: THREE.Matrix4 affine matrix
  1017. // vector interpreted as a direction
  1018. var x = this.x, y = this.y, z = this.z;
  1019. var e = m.elements;
  1020. this.x = e[0] * x + e[4] * y + e[8] * z;
  1021. this.y = e[1] * x + e[5] * y + e[9] * z;
  1022. this.z = e[2] * x + e[6] * y + e[10] * z;
  1023. this.normalize();
  1024. return this;
  1025. },
  1026. divide: function ( v ) {
  1027. this.x /= v.x;
  1028. this.y /= v.y;
  1029. this.z /= v.z;
  1030. return this;
  1031. },
  1032. divideScalar: function ( scalar ) {
  1033. if ( scalar !== 0 ) {
  1034. var invScalar = 1 / scalar;
  1035. this.x *= invScalar;
  1036. this.y *= invScalar;
  1037. this.z *= invScalar;
  1038. } else {
  1039. this.x = 0;
  1040. this.y = 0;
  1041. this.z = 0;
  1042. }
  1043. return this;
  1044. },
  1045. min: function ( v ) {
  1046. if ( this.x > v.x ) {
  1047. this.x = v.x;
  1048. }
  1049. if ( this.y > v.y ) {
  1050. this.y = v.y;
  1051. }
  1052. if ( this.z > v.z ) {
  1053. this.z = v.z;
  1054. }
  1055. return this;
  1056. },
  1057. max: function ( v ) {
  1058. if ( this.x < v.x ) {
  1059. this.x = v.x;
  1060. }
  1061. if ( this.y < v.y ) {
  1062. this.y = v.y;
  1063. }
  1064. if ( this.z < v.z ) {
  1065. this.z = v.z;
  1066. }
  1067. return this;
  1068. },
  1069. clamp: function ( min, max ) {
  1070. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1071. if ( this.x < min.x ) {
  1072. this.x = min.x;
  1073. } else if ( this.x > max.x ) {
  1074. this.x = max.x;
  1075. }
  1076. if ( this.y < min.y ) {
  1077. this.y = min.y;
  1078. } else if ( this.y > max.y ) {
  1079. this.y = max.y;
  1080. }
  1081. if ( this.z < min.z ) {
  1082. this.z = min.z;
  1083. } else if ( this.z > max.z ) {
  1084. this.z = max.z;
  1085. }
  1086. return this;
  1087. },
  1088. negate: function () {
  1089. return this.multiplyScalar( - 1 );
  1090. },
  1091. dot: function ( v ) {
  1092. return this.x * v.x + this.y * v.y + this.z * v.z;
  1093. },
  1094. lengthSq: function () {
  1095. return this.x * this.x + this.y * this.y + this.z * this.z;
  1096. },
  1097. length: function () {
  1098. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1099. },
  1100. lengthManhattan: function () {
  1101. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1102. },
  1103. normalize: function () {
  1104. return this.divideScalar( this.length() );
  1105. },
  1106. setLength: function ( l ) {
  1107. var oldLength = this.length();
  1108. if ( oldLength !== 0 && l !== oldLength ) {
  1109. this.multiplyScalar( l / oldLength );
  1110. }
  1111. return this;
  1112. },
  1113. lerp: function ( v, alpha ) {
  1114. this.x += ( v.x - this.x ) * alpha;
  1115. this.y += ( v.y - this.y ) * alpha;
  1116. this.z += ( v.z - this.z ) * alpha;
  1117. return this;
  1118. },
  1119. cross: function ( v, w ) {
  1120. if ( w !== undefined ) {
  1121. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1122. return this.crossVectors( v, w );
  1123. }
  1124. var x = this.x, y = this.y, z = this.z;
  1125. this.x = y * v.z - z * v.y;
  1126. this.y = z * v.x - x * v.z;
  1127. this.z = x * v.y - y * v.x;
  1128. return this;
  1129. },
  1130. crossVectors: function ( a, b ) {
  1131. var ax = a.x, ay = a.y, az = a.z;
  1132. var bx = b.x, by = b.y, bz = b.z;
  1133. this.x = ay * bz - az * by;
  1134. this.y = az * bx - ax * bz;
  1135. this.z = ax * by - ay * bx;
  1136. return this;
  1137. },
  1138. angleTo: function ( v ) {
  1139. var theta = this.dot( v ) / ( this.length() * v.length() );
  1140. // clamp, to handle numerical problems
  1141. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1142. },
  1143. distanceTo: function ( v ) {
  1144. return Math.sqrt( this.distanceToSquared( v ) );
  1145. },
  1146. distanceToSquared: function ( v ) {
  1147. var dx = this.x - v.x;
  1148. var dy = this.y - v.y;
  1149. var dz = this.z - v.z;
  1150. return dx * dx + dy * dy + dz * dz;
  1151. },
  1152. setEulerFromRotationMatrix: function ( m, order ) {
  1153. console.error( "REMOVED: Vector3\'s setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code.");
  1154. },
  1155. setEulerFromQuaternion: function ( q, order ) {
  1156. console.error( "REMOVED: Vector3\'s setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code.");
  1157. },
  1158. getPositionFromMatrix: function ( m ) {
  1159. console.warn( "DEPRECATED: Vector3\'s .getPositionFromMatrix() has been renamed to .setFromMatrixPosition(). Please update your code." );
  1160. return this.setFromMatrixPosition( m );
  1161. },
  1162. getScaleFromMatrix: function ( m ) {
  1163. console.warn( "DEPRECATED: Vector3\'s .getScaleFromMatrix() has been renamed to .setFromMatrixScale(). Please update your code." );
  1164. return this.setFromMatrixScale( m );
  1165. },
  1166. getColumnFromMatrix: function ( index, matrix ) {
  1167. console.warn( "DEPRECATED: Vector3\'s .getColumnFromMatrix() has been renamed to .setFromMatrixColumn(). Please update your code." );
  1168. return this.setFromMatrixColumn( index, matrix );
  1169. },
  1170. setFromMatrixPosition: function ( m ) {
  1171. this.x = m.elements[ 12 ];
  1172. this.y = m.elements[ 13 ];
  1173. this.z = m.elements[ 14 ];
  1174. return this;
  1175. },
  1176. setFromMatrixScale: function ( m ) {
  1177. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1178. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1179. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1180. this.x = sx;
  1181. this.y = sy;
  1182. this.z = sz;
  1183. return this;
  1184. },
  1185. setFromMatrixColumn: function ( index, matrix ) {
  1186. var offset = index * 4;
  1187. var me = matrix.elements;
  1188. this.x = me[ offset ];
  1189. this.y = me[ offset + 1 ];
  1190. this.z = me[ offset + 2 ];
  1191. return this;
  1192. },
  1193. equals: function ( v ) {
  1194. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1195. },
  1196. fromArray: function ( array ) {
  1197. this.x = array[ 0 ];
  1198. this.y = array[ 1 ];
  1199. this.z = array[ 2 ];
  1200. return this;
  1201. },
  1202. toArray: function () {
  1203. return [ this.x, this.y, this.z ];
  1204. },
  1205. clone: function () {
  1206. return new THREE.Vector3( this.x, this.y, this.z );
  1207. }
  1208. };
  1209. THREE.extend( THREE.Vector3.prototype, {
  1210. applyEuler: function () {
  1211. var quaternion = new THREE.Quaternion();
  1212. return function ( euler ) {
  1213. if ( euler instanceof THREE.Euler === false ) {
  1214. console.error( 'ERROR: Vector3\'s .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  1215. }
  1216. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1217. return this;
  1218. };
  1219. }(),
  1220. applyAxisAngle: function () {
  1221. var quaternion = new THREE.Quaternion();
  1222. return function ( axis, angle ) {
  1223. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1224. return this;
  1225. };
  1226. }(),
  1227. projectOnVector: function () {
  1228. var v1 = new THREE.Vector3();
  1229. return function ( vector ) {
  1230. v1.copy( vector ).normalize();
  1231. var d = this.dot( v1 );
  1232. return this.copy( v1 ).multiplyScalar( d );
  1233. };
  1234. }(),
  1235. projectOnPlane: function () {
  1236. var v1 = new THREE.Vector3();
  1237. return function ( planeNormal ) {
  1238. v1.copy( this ).projectOnVector( planeNormal );
  1239. return this.sub( v1 );
  1240. }
  1241. }(),
  1242. reflect: function () {
  1243. // reflect incident vector off plane orthogonal to normal
  1244. // normal is assumed to have unit length
  1245. var v1 = new THREE.Vector3();
  1246. return function ( normal ) {
  1247. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1248. }
  1249. }()
  1250. } );
  1251. /**
  1252. * @author supereggbert / http://www.paulbrunt.co.uk/
  1253. * @author philogb / http://blog.thejit.org/
  1254. * @author mikael emtinger / http://gomo.se/
  1255. * @author egraether / http://egraether.com/
  1256. * @author WestLangley / http://github.com/WestLangley
  1257. */
  1258. THREE.Vector4 = function ( x, y, z, w ) {
  1259. this.x = x || 0;
  1260. this.y = y || 0;
  1261. this.z = z || 0;
  1262. this.w = ( w !== undefined ) ? w : 1;
  1263. };
  1264. THREE.Vector4.prototype = {
  1265. constructor: THREE.Vector4,
  1266. set: function ( x, y, z, w ) {
  1267. this.x = x;
  1268. this.y = y;
  1269. this.z = z;
  1270. this.w = w;
  1271. return this;
  1272. },
  1273. setX: function ( x ) {
  1274. this.x = x;
  1275. return this;
  1276. },
  1277. setY: function ( y ) {
  1278. this.y = y;
  1279. return this;
  1280. },
  1281. setZ: function ( z ) {
  1282. this.z = z;
  1283. return this;
  1284. },
  1285. setW: function ( w ) {
  1286. this.w = w;
  1287. return this;
  1288. },
  1289. setComponent: function ( index, value ) {
  1290. switch ( index ) {
  1291. case 0: this.x = value; break;
  1292. case 1: this.y = value; break;
  1293. case 2: this.z = value; break;
  1294. case 3: this.w = value; break;
  1295. default: throw new Error( "index is out of range: " + index );
  1296. }
  1297. },
  1298. getComponent: function ( index ) {
  1299. switch ( index ) {
  1300. case 0: return this.x;
  1301. case 1: return this.y;
  1302. case 2: return this.z;
  1303. case 3: return this.w;
  1304. default: throw new Error( "index is out of range: " + index );
  1305. }
  1306. },
  1307. copy: function ( v ) {
  1308. this.x = v.x;
  1309. this.y = v.y;
  1310. this.z = v.z;
  1311. this.w = ( v.w !== undefined ) ? v.w : 1;
  1312. return this;
  1313. },
  1314. add: function ( v, w ) {
  1315. if ( w !== undefined ) {
  1316. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1317. return this.addVectors( v, w );
  1318. }
  1319. this.x += v.x;
  1320. this.y += v.y;
  1321. this.z += v.z;
  1322. this.w += v.w;
  1323. return this;
  1324. },
  1325. addScalar: function ( s ) {
  1326. this.x += s;
  1327. this.y += s;
  1328. this.z += s;
  1329. this.w += s;
  1330. return this;
  1331. },
  1332. addVectors: function ( a, b ) {
  1333. this.x = a.x + b.x;
  1334. this.y = a.y + b.y;
  1335. this.z = a.z + b.z;
  1336. this.w = a.w + b.w;
  1337. return this;
  1338. },
  1339. sub: function ( v, w ) {
  1340. if ( w !== undefined ) {
  1341. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1342. return this.subVectors( v, w );
  1343. }
  1344. this.x -= v.x;
  1345. this.y -= v.y;
  1346. this.z -= v.z;
  1347. this.w -= v.w;
  1348. return this;
  1349. },
  1350. subVectors: function ( a, b ) {
  1351. this.x = a.x - b.x;
  1352. this.y = a.y - b.y;
  1353. this.z = a.z - b.z;
  1354. this.w = a.w - b.w;
  1355. return this;
  1356. },
  1357. multiplyScalar: function ( scalar ) {
  1358. this.x *= scalar;
  1359. this.y *= scalar;
  1360. this.z *= scalar;
  1361. this.w *= scalar;
  1362. return this;
  1363. },
  1364. applyMatrix4: function ( m ) {
  1365. var x = this.x;
  1366. var y = this.y;
  1367. var z = this.z;
  1368. var w = this.w;
  1369. var e = m.elements;
  1370. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1371. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1372. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1373. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1374. return this;
  1375. },
  1376. divideScalar: function ( scalar ) {
  1377. if ( scalar !== 0 ) {
  1378. var invScalar = 1 / scalar;
  1379. this.x *= invScalar;
  1380. this.y *= invScalar;
  1381. this.z *= invScalar;
  1382. this.w *= invScalar;
  1383. } else {
  1384. this.x = 0;
  1385. this.y = 0;
  1386. this.z = 0;
  1387. this.w = 1;
  1388. }
  1389. return this;
  1390. },
  1391. setAxisAngleFromQuaternion: function ( q ) {
  1392. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1393. // q is assumed to be normalized
  1394. this.w = 2 * Math.acos( q.w );
  1395. var s = Math.sqrt( 1 - q.w * q.w );
  1396. if ( s < 0.0001 ) {
  1397. this.x = 1;
  1398. this.y = 0;
  1399. this.z = 0;
  1400. } else {
  1401. this.x = q.x / s;
  1402. this.y = q.y / s;
  1403. this.z = q.z / s;
  1404. }
  1405. return this;
  1406. },
  1407. setAxisAngleFromRotationMatrix: function ( m ) {
  1408. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1409. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1410. var angle, x, y, z, // variables for result
  1411. epsilon = 0.01, // margin to allow for rounding errors
  1412. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1413. te = m.elements,
  1414. m11 = te[0], m12 = te[4], m13 = te[8],
  1415. m21 = te[1], m22 = te[5], m23 = te[9],
  1416. m31 = te[2], m32 = te[6], m33 = te[10];
  1417. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1418. && ( Math.abs( m13 - m31 ) < epsilon )
  1419. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1420. // singularity found
  1421. // first check for identity matrix which must have +1 for all terms
  1422. // in leading diagonal and zero in other terms
  1423. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1424. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1425. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1426. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1427. // this singularity is identity matrix so angle = 0
  1428. this.set( 1, 0, 0, 0 );
  1429. return this; // zero angle, arbitrary axis
  1430. }
  1431. // otherwise this singularity is angle = 180
  1432. angle = Math.PI;
  1433. var xx = ( m11 + 1 ) / 2;
  1434. var yy = ( m22 + 1 ) / 2;
  1435. var zz = ( m33 + 1 ) / 2;
  1436. var xy = ( m12 + m21 ) / 4;
  1437. var xz = ( m13 + m31 ) / 4;
  1438. var yz = ( m23 + m32 ) / 4;
  1439. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1440. if ( xx < epsilon ) {
  1441. x = 0;
  1442. y = 0.707106781;
  1443. z = 0.707106781;
  1444. } else {
  1445. x = Math.sqrt( xx );
  1446. y = xy / x;
  1447. z = xz / x;
  1448. }
  1449. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1450. if ( yy < epsilon ) {
  1451. x = 0.707106781;
  1452. y = 0;
  1453. z = 0.707106781;
  1454. } else {
  1455. y = Math.sqrt( yy );
  1456. x = xy / y;
  1457. z = yz / y;
  1458. }
  1459. } else { // m33 is the largest diagonal term so base result on this
  1460. if ( zz < epsilon ) {
  1461. x = 0.707106781;
  1462. y = 0.707106781;
  1463. z = 0;
  1464. } else {
  1465. z = Math.sqrt( zz );
  1466. x = xz / z;
  1467. y = yz / z;
  1468. }
  1469. }
  1470. this.set( x, y, z, angle );
  1471. return this; // return 180 deg rotation
  1472. }
  1473. // as we have reached here there are no singularities so we can handle normally
  1474. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1475. + ( m13 - m31 ) * ( m13 - m31 )
  1476. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1477. if ( Math.abs( s ) < 0.001 ) s = 1;
  1478. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1479. // caught by singularity test above, but I've left it in just in case
  1480. this.x = ( m32 - m23 ) / s;
  1481. this.y = ( m13 - m31 ) / s;
  1482. this.z = ( m21 - m12 ) / s;
  1483. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1484. return this;
  1485. },
  1486. min: function ( v ) {
  1487. if ( this.x > v.x ) {
  1488. this.x = v.x;
  1489. }
  1490. if ( this.y > v.y ) {
  1491. this.y = v.y;
  1492. }
  1493. if ( this.z > v.z ) {
  1494. this.z = v.z;
  1495. }
  1496. if ( this.w > v.w ) {
  1497. this.w = v.w;
  1498. }
  1499. return this;
  1500. },
  1501. max: function ( v ) {
  1502. if ( this.x < v.x ) {
  1503. this.x = v.x;
  1504. }
  1505. if ( this.y < v.y ) {
  1506. this.y = v.y;
  1507. }
  1508. if ( this.z < v.z ) {
  1509. this.z = v.z;
  1510. }
  1511. if ( this.w < v.w ) {
  1512. this.w = v.w;
  1513. }
  1514. return this;
  1515. },
  1516. clamp: function ( min, max ) {
  1517. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1518. if ( this.x < min.x ) {
  1519. this.x = min.x;
  1520. } else if ( this.x > max.x ) {
  1521. this.x = max.x;
  1522. }
  1523. if ( this.y < min.y ) {
  1524. this.y = min.y;
  1525. } else if ( this.y > max.y ) {
  1526. this.y = max.y;
  1527. }
  1528. if ( this.z < min.z ) {
  1529. this.z = min.z;
  1530. } else if ( this.z > max.z ) {
  1531. this.z = max.z;
  1532. }
  1533. if ( this.w < min.w ) {
  1534. this.w = min.w;
  1535. } else if ( this.w > max.w ) {
  1536. this.w = max.w;
  1537. }
  1538. return this;
  1539. },
  1540. negate: function() {
  1541. return this.multiplyScalar( -1 );
  1542. },
  1543. dot: function ( v ) {
  1544. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1545. },
  1546. lengthSq: function () {
  1547. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1548. },
  1549. length: function () {
  1550. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1551. },
  1552. lengthManhattan: function () {
  1553. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1554. },
  1555. normalize: function () {
  1556. return this.divideScalar( this.length() );
  1557. },
  1558. setLength: function ( l ) {
  1559. var oldLength = this.length();
  1560. if ( oldLength !== 0 && l !== oldLength ) {
  1561. this.multiplyScalar( l / oldLength );
  1562. }
  1563. return this;
  1564. },
  1565. lerp: function ( v, alpha ) {
  1566. this.x += ( v.x - this.x ) * alpha;
  1567. this.y += ( v.y - this.y ) * alpha;
  1568. this.z += ( v.z - this.z ) * alpha;
  1569. this.w += ( v.w - this.w ) * alpha;
  1570. return this;
  1571. },
  1572. equals: function ( v ) {
  1573. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1574. },
  1575. fromArray: function ( array ) {
  1576. this.x = array[ 0 ];
  1577. this.y = array[ 1 ];
  1578. this.z = array[ 2 ];
  1579. this.w = array[ 3 ];
  1580. return this;
  1581. },
  1582. toArray: function () {
  1583. return [ this.x, this.y, this.z, this.w ];
  1584. },
  1585. clone: function () {
  1586. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1587. }
  1588. };
  1589. /**
  1590. * @author mrdoob / http://mrdoob.com/
  1591. * @author WestLangley / http://github.com/WestLangley
  1592. * @author bhouston / http://exocortex.com
  1593. */
  1594. THREE.Euler = function ( x, y, z, order ) {
  1595. this._x = x || 0;
  1596. this._y = y || 0;
  1597. this._z = z || 0;
  1598. this._order = order || THREE.Euler.DefaultOrder;
  1599. };
  1600. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1601. THREE.Euler.DefaultOrder = 'XYZ';
  1602. THREE.Euler.prototype = {
  1603. constructor: THREE.Euler,
  1604. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1605. _quaternion: undefined,
  1606. _updateQuaternion: function () {
  1607. if ( this._quaternion !== undefined ) {
  1608. this._quaternion.setFromEuler( this, false );
  1609. }
  1610. },
  1611. get x () {
  1612. return this._x;
  1613. },
  1614. set x ( value ) {
  1615. this._x = value;
  1616. this._updateQuaternion();
  1617. },
  1618. get y () {
  1619. return this._y;
  1620. },
  1621. set y ( value ) {
  1622. this._y = value;
  1623. this._updateQuaternion();
  1624. },
  1625. get z () {
  1626. return this._z;
  1627. },
  1628. set z ( value ) {
  1629. this._z = value;
  1630. this._updateQuaternion();
  1631. },
  1632. get order () {
  1633. return this._order;
  1634. },
  1635. set order ( value ) {
  1636. this._order = value;
  1637. this._updateQuaternion();
  1638. },
  1639. set: function ( x, y, z, order ) {
  1640. this._x = x;
  1641. this._y = y;
  1642. this._z = z;
  1643. this._order = order || this._order;
  1644. this._updateQuaternion();
  1645. return this;
  1646. },
  1647. copy: function ( euler ) {
  1648. this._x = euler._x;
  1649. this._y = euler._y;
  1650. this._z = euler._z;
  1651. this._order = euler._order;
  1652. this._updateQuaternion();
  1653. return this;
  1654. },
  1655. setFromRotationMatrix: function ( m, order ) {
  1656. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1657. // clamp, to handle numerical problems
  1658. function clamp( x ) {
  1659. return Math.min( Math.max( x, -1 ), 1 );
  1660. }
  1661. var te = m.elements;
  1662. var m11 = te[0], m12 = te[4], m13 = te[8];
  1663. var m21 = te[1], m22 = te[5], m23 = te[9];
  1664. var m31 = te[2], m32 = te[6], m33 = te[10];
  1665. order = order || this._order;
  1666. if ( order === 'XYZ' ) {
  1667. this._y = Math.asin( clamp( m13 ) );
  1668. if ( Math.abs( m13 ) < 0.99999 ) {
  1669. this._x = Math.atan2( - m23, m33 );
  1670. this._z = Math.atan2( - m12, m11 );
  1671. } else {
  1672. this._x = Math.atan2( m32, m22 );
  1673. this._z = 0;
  1674. }
  1675. } else if ( order === 'YXZ' ) {
  1676. this._x = Math.asin( - clamp( m23 ) );
  1677. if ( Math.abs( m23 ) < 0.99999 ) {
  1678. this._y = Math.atan2( m13, m33 );
  1679. this._z = Math.atan2( m21, m22 );
  1680. } else {
  1681. this._y = Math.atan2( - m31, m11 );
  1682. this._z = 0;
  1683. }
  1684. } else if ( order === 'ZXY' ) {
  1685. this._x = Math.asin( clamp( m32 ) );
  1686. if ( Math.abs( m32 ) < 0.99999 ) {
  1687. this._y = Math.atan2( - m31, m33 );
  1688. this._z = Math.atan2( - m12, m22 );
  1689. } else {
  1690. this._y = 0;
  1691. this._z = Math.atan2( m21, m11 );
  1692. }
  1693. } else if ( order === 'ZYX' ) {
  1694. this._y = Math.asin( - clamp( m31 ) );
  1695. if ( Math.abs( m31 ) < 0.99999 ) {
  1696. this._x = Math.atan2( m32, m33 );
  1697. this._z = Math.atan2( m21, m11 );
  1698. } else {
  1699. this._x = 0;
  1700. this._z = Math.atan2( - m12, m22 );
  1701. }
  1702. } else if ( order === 'YZX' ) {
  1703. this._z = Math.asin( clamp( m21 ) );
  1704. if ( Math.abs( m21 ) < 0.99999 ) {
  1705. this._x = Math.atan2( - m23, m22 );
  1706. this._y = Math.atan2( - m31, m11 );
  1707. } else {
  1708. this._x = 0;
  1709. this._y = Math.atan2( m13, m33 );
  1710. }
  1711. } else if ( order === 'XZY' ) {
  1712. this._z = Math.asin( - clamp( m12 ) );
  1713. if ( Math.abs( m12 ) < 0.99999 ) {
  1714. this._x = Math.atan2( m32, m22 );
  1715. this._y = Math.atan2( m13, m11 );
  1716. } else {
  1717. this._x = Math.atan2( - m23, m33 );
  1718. this._y = 0;
  1719. }
  1720. } else {
  1721. console.warn( 'WARNING: Euler.setFromRotationMatrix() given unsupported order: ' + order )
  1722. }
  1723. this._order = order;
  1724. this._updateQuaternion();
  1725. return this;
  1726. },
  1727. setFromQuaternion: function ( q, order, update ) {
  1728. // q is assumed to be normalized
  1729. // clamp, to handle numerical problems
  1730. function clamp( x ) {
  1731. return Math.min( Math.max( x, -1 ), 1 );
  1732. }
  1733. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1734. var sqx = q.x * q.x;
  1735. var sqy = q.y * q.y;
  1736. var sqz = q.z * q.z;
  1737. var sqw = q.w * q.w;
  1738. order = order || this._order;
  1739. if ( order === 'XYZ' ) {
  1740. this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1741. this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1742. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1743. } else if ( order === 'YXZ' ) {
  1744. this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1745. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1746. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1747. } else if ( order === 'ZXY' ) {
  1748. this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1749. this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1750. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1751. } else if ( order === 'ZYX' ) {
  1752. this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1753. this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1754. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1755. } else if ( order === 'YZX' ) {
  1756. this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1757. this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1758. this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1759. } else if ( order === 'XZY' ) {
  1760. this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1761. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1762. this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1763. } else {
  1764. console.warn( 'WARNING: Euler.setFromQuaternion() given unsupported order: ' + order )
  1765. }
  1766. this._order = order;
  1767. if ( update !== false ) this._updateQuaternion();
  1768. return this;
  1769. },
  1770. reorder: function () {
  1771. // WARNING: this discards revolution information -bhouston
  1772. var q = new THREE.Quaternion();
  1773. return function ( newOrder ) {
  1774. q.setFromEuler( this );
  1775. this.setFromQuaternion( q, newOrder );
  1776. };
  1777. }(),
  1778. fromArray: function ( array ) {
  1779. this._x = array[ 0 ];
  1780. this._y = array[ 1 ];
  1781. this._z = array[ 2 ];
  1782. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1783. this._updateQuaternion();
  1784. return this;
  1785. },
  1786. toArray: function () {
  1787. return [ this._x, this._y, this._z, this._order ];
  1788. },
  1789. equals: function ( euler ) {
  1790. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1791. },
  1792. clone: function () {
  1793. return new THREE.Euler( this._x, this._y, this._z, this._order );
  1794. }
  1795. };
  1796. /**
  1797. * @author bhouston / http://exocortex.com
  1798. */
  1799. THREE.Line3 = function ( start, end ) {
  1800. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1801. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1802. };
  1803. THREE.Line3.prototype = {
  1804. constructor: THREE.Line3,
  1805. set: function ( start, end ) {
  1806. this.start.copy( start );
  1807. this.end.copy( end );
  1808. return this;
  1809. },
  1810. copy: function ( line ) {
  1811. this.start.copy( line.start );
  1812. this.end.copy( line.end );
  1813. return this;
  1814. },
  1815. center: function ( optionalTarget ) {
  1816. var result = optionalTarget || new THREE.Vector3();
  1817. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1818. },
  1819. delta: function ( optionalTarget ) {
  1820. var result = optionalTarget || new THREE.Vector3();
  1821. return result.subVectors( this.end, this.start );
  1822. },
  1823. distanceSq: function () {
  1824. return this.start.distanceToSquared( this.end );
  1825. },
  1826. distance: function () {
  1827. return this.start.distanceTo( this.end );
  1828. },
  1829. at: function ( t, optionalTarget ) {
  1830. var result = optionalTarget || new THREE.Vector3();
  1831. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1832. },
  1833. closestPointToPointParameter: function() {
  1834. var startP = new THREE.Vector3();
  1835. var startEnd = new THREE.Vector3();
  1836. return function ( point, clampToLine ) {
  1837. startP.subVectors( point, this.start );
  1838. startEnd.subVectors( this.end, this.start );
  1839. var startEnd2 = startEnd.dot( startEnd );
  1840. var startEnd_startP = startEnd.dot( startP );
  1841. var t = startEnd_startP / startEnd2;
  1842. if ( clampToLine ) {
  1843. t = THREE.Math.clamp( t, 0, 1 );
  1844. }
  1845. return t;
  1846. };
  1847. }(),
  1848. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1849. var t = this.closestPointToPointParameter( point, clampToLine );
  1850. var result = optionalTarget || new THREE.Vector3();
  1851. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1852. },
  1853. applyMatrix4: function ( matrix ) {
  1854. this.start.applyMatrix4( matrix );
  1855. this.end.applyMatrix4( matrix );
  1856. return this;
  1857. },
  1858. equals: function ( line ) {
  1859. return line.start.equals( this.start ) && line.end.equals( this.end );
  1860. },
  1861. clone: function () {
  1862. return new THREE.Line3().copy( this );
  1863. }
  1864. };
  1865. /**
  1866. * @author bhouston / http://exocortex.com
  1867. */
  1868. THREE.Box2 = function ( min, max ) {
  1869. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1870. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1871. };
  1872. THREE.Box2.prototype = {
  1873. constructor: THREE.Box2,
  1874. set: function ( min, max ) {
  1875. this.min.copy( min );
  1876. this.max.copy( max );
  1877. return this;
  1878. },
  1879. setFromPoints: function ( points ) {
  1880. if ( points.length > 0 ) {
  1881. var point = points[ 0 ];
  1882. this.min.copy( point );
  1883. this.max.copy( point );
  1884. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1885. point = points[ i ];
  1886. if ( point.x < this.min.x ) {
  1887. this.min.x = point.x;
  1888. } else if ( point.x > this.max.x ) {
  1889. this.max.x = point.x;
  1890. }
  1891. if ( point.y < this.min.y ) {
  1892. this.min.y = point.y;
  1893. } else if ( point.y > this.max.y ) {
  1894. this.max.y = point.y;
  1895. }
  1896. }
  1897. } else {
  1898. this.makeEmpty();
  1899. }
  1900. return this;
  1901. },
  1902. setFromCenterAndSize: function () {
  1903. var v1 = new THREE.Vector2();
  1904. return function ( center, size ) {
  1905. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1906. this.min.copy( center ).sub( halfSize );
  1907. this.max.copy( center ).add( halfSize );
  1908. return this;
  1909. };
  1910. }(),
  1911. copy: function ( box ) {
  1912. this.min.copy( box.min );
  1913. this.max.copy( box.max );
  1914. return this;
  1915. },
  1916. makeEmpty: function () {
  1917. this.min.x = this.min.y = Infinity;
  1918. this.max.x = this.max.y = -Infinity;
  1919. return this;
  1920. },
  1921. empty: function () {
  1922. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1923. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1924. },
  1925. center: function ( optionalTarget ) {
  1926. var result = optionalTarget || new THREE.Vector2();
  1927. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1928. },
  1929. size: function ( optionalTarget ) {
  1930. var result = optionalTarget || new THREE.Vector2();
  1931. return result.subVectors( this.max, this.min );
  1932. },
  1933. expandByPoint: function ( point ) {
  1934. this.min.min( point );
  1935. this.max.max( point );
  1936. return this;
  1937. },
  1938. expandByVector: function ( vector ) {
  1939. this.min.sub( vector );
  1940. this.max.add( vector );
  1941. return this;
  1942. },
  1943. expandByScalar: function ( scalar ) {
  1944. this.min.addScalar( -scalar );
  1945. this.max.addScalar( scalar );
  1946. return this;
  1947. },
  1948. containsPoint: function ( point ) {
  1949. if ( point.x < this.min.x || point.x > this.max.x ||
  1950. point.y < this.min.y || point.y > this.max.y ) {
  1951. return false;
  1952. }
  1953. return true;
  1954. },
  1955. containsBox: function ( box ) {
  1956. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1957. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1958. return true;
  1959. }
  1960. return false;
  1961. },
  1962. getParameter: function ( point, optionalTarget ) {
  1963. // This can potentially have a divide by zero if the box
  1964. // has a size dimension of 0.
  1965. var result = optionalTarget || new THREE.Vector2();
  1966. return result.set(
  1967. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1968. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1969. );
  1970. },
  1971. isIntersectionBox: function ( box ) {
  1972. // using 6 splitting planes to rule out intersections.
  1973. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1974. box.max.y < this.min.y || box.min.y > this.max.y ) {
  1975. return false;
  1976. }
  1977. return true;
  1978. },
  1979. clampPoint: function ( point, optionalTarget ) {
  1980. var result = optionalTarget || new THREE.Vector2();
  1981. return result.copy( point ).clamp( this.min, this.max );
  1982. },
  1983. distanceToPoint: function () {
  1984. var v1 = new THREE.Vector2();
  1985. return function ( point ) {
  1986. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1987. return clampedPoint.sub( point ).length();
  1988. };
  1989. }(),
  1990. intersect: function ( box ) {
  1991. this.min.max( box.min );
  1992. this.max.min( box.max );
  1993. return this;
  1994. },
  1995. union: function ( box ) {
  1996. this.min.min( box.min );
  1997. this.max.max( box.max );
  1998. return this;
  1999. },
  2000. translate: function ( offset ) {
  2001. this.min.add( offset );
  2002. this.max.add( offset );
  2003. return this;
  2004. },
  2005. equals: function ( box ) {
  2006. return box.min.equals( this.min ) && box.max.equals( this.max );
  2007. },
  2008. clone: function () {
  2009. return new THREE.Box2().copy( this );
  2010. }
  2011. };
  2012. /**
  2013. * @author bhouston / http://exocortex.com
  2014. * @author WestLangley / http://github.com/WestLangley
  2015. */
  2016. THREE.Box3 = function ( min, max ) {
  2017. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2018. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  2019. };
  2020. THREE.Box3.prototype = {
  2021. constructor: THREE.Box3,
  2022. set: function ( min, max ) {
  2023. this.min.copy( min );
  2024. this.max.copy( max );
  2025. return this;
  2026. },
  2027. addPoint: function ( point ) {
  2028. if ( point.x < this.min.x ) {
  2029. this.min.x = point.x;
  2030. } else if ( point.x > this.max.x ) {
  2031. this.max.x = point.x;
  2032. }
  2033. if ( point.y < this.min.y ) {
  2034. this.min.y = point.y;
  2035. } else if ( point.y > this.max.y ) {
  2036. this.max.y = point.y;
  2037. }
  2038. if ( point.z < this.min.z ) {
  2039. this.min.z = point.z;
  2040. } else if ( point.z > this.max.z ) {
  2041. this.max.z = point.z;
  2042. }
  2043. },
  2044. setFromPoints: function ( points ) {
  2045. if ( points.length > 0 ) {
  2046. var point = points[ 0 ];
  2047. this.min.copy( point );
  2048. this.max.copy( point );
  2049. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2050. this.addPoint( points[ i ] )
  2051. }
  2052. } else {
  2053. this.makeEmpty();
  2054. }
  2055. return this;
  2056. },
  2057. setFromCenterAndSize: function() {
  2058. var v1 = new THREE.Vector3();
  2059. return function ( center, size ) {
  2060. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2061. this.min.copy( center ).sub( halfSize );
  2062. this.max.copy( center ).add( halfSize );
  2063. return this;
  2064. };
  2065. }(),
  2066. setFromObject: function() {
  2067. // Computes the world-axis-aligned bounding box of an object (including its children),
  2068. // accounting for both the object's, and childrens', world transforms
  2069. var v1 = new THREE.Vector3();
  2070. return function( object ) {
  2071. var scope = this;
  2072. object.updateMatrixWorld( true );
  2073. this.makeEmpty();
  2074. object.traverse( function ( node ) {
  2075. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2076. var vertices = node.geometry.vertices;
  2077. for ( var i = 0, il = vertices.length; i < il; i++ ) {
  2078. v1.copy( vertices[ i ] );
  2079. v1.applyMatrix4( node.matrixWorld );
  2080. scope.expandByPoint( v1 );
  2081. }
  2082. }
  2083. } );
  2084. return this;
  2085. };
  2086. }(),
  2087. copy: function ( box ) {
  2088. this.min.copy( box.min );
  2089. this.max.copy( box.max );
  2090. return this;
  2091. },
  2092. makeEmpty: function () {
  2093. this.min.x = this.min.y = this.min.z = Infinity;
  2094. this.max.x = this.max.y = this.max.z = -Infinity;
  2095. return this;
  2096. },
  2097. empty: function () {
  2098. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2099. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2100. },
  2101. center: function ( optionalTarget ) {
  2102. var result = optionalTarget || new THREE.Vector3();
  2103. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2104. },
  2105. size: function ( optionalTarget ) {
  2106. var result = optionalTarget || new THREE.Vector3();
  2107. return result.subVectors( this.max, this.min );
  2108. },
  2109. expandByPoint: function ( point ) {
  2110. this.min.min( point );
  2111. this.max.max( point );
  2112. return this;
  2113. },
  2114. expandByVector: function ( vector ) {
  2115. this.min.sub( vector );
  2116. this.max.add( vector );
  2117. return this;
  2118. },
  2119. expandByScalar: function ( scalar ) {
  2120. this.min.addScalar( -scalar );
  2121. this.max.addScalar( scalar );
  2122. return this;
  2123. },
  2124. containsPoint: function ( point ) {
  2125. if ( point.x < this.min.x || point.x > this.max.x ||
  2126. point.y < this.min.y || point.y > this.max.y ||
  2127. point.z < this.min.z || point.z > this.max.z ) {
  2128. return false;
  2129. }
  2130. return true;
  2131. },
  2132. containsBox: function ( box ) {
  2133. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2134. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2135. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2136. return true;
  2137. }
  2138. return false;
  2139. },
  2140. getParameter: function ( point, optionalTarget ) {
  2141. // This can potentially have a divide by zero if the box
  2142. // has a size dimension of 0.
  2143. var result = optionalTarget || new THREE.Vector3();
  2144. return result.set(
  2145. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2146. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2147. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2148. );
  2149. },
  2150. isIntersectionBox: function ( box ) {
  2151. // using 6 splitting planes to rule out intersections.
  2152. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2153. box.max.y < this.min.y || box.min.y > this.max.y ||
  2154. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2155. return false;
  2156. }
  2157. return true;
  2158. },
  2159. clampPoint: function ( point, optionalTarget ) {
  2160. var result = optionalTarget || new THREE.Vector3();
  2161. return result.copy( point ).clamp( this.min, this.max );
  2162. },
  2163. distanceToPoint: function() {
  2164. var v1 = new THREE.Vector3();
  2165. return function ( point ) {
  2166. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2167. return clampedPoint.sub( point ).length();
  2168. };
  2169. }(),
  2170. getBoundingSphere: function() {
  2171. var v1 = new THREE.Vector3();
  2172. return function ( optionalTarget ) {
  2173. var result = optionalTarget || new THREE.Sphere();
  2174. result.center = this.center();
  2175. result.radius = this.size( v1 ).length() * 0.5;
  2176. return result;
  2177. };
  2178. }(),
  2179. intersect: function ( box ) {
  2180. this.min.max( box.min );
  2181. this.max.min( box.max );
  2182. return this;
  2183. },
  2184. union: function ( box ) {
  2185. this.min.min( box.min );
  2186. this.max.max( box.max );
  2187. return this;
  2188. },
  2189. applyMatrix4: function() {
  2190. var points = [
  2191. new THREE.Vector3(),
  2192. new THREE.Vector3(),
  2193. new THREE.Vector3(),
  2194. new THREE.Vector3(),
  2195. new THREE.Vector3(),
  2196. new THREE.Vector3(),
  2197. new THREE.Vector3(),
  2198. new THREE.Vector3()
  2199. ];
  2200. return function ( matrix ) {
  2201. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2202. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2203. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2204. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2205. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2206. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2207. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2208. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2209. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2210. this.makeEmpty();
  2211. this.setFromPoints( points );
  2212. return this;
  2213. };
  2214. }(),
  2215. translate: function ( offset ) {
  2216. this.min.add( offset );
  2217. this.max.add( offset );
  2218. return this;
  2219. },
  2220. equals: function ( box ) {
  2221. return box.min.equals( this.min ) && box.max.equals( this.max );
  2222. },
  2223. clone: function () {
  2224. return new THREE.Box3().copy( this );
  2225. }
  2226. };
  2227. /**
  2228. * @author alteredq / http://alteredqualia.com/
  2229. * @author WestLangley / http://github.com/WestLangley
  2230. * @author bhouston / http://exocortex.com
  2231. */
  2232. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2233. this.elements = new Float32Array(9);
  2234. this.set(
  2235. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2236. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2237. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2238. );
  2239. };
  2240. THREE.Matrix3.prototype = {
  2241. constructor: THREE.Matrix3,
  2242. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2243. var te = this.elements;
  2244. te[0] = n11; te[3] = n12; te[6] = n13;
  2245. te[1] = n21; te[4] = n22; te[7] = n23;
  2246. te[2] = n31; te[5] = n32; te[8] = n33;
  2247. return this;
  2248. },
  2249. identity: function () {
  2250. this.set(
  2251. 1, 0, 0,
  2252. 0, 1, 0,
  2253. 0, 0, 1
  2254. );
  2255. return this;
  2256. },
  2257. copy: function ( m ) {
  2258. var me = m.elements;
  2259. this.set(
  2260. me[0], me[3], me[6],
  2261. me[1], me[4], me[7],
  2262. me[2], me[5], me[8]
  2263. );
  2264. return this;
  2265. },
  2266. multiplyVector3: function ( vector ) {
  2267. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2268. return vector.applyMatrix3( this );
  2269. },
  2270. multiplyVector3Array: function() {
  2271. var v1 = new THREE.Vector3();
  2272. return function ( a ) {
  2273. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2274. v1.x = a[ i ];
  2275. v1.y = a[ i + 1 ];
  2276. v1.z = a[ i + 2 ];
  2277. v1.applyMatrix3(this);
  2278. a[ i ] = v1.x;
  2279. a[ i + 1 ] = v1.y;
  2280. a[ i + 2 ] = v1.z;
  2281. }
  2282. return a;
  2283. };
  2284. }(),
  2285. multiplyScalar: function ( s ) {
  2286. var te = this.elements;
  2287. te[0] *= s; te[3] *= s; te[6] *= s;
  2288. te[1] *= s; te[4] *= s; te[7] *= s;
  2289. te[2] *= s; te[5] *= s; te[8] *= s;
  2290. return this;
  2291. },
  2292. determinant: function () {
  2293. var te = this.elements;
  2294. var a = te[0], b = te[1], c = te[2],
  2295. d = te[3], e = te[4], f = te[5],
  2296. g = te[6], h = te[7], i = te[8];
  2297. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2298. },
  2299. getInverse: function ( matrix, throwOnInvertible ) {
  2300. // input: THREE.Matrix4
  2301. // ( based on http://code.google.com/p/webgl-mjs/ )
  2302. var me = matrix.elements;
  2303. var te = this.elements;
  2304. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2305. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2306. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2307. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2308. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2309. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2310. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2311. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2312. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2313. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2314. // no inverse
  2315. if ( det === 0 ) {
  2316. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2317. if ( throwOnInvertible || false ) {
  2318. throw new Error( msg );
  2319. } else {
  2320. console.warn( msg );
  2321. }
  2322. this.identity();
  2323. return this;
  2324. }
  2325. this.multiplyScalar( 1.0 / det );
  2326. return this;
  2327. },
  2328. transpose: function () {
  2329. var tmp, m = this.elements;
  2330. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2331. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2332. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2333. return this;
  2334. },
  2335. getNormalMatrix: function ( m ) {
  2336. // input: THREE.Matrix4
  2337. this.getInverse( m ).transpose();
  2338. return this;
  2339. },
  2340. transposeIntoArray: function ( r ) {
  2341. var m = this.elements;
  2342. r[ 0 ] = m[ 0 ];
  2343. r[ 1 ] = m[ 3 ];
  2344. r[ 2 ] = m[ 6 ];
  2345. r[ 3 ] = m[ 1 ];
  2346. r[ 4 ] = m[ 4 ];
  2347. r[ 5 ] = m[ 7 ];
  2348. r[ 6 ] = m[ 2 ];
  2349. r[ 7 ] = m[ 5 ];
  2350. r[ 8 ] = m[ 8 ];
  2351. return this;
  2352. },
  2353. fromArray: function ( array ) {
  2354. this.elements.set( array );
  2355. return this;
  2356. },
  2357. toArray: function () {
  2358. var te = this.elements;
  2359. return [
  2360. te[ 0 ], te[ 1 ], te[ 2 ],
  2361. te[ 3 ], te[ 4 ], te[ 5 ],
  2362. te[ 6 ], te[ 7 ], te[ 8 ]
  2363. ];
  2364. },
  2365. clone: function () {
  2366. var te = this.elements;
  2367. return new THREE.Matrix3(
  2368. te[0], te[3], te[6],
  2369. te[1], te[4], te[7],
  2370. te[2], te[5], te[8]
  2371. );
  2372. }
  2373. };
  2374. /**
  2375. * @author mrdoob / http://mrdoob.com/
  2376. * @author supereggbert / http://www.paulbrunt.co.uk/
  2377. * @author philogb / http://blog.thejit.org/
  2378. * @author jordi_ros / http://plattsoft.com
  2379. * @author D1plo1d / http://github.com/D1plo1d
  2380. * @author alteredq / http://alteredqualia.com/
  2381. * @author mikael emtinger / http://gomo.se/
  2382. * @author timknip / http://www.floorplanner.com/
  2383. * @author bhouston / http://exocortex.com
  2384. * @author WestLangley / http://github.com/WestLangley
  2385. */
  2386. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2387. this.elements = new Float32Array( 16 );
  2388. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2389. // we should not support semi specification of Matrix4, it is just weird.
  2390. var te = this.elements;
  2391. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2392. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2393. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2394. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2395. };
  2396. THREE.Matrix4.prototype = {
  2397. constructor: THREE.Matrix4,
  2398. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2399. var te = this.elements;
  2400. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2401. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2402. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2403. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2404. return this;
  2405. },
  2406. identity: function () {
  2407. this.set(
  2408. 1, 0, 0, 0,
  2409. 0, 1, 0, 0,
  2410. 0, 0, 1, 0,
  2411. 0, 0, 0, 1
  2412. );
  2413. return this;
  2414. },
  2415. copy: function ( m ) {
  2416. this.elements.set( m.elements );
  2417. return this;
  2418. },
  2419. extractPosition: function ( m ) {
  2420. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2421. return this.copyPosition( m );
  2422. },
  2423. copyPosition: function ( m ) {
  2424. var te = this.elements;
  2425. var me = m.elements;
  2426. te[12] = me[12];
  2427. te[13] = me[13];
  2428. te[14] = me[14];
  2429. return this;
  2430. },
  2431. extractRotation: function () {
  2432. var v1 = new THREE.Vector3();
  2433. return function ( m ) {
  2434. var te = this.elements;
  2435. var me = m.elements;
  2436. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2437. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2438. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2439. te[0] = me[0] * scaleX;
  2440. te[1] = me[1] * scaleX;
  2441. te[2] = me[2] * scaleX;
  2442. te[4] = me[4] * scaleY;
  2443. te[5] = me[5] * scaleY;
  2444. te[6] = me[6] * scaleY;
  2445. te[8] = me[8] * scaleZ;
  2446. te[9] = me[9] * scaleZ;
  2447. te[10] = me[10] * scaleZ;
  2448. return this;
  2449. };
  2450. }(),
  2451. makeRotationFromEuler: function ( euler ) {
  2452. if ( euler instanceof THREE.Euler === false ) {
  2453. console.error( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  2454. }
  2455. var te = this.elements;
  2456. var x = euler.x, y = euler.y, z = euler.z;
  2457. var a = Math.cos( x ), b = Math.sin( x );
  2458. var c = Math.cos( y ), d = Math.sin( y );
  2459. var e = Math.cos( z ), f = Math.sin( z );
  2460. if ( euler.order === 'XYZ' ) {
  2461. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2462. te[0] = c * e;
  2463. te[4] = - c * f;
  2464. te[8] = d;
  2465. te[1] = af + be * d;
  2466. te[5] = ae - bf * d;
  2467. te[9] = - b * c;
  2468. te[2] = bf - ae * d;
  2469. te[6] = be + af * d;
  2470. te[10] = a * c;
  2471. } else if ( euler.order === 'YXZ' ) {
  2472. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2473. te[0] = ce + df * b;
  2474. te[4] = de * b - cf;
  2475. te[8] = a * d;
  2476. te[1] = a * f;
  2477. te[5] = a * e;
  2478. te[9] = - b;
  2479. te[2] = cf * b - de;
  2480. te[6] = df + ce * b;
  2481. te[10] = a * c;
  2482. } else if ( euler.order === 'ZXY' ) {
  2483. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2484. te[0] = ce - df * b;
  2485. te[4] = - a * f;
  2486. te[8] = de + cf * b;
  2487. te[1] = cf + de * b;
  2488. te[5] = a * e;
  2489. te[9] = df - ce * b;
  2490. te[2] = - a * d;
  2491. te[6] = b;
  2492. te[10] = a * c;
  2493. } else if ( euler.order === 'ZYX' ) {
  2494. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2495. te[0] = c * e;
  2496. te[4] = be * d - af;
  2497. te[8] = ae * d + bf;
  2498. te[1] = c * f;
  2499. te[5] = bf * d + ae;
  2500. te[9] = af * d - be;
  2501. te[2] = - d;
  2502. te[6] = b * c;
  2503. te[10] = a * c;
  2504. } else if ( euler.order === 'YZX' ) {
  2505. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2506. te[0] = c * e;
  2507. te[4] = bd - ac * f;
  2508. te[8] = bc * f + ad;
  2509. te[1] = f;
  2510. te[5] = a * e;
  2511. te[9] = - b * e;
  2512. te[2] = - d * e;
  2513. te[6] = ad * f + bc;
  2514. te[10] = ac - bd * f;
  2515. } else if ( euler.order === 'XZY' ) {
  2516. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2517. te[0] = c * e;
  2518. te[4] = - f;
  2519. te[8] = d * e;
  2520. te[1] = ac * f + bd;
  2521. te[5] = a * e;
  2522. te[9] = ad * f - bc;
  2523. te[2] = bc * f - ad;
  2524. te[6] = b * e;
  2525. te[10] = bd * f + ac;
  2526. }
  2527. // last column
  2528. te[3] = 0;
  2529. te[7] = 0;
  2530. te[11] = 0;
  2531. // bottom row
  2532. te[12] = 0;
  2533. te[13] = 0;
  2534. te[14] = 0;
  2535. te[15] = 1;
  2536. return this;
  2537. },
  2538. setRotationFromQuaternion: function ( q ) {
  2539. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2540. return this.makeRotationFromQuaternion( q );
  2541. },
  2542. makeRotationFromQuaternion: function ( q ) {
  2543. var te = this.elements;
  2544. var x = q.x, y = q.y, z = q.z, w = q.w;
  2545. var x2 = x + x, y2 = y + y, z2 = z + z;
  2546. var xx = x * x2, xy = x * y2, xz = x * z2;
  2547. var yy = y * y2, yz = y * z2, zz = z * z2;
  2548. var wx = w * x2, wy = w * y2, wz = w * z2;
  2549. te[0] = 1 - ( yy + zz );
  2550. te[4] = xy - wz;
  2551. te[8] = xz + wy;
  2552. te[1] = xy + wz;
  2553. te[5] = 1 - ( xx + zz );
  2554. te[9] = yz - wx;
  2555. te[2] = xz - wy;
  2556. te[6] = yz + wx;
  2557. te[10] = 1 - ( xx + yy );
  2558. // last column
  2559. te[3] = 0;
  2560. te[7] = 0;
  2561. te[11] = 0;
  2562. // bottom row
  2563. te[12] = 0;
  2564. te[13] = 0;
  2565. te[14] = 0;
  2566. te[15] = 1;
  2567. return this;
  2568. },
  2569. lookAt: function() {
  2570. var x = new THREE.Vector3();
  2571. var y = new THREE.Vector3();
  2572. var z = new THREE.Vector3();
  2573. return function ( eye, target, up ) {
  2574. var te = this.elements;
  2575. z.subVectors( eye, target ).normalize();
  2576. if ( z.length() === 0 ) {
  2577. z.z = 1;
  2578. }
  2579. x.crossVectors( up, z ).normalize();
  2580. if ( x.length() === 0 ) {
  2581. z.x += 0.0001;
  2582. x.crossVectors( up, z ).normalize();
  2583. }
  2584. y.crossVectors( z, x );
  2585. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2586. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2587. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2588. return this;
  2589. };
  2590. }(),
  2591. multiply: function ( m, n ) {
  2592. if ( n !== undefined ) {
  2593. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2594. return this.multiplyMatrices( m, n );
  2595. }
  2596. return this.multiplyMatrices( this, m );
  2597. },
  2598. multiplyMatrices: function ( a, b ) {
  2599. var ae = a.elements;
  2600. var be = b.elements;
  2601. var te = this.elements;
  2602. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2603. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2604. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2605. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2606. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2607. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2608. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2609. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2610. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2611. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2612. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2613. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2614. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2615. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2616. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2617. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2618. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2619. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2620. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2621. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2622. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2623. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2624. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2625. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2626. return this;
  2627. },
  2628. multiplyToArray: function ( a, b, r ) {
  2629. var te = this.elements;
  2630. this.multiplyMatrices( a, b );
  2631. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2632. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2633. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2634. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2635. return this;
  2636. },
  2637. multiplyScalar: function ( s ) {
  2638. var te = this.elements;
  2639. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2640. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2641. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2642. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2643. return this;
  2644. },
  2645. multiplyVector3: function ( vector ) {
  2646. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2647. return vector.applyProjection( this );
  2648. },
  2649. multiplyVector4: function ( vector ) {
  2650. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2651. return vector.applyMatrix4( this );
  2652. },
  2653. multiplyVector3Array: function() {
  2654. var v1 = new THREE.Vector3();
  2655. return function ( a ) {
  2656. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2657. v1.x = a[ i ];
  2658. v1.y = a[ i + 1 ];
  2659. v1.z = a[ i + 2 ];
  2660. v1.applyProjection( this );
  2661. a[ i ] = v1.x;
  2662. a[ i + 1 ] = v1.y;
  2663. a[ i + 2 ] = v1.z;
  2664. }
  2665. return a;
  2666. };
  2667. }(),
  2668. rotateAxis: function ( v ) {
  2669. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2670. v.transformDirection( this );
  2671. },
  2672. crossVector: function ( vector ) {
  2673. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2674. return vector.applyMatrix4( this );
  2675. },
  2676. determinant: function () {
  2677. var te = this.elements;
  2678. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2679. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2680. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2681. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2682. //TODO: make this more efficient
  2683. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2684. return (
  2685. n41 * (
  2686. +n14 * n23 * n32
  2687. -n13 * n24 * n32
  2688. -n14 * n22 * n33
  2689. +n12 * n24 * n33
  2690. +n13 * n22 * n34
  2691. -n12 * n23 * n34
  2692. ) +
  2693. n42 * (
  2694. +n11 * n23 * n34
  2695. -n11 * n24 * n33
  2696. +n14 * n21 * n33
  2697. -n13 * n21 * n34
  2698. +n13 * n24 * n31
  2699. -n14 * n23 * n31
  2700. ) +
  2701. n43 * (
  2702. +n11 * n24 * n32
  2703. -n11 * n22 * n34
  2704. -n14 * n21 * n32
  2705. +n12 * n21 * n34
  2706. +n14 * n22 * n31
  2707. -n12 * n24 * n31
  2708. ) +
  2709. n44 * (
  2710. -n13 * n22 * n31
  2711. -n11 * n23 * n32
  2712. +n11 * n22 * n33
  2713. +n13 * n21 * n32
  2714. -n12 * n21 * n33
  2715. +n12 * n23 * n31
  2716. )
  2717. );
  2718. },
  2719. transpose: function () {
  2720. var te = this.elements;
  2721. var tmp;
  2722. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2723. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2724. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2725. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2726. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2727. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2728. return this;
  2729. },
  2730. flattenToArray: function ( flat ) {
  2731. var te = this.elements;
  2732. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2733. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2734. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2735. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2736. return flat;
  2737. },
  2738. flattenToArrayOffset: function( flat, offset ) {
  2739. var te = this.elements;
  2740. flat[ offset ] = te[0];
  2741. flat[ offset + 1 ] = te[1];
  2742. flat[ offset + 2 ] = te[2];
  2743. flat[ offset + 3 ] = te[3];
  2744. flat[ offset + 4 ] = te[4];
  2745. flat[ offset + 5 ] = te[5];
  2746. flat[ offset + 6 ] = te[6];
  2747. flat[ offset + 7 ] = te[7];
  2748. flat[ offset + 8 ] = te[8];
  2749. flat[ offset + 9 ] = te[9];
  2750. flat[ offset + 10 ] = te[10];
  2751. flat[ offset + 11 ] = te[11];
  2752. flat[ offset + 12 ] = te[12];
  2753. flat[ offset + 13 ] = te[13];
  2754. flat[ offset + 14 ] = te[14];
  2755. flat[ offset + 15 ] = te[15];
  2756. return flat;
  2757. },
  2758. getPosition: function() {
  2759. var v1 = new THREE.Vector3();
  2760. return function () {
  2761. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  2762. var te = this.elements;
  2763. return v1.set( te[12], te[13], te[14] );
  2764. };
  2765. }(),
  2766. setPosition: function ( v ) {
  2767. var te = this.elements;
  2768. te[12] = v.x;
  2769. te[13] = v.y;
  2770. te[14] = v.z;
  2771. return this;
  2772. },
  2773. getInverse: function ( m, throwOnInvertible ) {
  2774. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2775. var te = this.elements;
  2776. var me = m.elements;
  2777. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2778. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2779. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2780. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2781. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2782. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2783. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2784. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2785. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2786. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2787. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2788. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2789. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2790. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2791. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2792. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2793. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2794. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2795. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2796. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2797. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2798. if ( det == 0 ) {
  2799. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2800. if ( throwOnInvertible || false ) {
  2801. throw new Error( msg );
  2802. } else {
  2803. console.warn( msg );
  2804. }
  2805. this.identity();
  2806. return this;
  2807. }
  2808. this.multiplyScalar( 1 / det );
  2809. return this;
  2810. },
  2811. translate: function ( v ) {
  2812. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2813. },
  2814. rotateX: function ( angle ) {
  2815. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2816. },
  2817. rotateY: function ( angle ) {
  2818. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2819. },
  2820. rotateZ: function ( angle ) {
  2821. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2822. },
  2823. rotateByAxis: function ( axis, angle ) {
  2824. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2825. },
  2826. scale: function ( v ) {
  2827. var te = this.elements;
  2828. var x = v.x, y = v.y, z = v.z;
  2829. te[0] *= x; te[4] *= y; te[8] *= z;
  2830. te[1] *= x; te[5] *= y; te[9] *= z;
  2831. te[2] *= x; te[6] *= y; te[10] *= z;
  2832. te[3] *= x; te[7] *= y; te[11] *= z;
  2833. return this;
  2834. },
  2835. getMaxScaleOnAxis: function () {
  2836. var te = this.elements;
  2837. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2838. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2839. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2840. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2841. },
  2842. makeTranslation: function ( x, y, z ) {
  2843. this.set(
  2844. 1, 0, 0, x,
  2845. 0, 1, 0, y,
  2846. 0, 0, 1, z,
  2847. 0, 0, 0, 1
  2848. );
  2849. return this;
  2850. },
  2851. makeRotationX: function ( theta ) {
  2852. var c = Math.cos( theta ), s = Math.sin( theta );
  2853. this.set(
  2854. 1, 0, 0, 0,
  2855. 0, c, -s, 0,
  2856. 0, s, c, 0,
  2857. 0, 0, 0, 1
  2858. );
  2859. return this;
  2860. },
  2861. makeRotationY: function ( theta ) {
  2862. var c = Math.cos( theta ), s = Math.sin( theta );
  2863. this.set(
  2864. c, 0, s, 0,
  2865. 0, 1, 0, 0,
  2866. -s, 0, c, 0,
  2867. 0, 0, 0, 1
  2868. );
  2869. return this;
  2870. },
  2871. makeRotationZ: function ( theta ) {
  2872. var c = Math.cos( theta ), s = Math.sin( theta );
  2873. this.set(
  2874. c, -s, 0, 0,
  2875. s, c, 0, 0,
  2876. 0, 0, 1, 0,
  2877. 0, 0, 0, 1
  2878. );
  2879. return this;
  2880. },
  2881. makeRotationAxis: function ( axis, angle ) {
  2882. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2883. var c = Math.cos( angle );
  2884. var s = Math.sin( angle );
  2885. var t = 1 - c;
  2886. var x = axis.x, y = axis.y, z = axis.z;
  2887. var tx = t * x, ty = t * y;
  2888. this.set(
  2889. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2890. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2891. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2892. 0, 0, 0, 1
  2893. );
  2894. return this;
  2895. },
  2896. makeScale: function ( x, y, z ) {
  2897. this.set(
  2898. x, 0, 0, 0,
  2899. 0, y, 0, 0,
  2900. 0, 0, z, 0,
  2901. 0, 0, 0, 1
  2902. );
  2903. return this;
  2904. },
  2905. compose: function ( position, quaternion, scale ) {
  2906. this.makeRotationFromQuaternion( quaternion );
  2907. this.scale( scale );
  2908. this.setPosition( position );
  2909. return this;
  2910. },
  2911. decompose: function () {
  2912. var vector = new THREE.Vector3();
  2913. var matrix = new THREE.Matrix4();
  2914. return function ( position, quaternion, scale ) {
  2915. var te = this.elements;
  2916. var sx = vector.set( te[0], te[1], te[2] ).length();
  2917. var sy = vector.set( te[4], te[5], te[6] ).length();
  2918. var sz = vector.set( te[8], te[9], te[10] ).length();
  2919. // if determine is negative, we need to invert one scale
  2920. var det = this.determinant();
  2921. if( det < 0 ) {
  2922. sx = -sx;
  2923. }
  2924. position.x = te[12];
  2925. position.y = te[13];
  2926. position.z = te[14];
  2927. // scale the rotation part
  2928. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  2929. var invSX = 1 / sx;
  2930. var invSY = 1 / sy;
  2931. var invSZ = 1 / sz;
  2932. matrix.elements[0] *= invSX;
  2933. matrix.elements[1] *= invSX;
  2934. matrix.elements[2] *= invSX;
  2935. matrix.elements[4] *= invSY;
  2936. matrix.elements[5] *= invSY;
  2937. matrix.elements[6] *= invSY;
  2938. matrix.elements[8] *= invSZ;
  2939. matrix.elements[9] *= invSZ;
  2940. matrix.elements[10] *= invSZ;
  2941. quaternion.setFromRotationMatrix( matrix );
  2942. scale.x = sx;
  2943. scale.y = sy;
  2944. scale.z = sz;
  2945. return this;
  2946. };
  2947. }(),
  2948. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2949. var te = this.elements;
  2950. var x = 2 * near / ( right - left );
  2951. var y = 2 * near / ( top - bottom );
  2952. var a = ( right + left ) / ( right - left );
  2953. var b = ( top + bottom ) / ( top - bottom );
  2954. var c = - ( far + near ) / ( far - near );
  2955. var d = - 2 * far * near / ( far - near );
  2956. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2957. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2958. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2959. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2960. return this;
  2961. },
  2962. makePerspective: function ( fov, aspect, near, far ) {
  2963. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2964. var ymin = - ymax;
  2965. var xmin = ymin * aspect;
  2966. var xmax = ymax * aspect;
  2967. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2968. },
  2969. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2970. var te = this.elements;
  2971. var w = right - left;
  2972. var h = top - bottom;
  2973. var p = far - near;
  2974. var x = ( right + left ) / w;
  2975. var y = ( top + bottom ) / h;
  2976. var z = ( far + near ) / p;
  2977. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2978. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2979. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2980. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2981. return this;
  2982. },
  2983. fromArray: function ( array ) {
  2984. this.elements.set( array );
  2985. return this;
  2986. },
  2987. toArray: function () {
  2988. var te = this.elements;
  2989. return [
  2990. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  2991. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  2992. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  2993. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  2994. ];
  2995. },
  2996. clone: function () {
  2997. var te = this.elements;
  2998. return new THREE.Matrix4(
  2999. te[0], te[4], te[8], te[12],
  3000. te[1], te[5], te[9], te[13],
  3001. te[2], te[6], te[10], te[14],
  3002. te[3], te[7], te[11], te[15]
  3003. );
  3004. }
  3005. };
  3006. /**
  3007. * @author bhouston / http://exocortex.com
  3008. */
  3009. THREE.Ray = function ( origin, direction ) {
  3010. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3011. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3012. };
  3013. THREE.Ray.prototype = {
  3014. constructor: THREE.Ray,
  3015. set: function ( origin, direction ) {
  3016. this.origin.copy( origin );
  3017. this.direction.copy( direction );
  3018. return this;
  3019. },
  3020. copy: function ( ray ) {
  3021. this.origin.copy( ray.origin );
  3022. this.direction.copy( ray.direction );
  3023. return this;
  3024. },
  3025. at: function ( t, optionalTarget ) {
  3026. var result = optionalTarget || new THREE.Vector3();
  3027. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3028. },
  3029. recast: function () {
  3030. var v1 = new THREE.Vector3();
  3031. return function ( t ) {
  3032. this.origin.copy( this.at( t, v1 ) );
  3033. return this;
  3034. };
  3035. }(),
  3036. closestPointToPoint: function ( point, optionalTarget ) {
  3037. var result = optionalTarget || new THREE.Vector3();
  3038. result.subVectors( point, this.origin );
  3039. var directionDistance = result.dot( this.direction );
  3040. if ( directionDistance < 0 ) {
  3041. return result.copy( this.origin );
  3042. }
  3043. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3044. },
  3045. distanceToPoint: function () {
  3046. var v1 = new THREE.Vector3();
  3047. return function ( point ) {
  3048. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3049. // point behind the ray
  3050. if ( directionDistance < 0 ) {
  3051. return this.origin.distanceTo( point );
  3052. }
  3053. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3054. return v1.distanceTo( point );
  3055. };
  3056. }(),
  3057. distanceSqToSegment: function( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3058. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3059. // It returns the min distance between the ray and the segment
  3060. // defined by v0 and v1
  3061. // It can also set two optional targets :
  3062. // - The closest point on the ray
  3063. // - The closest point on the segment
  3064. var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 );
  3065. var segDir = v1.clone().sub( v0 ).normalize();
  3066. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3067. var diff = this.origin.clone().sub( segCenter );
  3068. var a01 = - this.direction.dot( segDir );
  3069. var b0 = diff.dot( this.direction );
  3070. var b1 = - diff.dot( segDir );
  3071. var c = diff.lengthSq();
  3072. var det = Math.abs( 1 - a01 * a01 );
  3073. var s0, s1, sqrDist, extDet;
  3074. if ( det >= 0 ) {
  3075. // The ray and segment are not parallel.
  3076. s0 = a01 * b1 - b0;
  3077. s1 = a01 * b0 - b1;
  3078. extDet = segExtent * det;
  3079. if ( s0 >= 0 ) {
  3080. if ( s1 >= - extDet ) {
  3081. if ( s1 <= extDet ) {
  3082. // region 0
  3083. // Minimum at interior points of ray and segment.
  3084. var invDet = 1 / det;
  3085. s0 *= invDet;
  3086. s1 *= invDet;
  3087. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3088. } else {
  3089. // region 1
  3090. s1 = segExtent;
  3091. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3092. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3093. }
  3094. } else {
  3095. // region 5
  3096. s1 = - segExtent;
  3097. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3098. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3099. }
  3100. } else {
  3101. if ( s1 <= - extDet) {
  3102. // region 4
  3103. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3104. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3105. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3106. } else if ( s1 <= extDet ) {
  3107. // region 3
  3108. s0 = 0;
  3109. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3110. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3111. } else {
  3112. // region 2
  3113. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3114. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3115. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3116. }
  3117. }
  3118. } else {
  3119. // Ray and segment are parallel.
  3120. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3121. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3122. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3123. }
  3124. if ( optionalPointOnRay ) {
  3125. optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) );
  3126. }
  3127. if ( optionalPointOnSegment ) {
  3128. optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) );
  3129. }
  3130. return sqrDist;
  3131. },
  3132. isIntersectionSphere: function ( sphere ) {
  3133. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3134. },
  3135. isIntersectionPlane: function ( plane ) {
  3136. // check if the ray lies on the plane first
  3137. var distToPoint = plane.distanceToPoint( this.origin );
  3138. if ( distToPoint === 0 ) {
  3139. return true;
  3140. }
  3141. var denominator = plane.normal.dot( this.direction );
  3142. if ( denominator * distToPoint < 0 ) {
  3143. return true
  3144. }
  3145. // ray origin is behind the plane (and is pointing behind it)
  3146. return false;
  3147. },
  3148. distanceToPlane: function ( plane ) {
  3149. var denominator = plane.normal.dot( this.direction );
  3150. if ( denominator == 0 ) {
  3151. // line is coplanar, return origin
  3152. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3153. return 0;
  3154. }
  3155. // Null is preferable to undefined since undefined means.... it is undefined
  3156. return null;
  3157. }
  3158. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3159. // Return if the ray never intersects the plane
  3160. return t >= 0 ? t : null;
  3161. },
  3162. intersectPlane: function ( plane, optionalTarget ) {
  3163. var t = this.distanceToPlane( plane );
  3164. if ( t === null ) {
  3165. return null;
  3166. }
  3167. return this.at( t, optionalTarget );
  3168. },
  3169. isIntersectionBox: function () {
  3170. var v = new THREE.Vector3();
  3171. return function ( box ) {
  3172. return this.intersectBox( box, v ) !== null;
  3173. }
  3174. }(),
  3175. intersectBox: function ( box , optionalTarget ) {
  3176. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3177. var tmin,tmax,tymin,tymax,tzmin,tzmax;
  3178. var invdirx = 1/this.direction.x,
  3179. invdiry = 1/this.direction.y,
  3180. invdirz = 1/this.direction.z;
  3181. var origin = this.origin;
  3182. if (invdirx >= 0) {
  3183. tmin = (box.min.x - origin.x) * invdirx;
  3184. tmax = (box.max.x - origin.x) * invdirx;
  3185. } else {
  3186. tmin = (box.max.x - origin.x) * invdirx;
  3187. tmax = (box.min.x - origin.x) * invdirx;
  3188. }
  3189. if (invdiry >= 0) {
  3190. tymin = (box.min.y - origin.y) * invdiry;
  3191. tymax = (box.max.y - origin.y) * invdiry;
  3192. } else {
  3193. tymin = (box.max.y - origin.y) * invdiry;
  3194. tymax = (box.min.y - origin.y) * invdiry;
  3195. }
  3196. if ((tmin > tymax) || (tymin > tmax)) return null;
  3197. // These lines also handle the case where tmin or tmax is NaN
  3198. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3199. if (tymin > tmin || tmin !== tmin ) tmin = tymin;
  3200. if (tymax < tmax || tmax !== tmax ) tmax = tymax;
  3201. if (invdirz >= 0) {
  3202. tzmin = (box.min.z - origin.z) * invdirz;
  3203. tzmax = (box.max.z - origin.z) * invdirz;
  3204. } else {
  3205. tzmin = (box.max.z - origin.z) * invdirz;
  3206. tzmax = (box.min.z - origin.z) * invdirz;
  3207. }
  3208. if ((tmin > tzmax) || (tzmin > tmax)) return null;
  3209. if (tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3210. if (tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3211. //return point closest to the ray (positive side)
  3212. if ( tmax < 0 ) return null;
  3213. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3214. },
  3215. intersectTriangle: function() {
  3216. // Compute the offset origin, edges, and normal.
  3217. var diff = new THREE.Vector3();
  3218. var edge1 = new THREE.Vector3();
  3219. var edge2 = new THREE.Vector3();
  3220. var normal = new THREE.Vector3();
  3221. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3222. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3223. edge1.subVectors( b, a );
  3224. edge2.subVectors( c, a );
  3225. normal.crossVectors( edge1, edge2 );
  3226. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3227. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3228. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3229. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3230. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3231. var DdN = this.direction.dot( normal );
  3232. var sign;
  3233. if ( DdN > 0 ) {
  3234. if ( backfaceCulling ) return null;
  3235. sign = 1;
  3236. } else if ( DdN < 0 ) {
  3237. sign = - 1;
  3238. DdN = - DdN;
  3239. } else {
  3240. return null;
  3241. }
  3242. diff.subVectors( this.origin, a );
  3243. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3244. // b1 < 0, no intersection
  3245. if ( DdQxE2 < 0 ) {
  3246. return null;
  3247. }
  3248. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3249. // b2 < 0, no intersection
  3250. if ( DdE1xQ < 0 ) {
  3251. return null;
  3252. }
  3253. // b1+b2 > 1, no intersection
  3254. if ( DdQxE2 + DdE1xQ > DdN ) {
  3255. return null;
  3256. }
  3257. // Line intersects triangle, check if ray does.
  3258. var QdN = - sign * diff.dot( normal );
  3259. // t < 0, no intersection
  3260. if ( QdN < 0 ) {
  3261. return null;
  3262. }
  3263. // Ray intersects triangle.
  3264. return this.at( QdN / DdN, optionalTarget );
  3265. }
  3266. }(),
  3267. applyMatrix4: function ( matrix4 ) {
  3268. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3269. this.origin.applyMatrix4( matrix4 );
  3270. this.direction.sub( this.origin );
  3271. this.direction.normalize();
  3272. return this;
  3273. },
  3274. equals: function ( ray ) {
  3275. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3276. },
  3277. clone: function () {
  3278. return new THREE.Ray().copy( this );
  3279. }
  3280. };
  3281. /**
  3282. * @author bhouston / http://exocortex.com
  3283. * @author mrdoob / http://mrdoob.com/
  3284. */
  3285. THREE.Sphere = function ( center, radius ) {
  3286. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3287. this.radius = ( radius !== undefined ) ? radius : 0;
  3288. };
  3289. THREE.Sphere.prototype = {
  3290. constructor: THREE.Sphere,
  3291. set: function ( center, radius ) {
  3292. this.center.copy( center );
  3293. this.radius = radius;
  3294. return this;
  3295. },
  3296. setFromPoints: function () {
  3297. var box = new THREE.Box3();
  3298. return function ( points, optionalCenter ) {
  3299. var center = this.center;
  3300. if ( optionalCenter !== undefined ) {
  3301. center.copy( optionalCenter );
  3302. } else {
  3303. box.setFromPoints( points ).center( center );
  3304. }
  3305. var maxRadiusSq = 0;
  3306. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3307. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3308. }
  3309. this.radius = Math.sqrt( maxRadiusSq );
  3310. return this;
  3311. };
  3312. }(),
  3313. copy: function ( sphere ) {
  3314. this.center.copy( sphere.center );
  3315. this.radius = sphere.radius;
  3316. return this;
  3317. },
  3318. empty: function () {
  3319. return ( this.radius <= 0 );
  3320. },
  3321. containsPoint: function ( point ) {
  3322. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3323. },
  3324. distanceToPoint: function ( point ) {
  3325. return ( point.distanceTo( this.center ) - this.radius );
  3326. },
  3327. intersectsSphere: function ( sphere ) {
  3328. var radiusSum = this.radius + sphere.radius;
  3329. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3330. },
  3331. clampPoint: function ( point, optionalTarget ) {
  3332. var deltaLengthSq = this.center.distanceToSquared( point );
  3333. var result = optionalTarget || new THREE.Vector3();
  3334. result.copy( point );
  3335. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3336. result.sub( this.center ).normalize();
  3337. result.multiplyScalar( this.radius ).add( this.center );
  3338. }
  3339. return result;
  3340. },
  3341. getBoundingBox: function ( optionalTarget ) {
  3342. var box = optionalTarget || new THREE.Box3();
  3343. box.set( this.center, this.center );
  3344. box.expandByScalar( this.radius );
  3345. return box;
  3346. },
  3347. applyMatrix4: function ( matrix ) {
  3348. this.center.applyMatrix4( matrix );
  3349. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3350. return this;
  3351. },
  3352. translate: function ( offset ) {
  3353. this.center.add( offset );
  3354. return this;
  3355. },
  3356. equals: function ( sphere ) {
  3357. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3358. },
  3359. clone: function () {
  3360. return new THREE.Sphere().copy( this );
  3361. }
  3362. };
  3363. /**
  3364. * @author mrdoob / http://mrdoob.com/
  3365. * @author alteredq / http://alteredqualia.com/
  3366. * @author bhouston / http://exocortex.com
  3367. */
  3368. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3369. this.planes = [
  3370. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3371. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3372. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3373. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3374. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3375. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3376. ];
  3377. };
  3378. THREE.Frustum.prototype = {
  3379. constructor: THREE.Frustum,
  3380. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3381. var planes = this.planes;
  3382. planes[0].copy( p0 );
  3383. planes[1].copy( p1 );
  3384. planes[2].copy( p2 );
  3385. planes[3].copy( p3 );
  3386. planes[4].copy( p4 );
  3387. planes[5].copy( p5 );
  3388. return this;
  3389. },
  3390. copy: function ( frustum ) {
  3391. var planes = this.planes;
  3392. for( var i = 0; i < 6; i ++ ) {
  3393. planes[i].copy( frustum.planes[i] );
  3394. }
  3395. return this;
  3396. },
  3397. setFromMatrix: function ( m ) {
  3398. var planes = this.planes;
  3399. var me = m.elements;
  3400. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3401. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3402. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3403. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3404. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3405. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3406. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3407. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3408. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3409. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3410. return this;
  3411. },
  3412. intersectsObject: function () {
  3413. var sphere = new THREE.Sphere();
  3414. return function ( object ) {
  3415. var geometry = object.geometry;
  3416. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3417. sphere.copy( geometry.boundingSphere );
  3418. sphere.applyMatrix4( object.matrixWorld );
  3419. return this.intersectsSphere( sphere );
  3420. };
  3421. }(),
  3422. intersectsSphere: function ( sphere ) {
  3423. var planes = this.planes;
  3424. var center = sphere.center;
  3425. var negRadius = -sphere.radius;
  3426. for ( var i = 0; i < 6; i ++ ) {
  3427. var distance = planes[ i ].distanceToPoint( center );
  3428. if ( distance < negRadius ) {
  3429. return false;
  3430. }
  3431. }
  3432. return true;
  3433. },
  3434. intersectsBox : function() {
  3435. var p1 = new THREE.Vector3(),
  3436. p2 = new THREE.Vector3();
  3437. return function( box ) {
  3438. var planes = this.planes;
  3439. for ( var i = 0; i < 6 ; i ++ ) {
  3440. var plane = planes[i];
  3441. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3442. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3443. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3444. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3445. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3446. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3447. var d1 = plane.distanceToPoint( p1 );
  3448. var d2 = plane.distanceToPoint( p2 );
  3449. // if both outside plane, no intersection
  3450. if ( d1 < 0 && d2 < 0 ) {
  3451. return false;
  3452. }
  3453. }
  3454. return true;
  3455. };
  3456. }(),
  3457. containsPoint: function ( point ) {
  3458. var planes = this.planes;
  3459. for ( var i = 0; i < 6; i ++ ) {
  3460. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3461. return false;
  3462. }
  3463. }
  3464. return true;
  3465. },
  3466. clone: function () {
  3467. return new THREE.Frustum().copy( this );
  3468. }
  3469. };
  3470. /**
  3471. * @author bhouston / http://exocortex.com
  3472. */
  3473. THREE.Plane = function ( normal, constant ) {
  3474. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3475. this.constant = ( constant !== undefined ) ? constant : 0;
  3476. };
  3477. THREE.Plane.prototype = {
  3478. constructor: THREE.Plane,
  3479. set: function ( normal, constant ) {
  3480. this.normal.copy( normal );
  3481. this.constant = constant;
  3482. return this;
  3483. },
  3484. setComponents: function ( x, y, z, w ) {
  3485. this.normal.set( x, y, z );
  3486. this.constant = w;
  3487. return this;
  3488. },
  3489. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3490. this.normal.copy( normal );
  3491. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3492. return this;
  3493. },
  3494. setFromCoplanarPoints: function() {
  3495. var v1 = new THREE.Vector3();
  3496. var v2 = new THREE.Vector3();
  3497. return function ( a, b, c ) {
  3498. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3499. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3500. this.setFromNormalAndCoplanarPoint( normal, a );
  3501. return this;
  3502. };
  3503. }(),
  3504. copy: function ( plane ) {
  3505. this.normal.copy( plane.normal );
  3506. this.constant = plane.constant;
  3507. return this;
  3508. },
  3509. normalize: function () {
  3510. // Note: will lead to a divide by zero if the plane is invalid.
  3511. var inverseNormalLength = 1.0 / this.normal.length();
  3512. this.normal.multiplyScalar( inverseNormalLength );
  3513. this.constant *= inverseNormalLength;
  3514. return this;
  3515. },
  3516. negate: function () {
  3517. this.constant *= -1;
  3518. this.normal.negate();
  3519. return this;
  3520. },
  3521. distanceToPoint: function ( point ) {
  3522. return this.normal.dot( point ) + this.constant;
  3523. },
  3524. distanceToSphere: function ( sphere ) {
  3525. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3526. },
  3527. projectPoint: function ( point, optionalTarget ) {
  3528. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3529. },
  3530. orthoPoint: function ( point, optionalTarget ) {
  3531. var perpendicularMagnitude = this.distanceToPoint( point );
  3532. var result = optionalTarget || new THREE.Vector3();
  3533. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3534. },
  3535. isIntersectionLine: function ( line ) {
  3536. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3537. var startSign = this.distanceToPoint( line.start );
  3538. var endSign = this.distanceToPoint( line.end );
  3539. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3540. },
  3541. intersectLine: function() {
  3542. var v1 = new THREE.Vector3();
  3543. return function ( line, optionalTarget ) {
  3544. var result = optionalTarget || new THREE.Vector3();
  3545. var direction = line.delta( v1 );
  3546. var denominator = this.normal.dot( direction );
  3547. if ( denominator == 0 ) {
  3548. // line is coplanar, return origin
  3549. if( this.distanceToPoint( line.start ) == 0 ) {
  3550. return result.copy( line.start );
  3551. }
  3552. // Unsure if this is the correct method to handle this case.
  3553. return undefined;
  3554. }
  3555. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3556. if( t < 0 || t > 1 ) {
  3557. return undefined;
  3558. }
  3559. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3560. };
  3561. }(),
  3562. coplanarPoint: function ( optionalTarget ) {
  3563. var result = optionalTarget || new THREE.Vector3();
  3564. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3565. },
  3566. applyMatrix4: function() {
  3567. var v1 = new THREE.Vector3();
  3568. var v2 = new THREE.Vector3();
  3569. var m1 = new THREE.Matrix3();
  3570. return function ( matrix, optionalNormalMatrix ) {
  3571. // compute new normal based on theory here:
  3572. // http://www.songho.ca/opengl/gl_normaltransform.html
  3573. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3574. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3575. var newCoplanarPoint = this.coplanarPoint( v2 );
  3576. newCoplanarPoint.applyMatrix4( matrix );
  3577. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3578. return this;
  3579. };
  3580. }(),
  3581. translate: function ( offset ) {
  3582. this.constant = this.constant - offset.dot( this.normal );
  3583. return this;
  3584. },
  3585. equals: function ( plane ) {
  3586. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3587. },
  3588. clone: function () {
  3589. return new THREE.Plane().copy( this );
  3590. }
  3591. };
  3592. /**
  3593. * @author alteredq / http://alteredqualia.com/
  3594. * @author mrdoob / http://mrdoob.com/
  3595. */
  3596. THREE.Math = {
  3597. PI2: Math.PI * 2,
  3598. generateUUID: function () {
  3599. // http://www.broofa.com/Tools/Math.uuid.htm
  3600. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3601. var uuid = new Array(36);
  3602. var rnd = 0, r;
  3603. return function () {
  3604. for ( var i = 0; i < 36; i ++ ) {
  3605. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3606. uuid[ i ] = '-';
  3607. } else if ( i == 14 ) {
  3608. uuid[ i ] = '4';
  3609. } else {
  3610. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3611. r = rnd & 0xf;
  3612. rnd = rnd >> 4;
  3613. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3614. }
  3615. }
  3616. return uuid.join('');
  3617. };
  3618. }(),
  3619. // Clamp value to range <a, b>
  3620. clamp: function ( x, a, b ) {
  3621. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3622. },
  3623. // Clamp value to range <a, inf)
  3624. clampBottom: function ( x, a ) {
  3625. return x < a ? a : x;
  3626. },
  3627. // Linear mapping from range <a1, a2> to range <b1, b2>
  3628. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3629. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3630. },
  3631. // http://en.wikipedia.org/wiki/Smoothstep
  3632. smoothstep: function ( x, min, max ) {
  3633. if ( x <= min ) return 0;
  3634. if ( x >= max ) return 1;
  3635. x = ( x - min )/( max - min );
  3636. return x*x*(3 - 2*x);
  3637. },
  3638. smootherstep: function ( x, min, max ) {
  3639. if ( x <= min ) return 0;
  3640. if ( x >= max ) return 1;
  3641. x = ( x - min )/( max - min );
  3642. return x*x*x*(x*(x*6 - 15) + 10);
  3643. },
  3644. // Random float from <0, 1> with 16 bits of randomness
  3645. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3646. random16: function () {
  3647. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3648. },
  3649. // Random integer from <low, high> interval
  3650. randInt: function ( low, high ) {
  3651. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3652. },
  3653. // Random float from <low, high> interval
  3654. randFloat: function ( low, high ) {
  3655. return low + Math.random() * ( high - low );
  3656. },
  3657. // Random float from <-range/2, range/2> interval
  3658. randFloatSpread: function ( range ) {
  3659. return range * ( 0.5 - Math.random() );
  3660. },
  3661. sign: function ( x ) {
  3662. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : 0;
  3663. },
  3664. degToRad: function() {
  3665. var degreeToRadiansFactor = Math.PI / 180;
  3666. return function ( degrees ) {
  3667. return degrees * degreeToRadiansFactor;
  3668. };
  3669. }(),
  3670. radToDeg: function() {
  3671. var radianToDegreesFactor = 180 / Math.PI;
  3672. return function ( radians ) {
  3673. return radians * radianToDegreesFactor;
  3674. };
  3675. }(),
  3676. isPowerOfTwo: function ( value ) {
  3677. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  3678. }
  3679. };
  3680. /**
  3681. * Spline from Tween.js, slightly optimized (and trashed)
  3682. * http://sole.github.com/tween.js/examples/05_spline.html
  3683. *
  3684. * @author mrdoob / http://mrdoob.com/
  3685. * @author alteredq / http://alteredqualia.com/
  3686. */
  3687. THREE.Spline = function ( points ) {
  3688. this.points = points;
  3689. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3690. point, intPoint, weight, w2, w3,
  3691. pa, pb, pc, pd;
  3692. this.initFromArray = function( a ) {
  3693. this.points = [];
  3694. for ( var i = 0; i < a.length; i++ ) {
  3695. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3696. }
  3697. };
  3698. this.getPoint = function ( k ) {
  3699. point = ( this.points.length - 1 ) * k;
  3700. intPoint = Math.floor( point );
  3701. weight = point - intPoint;
  3702. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3703. c[ 1 ] = intPoint;
  3704. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3705. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3706. pa = this.points[ c[ 0 ] ];
  3707. pb = this.points[ c[ 1 ] ];
  3708. pc = this.points[ c[ 2 ] ];
  3709. pd = this.points[ c[ 3 ] ];
  3710. w2 = weight * weight;
  3711. w3 = weight * w2;
  3712. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3713. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3714. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3715. return v3;
  3716. };
  3717. this.getControlPointsArray = function () {
  3718. var i, p, l = this.points.length,
  3719. coords = [];
  3720. for ( i = 0; i < l; i ++ ) {
  3721. p = this.points[ i ];
  3722. coords[ i ] = [ p.x, p.y, p.z ];
  3723. }
  3724. return coords;
  3725. };
  3726. // approximate length by summing linear segments
  3727. this.getLength = function ( nSubDivisions ) {
  3728. var i, index, nSamples, position,
  3729. point = 0, intPoint = 0, oldIntPoint = 0,
  3730. oldPosition = new THREE.Vector3(),
  3731. tmpVec = new THREE.Vector3(),
  3732. chunkLengths = [],
  3733. totalLength = 0;
  3734. // first point has 0 length
  3735. chunkLengths[ 0 ] = 0;
  3736. if ( !nSubDivisions ) nSubDivisions = 100;
  3737. nSamples = this.points.length * nSubDivisions;
  3738. oldPosition.copy( this.points[ 0 ] );
  3739. for ( i = 1; i < nSamples; i ++ ) {
  3740. index = i / nSamples;
  3741. position = this.getPoint( index );
  3742. tmpVec.copy( position );
  3743. totalLength += tmpVec.distanceTo( oldPosition );
  3744. oldPosition.copy( position );
  3745. point = ( this.points.length - 1 ) * index;
  3746. intPoint = Math.floor( point );
  3747. if ( intPoint != oldIntPoint ) {
  3748. chunkLengths[ intPoint ] = totalLength;
  3749. oldIntPoint = intPoint;
  3750. }
  3751. }
  3752. // last point ends with total length
  3753. chunkLengths[ chunkLengths.length ] = totalLength;
  3754. return { chunks: chunkLengths, total: totalLength };
  3755. };
  3756. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3757. var i, j,
  3758. index, indexCurrent, indexNext,
  3759. linearDistance, realDistance,
  3760. sampling, position,
  3761. newpoints = [],
  3762. tmpVec = new THREE.Vector3(),
  3763. sl = this.getLength();
  3764. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3765. for ( i = 1; i < this.points.length; i++ ) {
  3766. //tmpVec.copy( this.points[ i - 1 ] );
  3767. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3768. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3769. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3770. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3771. indexNext = i / ( this.points.length - 1 );
  3772. for ( j = 1; j < sampling - 1; j++ ) {
  3773. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3774. position = this.getPoint( index );
  3775. newpoints.push( tmpVec.copy( position ).clone() );
  3776. }
  3777. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3778. }
  3779. this.points = newpoints;
  3780. };
  3781. // Catmull-Rom
  3782. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3783. var v0 = ( p2 - p0 ) * 0.5,
  3784. v1 = ( p3 - p1 ) * 0.5;
  3785. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3786. };
  3787. };
  3788. /**
  3789. * @author bhouston / http://exocortex.com
  3790. * @author mrdoob / http://mrdoob.com/
  3791. */
  3792. THREE.Triangle = function ( a, b, c ) {
  3793. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3794. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3795. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3796. };
  3797. THREE.Triangle.normal = function() {
  3798. var v0 = new THREE.Vector3();
  3799. return function ( a, b, c, optionalTarget ) {
  3800. var result = optionalTarget || new THREE.Vector3();
  3801. result.subVectors( c, b );
  3802. v0.subVectors( a, b );
  3803. result.cross( v0 );
  3804. var resultLengthSq = result.lengthSq();
  3805. if( resultLengthSq > 0 ) {
  3806. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3807. }
  3808. return result.set( 0, 0, 0 );
  3809. };
  3810. }();
  3811. // static/instance method to calculate barycoordinates
  3812. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3813. THREE.Triangle.barycoordFromPoint = function() {
  3814. var v0 = new THREE.Vector3();
  3815. var v1 = new THREE.Vector3();
  3816. var v2 = new THREE.Vector3();
  3817. return function ( point, a, b, c, optionalTarget ) {
  3818. v0.subVectors( c, a );
  3819. v1.subVectors( b, a );
  3820. v2.subVectors( point, a );
  3821. var dot00 = v0.dot( v0 );
  3822. var dot01 = v0.dot( v1 );
  3823. var dot02 = v0.dot( v2 );
  3824. var dot11 = v1.dot( v1 );
  3825. var dot12 = v1.dot( v2 );
  3826. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3827. var result = optionalTarget || new THREE.Vector3();
  3828. // colinear or singular triangle
  3829. if( denom == 0 ) {
  3830. // arbitrary location outside of triangle?
  3831. // not sure if this is the best idea, maybe should be returning undefined
  3832. return result.set( -2, -1, -1 );
  3833. }
  3834. var invDenom = 1 / denom;
  3835. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3836. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3837. // barycoordinates must always sum to 1
  3838. return result.set( 1 - u - v, v, u );
  3839. };
  3840. }();
  3841. THREE.Triangle.containsPoint = function() {
  3842. var v1 = new THREE.Vector3();
  3843. return function ( point, a, b, c ) {
  3844. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3845. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3846. };
  3847. }();
  3848. THREE.Triangle.prototype = {
  3849. constructor: THREE.Triangle,
  3850. set: function ( a, b, c ) {
  3851. this.a.copy( a );
  3852. this.b.copy( b );
  3853. this.c.copy( c );
  3854. return this;
  3855. },
  3856. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3857. this.a.copy( points[i0] );
  3858. this.b.copy( points[i1] );
  3859. this.c.copy( points[i2] );
  3860. return this;
  3861. },
  3862. copy: function ( triangle ) {
  3863. this.a.copy( triangle.a );
  3864. this.b.copy( triangle.b );
  3865. this.c.copy( triangle.c );
  3866. return this;
  3867. },
  3868. area: function() {
  3869. var v0 = new THREE.Vector3();
  3870. var v1 = new THREE.Vector3();
  3871. return function () {
  3872. v0.subVectors( this.c, this.b );
  3873. v1.subVectors( this.a, this.b );
  3874. return v0.cross( v1 ).length() * 0.5;
  3875. };
  3876. }(),
  3877. midpoint: function ( optionalTarget ) {
  3878. var result = optionalTarget || new THREE.Vector3();
  3879. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3880. },
  3881. normal: function ( optionalTarget ) {
  3882. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3883. },
  3884. plane: function ( optionalTarget ) {
  3885. var result = optionalTarget || new THREE.Plane();
  3886. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3887. },
  3888. barycoordFromPoint: function ( point, optionalTarget ) {
  3889. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3890. },
  3891. containsPoint: function ( point ) {
  3892. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3893. },
  3894. equals: function ( triangle ) {
  3895. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3896. },
  3897. clone: function () {
  3898. return new THREE.Triangle().copy( this );
  3899. }
  3900. };
  3901. /**
  3902. * @author mrdoob / http://mrdoob.com/
  3903. */
  3904. THREE.Vertex = function ( v ) {
  3905. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3906. return v;
  3907. };
  3908. /**
  3909. * @author mrdoob / http://mrdoob.com/
  3910. */
  3911. THREE.UV = function ( u, v ) {
  3912. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3913. return new THREE.Vector2( u, v );
  3914. };
  3915. /**
  3916. * @author alteredq / http://alteredqualia.com/
  3917. */
  3918. THREE.Clock = function ( autoStart ) {
  3919. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3920. this.startTime = 0;
  3921. this.oldTime = 0;
  3922. this.elapsedTime = 0;
  3923. this.running = false;
  3924. };
  3925. THREE.Clock.prototype = {
  3926. constructor: THREE.Clock,
  3927. start: function () {
  3928. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  3929. ? self.performance.now()
  3930. : Date.now();
  3931. this.oldTime = this.startTime;
  3932. this.running = true;
  3933. },
  3934. stop: function () {
  3935. this.getElapsedTime();
  3936. this.running = false;
  3937. },
  3938. getElapsedTime: function () {
  3939. this.getDelta();
  3940. return this.elapsedTime;
  3941. },
  3942. getDelta: function () {
  3943. var diff = 0;
  3944. if ( this.autoStart && ! this.running ) {
  3945. this.start();
  3946. }
  3947. if ( this.running ) {
  3948. var newTime = self.performance !== undefined && self.performance.now !== undefined
  3949. ? self.performance.now()
  3950. : Date.now();
  3951. diff = 0.001 * ( newTime - this.oldTime );
  3952. this.oldTime = newTime;
  3953. this.elapsedTime += diff;
  3954. }
  3955. return diff;
  3956. }
  3957. };
  3958. /**
  3959. * https://github.com/mrdoob/eventdispatcher.js/
  3960. */
  3961. THREE.EventDispatcher = function () {}
  3962. THREE.EventDispatcher.prototype = {
  3963. constructor: THREE.EventDispatcher,
  3964. apply: function ( object ) {
  3965. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  3966. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  3967. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  3968. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  3969. },
  3970. addEventListener: function ( type, listener ) {
  3971. if ( this._listeners === undefined ) this._listeners = {};
  3972. var listeners = this._listeners;
  3973. if ( listeners[ type ] === undefined ) {
  3974. listeners[ type ] = [];
  3975. }
  3976. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3977. listeners[ type ].push( listener );
  3978. }
  3979. },
  3980. hasEventListener: function ( type, listener ) {
  3981. if ( this._listeners === undefined ) return false;
  3982. var listeners = this._listeners;
  3983. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  3984. return true;
  3985. }
  3986. return false;
  3987. },
  3988. removeEventListener: function ( type, listener ) {
  3989. if ( this._listeners === undefined ) return;
  3990. var listeners = this._listeners;
  3991. var listenerArray = listeners[ type ];
  3992. if ( listenerArray !== undefined ) {
  3993. var index = listenerArray.indexOf( listener );
  3994. if ( index !== - 1 ) {
  3995. listenerArray.splice( index, 1 );
  3996. }
  3997. }
  3998. },
  3999. dispatchEvent: function () {
  4000. var array = [];
  4001. return function ( event ) {
  4002. if ( this._listeners === undefined ) return;
  4003. var listeners = this._listeners;
  4004. var listenerArray = listeners[ event.type ];
  4005. if ( listenerArray !== undefined ) {
  4006. event.target = this;
  4007. var length = listenerArray.length;
  4008. for ( var i = 0; i < length; i ++ ) {
  4009. array[ i ] = listenerArray[ i ];
  4010. }
  4011. for ( var i = 0; i < length; i ++ ) {
  4012. array[ i ].call( this, event );
  4013. }
  4014. }
  4015. };
  4016. }()
  4017. };
  4018. /**
  4019. * @author mrdoob / http://mrdoob.com/
  4020. * @author bhouston / http://exocortex.com/
  4021. * @author stephomi / http://stephaneginier.com/
  4022. */
  4023. ( function ( THREE ) {
  4024. THREE.Raycaster = function ( origin, direction, near, far ) {
  4025. this.ray = new THREE.Ray( origin, direction );
  4026. // direction is assumed to be normalized (for accurate distance calculations)
  4027. this.near = near || 0;
  4028. this.far = far || Infinity;
  4029. };
  4030. var sphere = new THREE.Sphere();
  4031. var localRay = new THREE.Ray();
  4032. var facePlane = new THREE.Plane();
  4033. var intersectPoint = new THREE.Vector3();
  4034. var matrixPosition = new THREE.Vector3();
  4035. var inverseMatrix = new THREE.Matrix4();
  4036. var descSort = function ( a, b ) {
  4037. return a.distance - b.distance;
  4038. };
  4039. var vA = new THREE.Vector3();
  4040. var vB = new THREE.Vector3();
  4041. var vC = new THREE.Vector3();
  4042. var intersectObject = function ( object, raycaster, intersects ) {
  4043. if ( object instanceof THREE.Sprite ) {
  4044. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4045. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  4046. if ( distance > object.scale.x ) {
  4047. return intersects;
  4048. }
  4049. intersects.push( {
  4050. distance: distance,
  4051. point: object.position,
  4052. face: null,
  4053. object: object
  4054. } );
  4055. } else if ( object instanceof THREE.LOD ) {
  4056. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4057. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  4058. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  4059. } else if ( object instanceof THREE.Mesh ) {
  4060. var geometry = object.geometry;
  4061. // Checking boundingSphere distance to ray
  4062. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4063. sphere.copy( geometry.boundingSphere );
  4064. sphere.applyMatrix4( object.matrixWorld );
  4065. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4066. return intersects;
  4067. }
  4068. // Check boundingBox before continuing
  4069. inverseMatrix.getInverse( object.matrixWorld );
  4070. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4071. if ( geometry.boundingBox !== null ) {
  4072. if ( localRay.isIntersectionBox( geometry.boundingBox ) === false ) {
  4073. return intersects;
  4074. }
  4075. }
  4076. if ( geometry instanceof THREE.BufferGeometry ) {
  4077. var material = object.material;
  4078. if ( material === undefined ) return intersects;
  4079. if ( geometry.dynamic === false ) return intersects;
  4080. var a, b, c;
  4081. var precision = raycaster.precision;
  4082. if ( geometry.attributes.index !== undefined ) {
  4083. var offsets = geometry.offsets;
  4084. var indices = geometry.attributes.index.array;
  4085. var positions = geometry.attributes.position.array;
  4086. var offLength = geometry.offsets.length;
  4087. var fl = geometry.attributes.index.array.length / 3;
  4088. for ( var oi = 0; oi < offLength; ++oi ) {
  4089. var start = offsets[ oi ].start;
  4090. var count = offsets[ oi ].count;
  4091. var index = offsets[ oi ].index;
  4092. for ( var i = start, il = start + count; i < il; i += 3 ) {
  4093. a = index + indices[ i ];
  4094. b = index + indices[ i + 1 ];
  4095. c = index + indices[ i + 2 ];
  4096. vA.set(
  4097. positions[ a * 3 ],
  4098. positions[ a * 3 + 1 ],
  4099. positions[ a * 3 + 2 ]
  4100. );
  4101. vB.set(
  4102. positions[ b * 3 ],
  4103. positions[ b * 3 + 1 ],
  4104. positions[ b * 3 + 2 ]
  4105. );
  4106. vC.set(
  4107. positions[ c * 3 ],
  4108. positions[ c * 3 + 1 ],
  4109. positions[ c * 3 + 2 ]
  4110. );
  4111. if ( material.side === THREE.BackSide ) {
  4112. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4113. } else {
  4114. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4115. }
  4116. if ( intersectionPoint === null ) continue;
  4117. intersectionPoint.applyMatrix4( object.matrixWorld );
  4118. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4119. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4120. intersects.push( {
  4121. distance: distance,
  4122. point: intersectionPoint,
  4123. face: null,
  4124. faceIndex: null,
  4125. object: object
  4126. } );
  4127. }
  4128. }
  4129. } else {
  4130. var offsets = geometry.offsets;
  4131. var positions = geometry.attributes.position.array;
  4132. var offLength = geometry.offsets.length;
  4133. var fl = geometry.attributes.position.array.length;
  4134. for ( var i = 0; i < fl; i += 3 ) {
  4135. a = i;
  4136. b = i + 1;
  4137. c = i + 2;
  4138. vA.set(
  4139. positions[ a * 3 ],
  4140. positions[ a * 3 + 1 ],
  4141. positions[ a * 3 + 2 ]
  4142. );
  4143. vB.set(
  4144. positions[ b * 3 ],
  4145. positions[ b * 3 + 1 ],
  4146. positions[ b * 3 + 2 ]
  4147. );
  4148. vC.set(
  4149. positions[ c * 3 ],
  4150. positions[ c * 3 + 1 ],
  4151. positions[ c * 3 + 2 ]
  4152. );
  4153. if ( material.side === THREE.BackSide ) {
  4154. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4155. } else {
  4156. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4157. }
  4158. if ( intersectionPoint === null ) continue;
  4159. intersectionPoint.applyMatrix4( object.matrixWorld );
  4160. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4161. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4162. intersects.push( {
  4163. distance: distance,
  4164. point: intersectionPoint,
  4165. face: null,
  4166. faceIndex: null,
  4167. object: object
  4168. } );
  4169. }
  4170. }
  4171. } else if ( geometry instanceof THREE.Geometry ) {
  4172. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4173. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  4174. var a, b, c, d;
  4175. var precision = raycaster.precision;
  4176. var vertices = geometry.vertices;
  4177. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  4178. var face = geometry.faces[ f ];
  4179. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  4180. if ( material === undefined ) continue;
  4181. a = vertices[ face.a ];
  4182. b = vertices[ face.b ];
  4183. c = vertices[ face.c ];
  4184. if ( material.morphTargets === true ) {
  4185. var morphTargets = geometry.morphTargets;
  4186. var morphInfluences = object.morphTargetInfluences;
  4187. vA.set( 0, 0, 0 );
  4188. vB.set( 0, 0, 0 );
  4189. vC.set( 0, 0, 0 );
  4190. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  4191. var influence = morphInfluences[ t ];
  4192. if ( influence === 0 ) continue;
  4193. var targets = morphTargets[ t ].vertices;
  4194. vA.x += ( targets[ face.a ].x - a.x ) * influence;
  4195. vA.y += ( targets[ face.a ].y - a.y ) * influence;
  4196. vA.z += ( targets[ face.a ].z - a.z ) * influence;
  4197. vB.x += ( targets[ face.b ].x - b.x ) * influence;
  4198. vB.y += ( targets[ face.b ].y - b.y ) * influence;
  4199. vB.z += ( targets[ face.b ].z - b.z ) * influence;
  4200. vC.x += ( targets[ face.c ].x - c.x ) * influence;
  4201. vC.y += ( targets[ face.c ].y - c.y ) * influence;
  4202. vC.z += ( targets[ face.c ].z - c.z ) * influence;
  4203. }
  4204. vA.add( a );
  4205. vB.add( b );
  4206. vC.add( c );
  4207. a = vA;
  4208. b = vB;
  4209. c = vC;
  4210. }
  4211. if ( material.side === THREE.BackSide ) {
  4212. var intersectionPoint = localRay.intersectTriangle( c, b, a, true );
  4213. } else {
  4214. var intersectionPoint = localRay.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
  4215. }
  4216. if ( intersectionPoint === null ) continue;
  4217. intersectionPoint.applyMatrix4( object.matrixWorld );
  4218. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4219. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4220. intersects.push( {
  4221. distance: distance,
  4222. point: intersectionPoint,
  4223. face: face,
  4224. faceIndex: f,
  4225. object: object
  4226. } );
  4227. }
  4228. }
  4229. } else if ( object instanceof THREE.Line ) {
  4230. var precision = raycaster.linePrecision;
  4231. var precisionSq = precision * precision;
  4232. var geometry = object.geometry;
  4233. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4234. // Checking boundingSphere distance to ray
  4235. sphere.copy( geometry.boundingSphere );
  4236. sphere.applyMatrix4( object.matrixWorld );
  4237. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4238. return intersects;
  4239. }
  4240. inverseMatrix.getInverse( object.matrixWorld );
  4241. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4242. /* if ( geometry instanceof THREE.BufferGeometry ) {
  4243. } else */ if ( geometry instanceof THREE.Geometry ) {
  4244. var vertices = geometry.vertices;
  4245. var nbVertices = vertices.length;
  4246. var interSegment = new THREE.Vector3();
  4247. var interRay = new THREE.Vector3();
  4248. var step = object.type === THREE.LineStrip ? 1 : 2;
  4249. for ( var i = 0; i < nbVertices - 1; i = i + step ) {
  4250. var distSq = localRay.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  4251. if ( distSq > precisionSq ) continue;
  4252. var distance = localRay.origin.distanceTo( interRay );
  4253. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  4254. intersects.push( {
  4255. distance: distance,
  4256. // What do we want? intersection point on the ray or on the segment??
  4257. // point: raycaster.ray.at( distance ),
  4258. point: interSegment.clone().applyMatrix4( object.matrixWorld ),
  4259. face: null,
  4260. faceIndex: null,
  4261. object: object
  4262. } );
  4263. }
  4264. }
  4265. }
  4266. };
  4267. var intersectDescendants = function ( object, raycaster, intersects ) {
  4268. var descendants = object.getDescendants();
  4269. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  4270. intersectObject( descendants[ i ], raycaster, intersects );
  4271. }
  4272. };
  4273. //
  4274. THREE.Raycaster.prototype.precision = 0.0001;
  4275. THREE.Raycaster.prototype.linePrecision = 1;
  4276. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  4277. this.ray.set( origin, direction );
  4278. // direction is assumed to be normalized (for accurate distance calculations)
  4279. };
  4280. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  4281. var intersects = [];
  4282. if ( recursive === true ) {
  4283. intersectDescendants( object, this, intersects );
  4284. }
  4285. intersectObject( object, this, intersects );
  4286. intersects.sort( descSort );
  4287. return intersects;
  4288. };
  4289. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  4290. var intersects = [];
  4291. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4292. intersectObject( objects[ i ], this, intersects );
  4293. if ( recursive === true ) {
  4294. intersectDescendants( objects[ i ], this, intersects );
  4295. }
  4296. }
  4297. intersects.sort( descSort );
  4298. return intersects;
  4299. };
  4300. }( THREE ) );
  4301. /**
  4302. * @author mrdoob / http://mrdoob.com/
  4303. * @author mikael emtinger / http://gomo.se/
  4304. * @author alteredq / http://alteredqualia.com/
  4305. * @author WestLangley / http://github.com/WestLangley
  4306. */
  4307. THREE.Object3D = function () {
  4308. this.id = THREE.Object3DIdCount ++;
  4309. this.uuid = THREE.Math.generateUUID();
  4310. this.name = '';
  4311. this.parent = undefined;
  4312. this.children = [];
  4313. this.up = new THREE.Vector3( 0, 1, 0 );
  4314. this.position = new THREE.Vector3();
  4315. this._rotation = new THREE.Euler();
  4316. this._quaternion = new THREE.Quaternion();
  4317. this.scale = new THREE.Vector3( 1, 1, 1 );
  4318. // keep rotation and quaternion in sync
  4319. this._rotation._quaternion = this.quaternion;
  4320. this._quaternion._euler = this.rotation;
  4321. this.renderDepth = null;
  4322. this.rotationAutoUpdate = true;
  4323. this.matrix = new THREE.Matrix4();
  4324. this.matrixWorld = new THREE.Matrix4();
  4325. this.matrixAutoUpdate = true;
  4326. this.matrixWorldNeedsUpdate = true;
  4327. this.visible = true;
  4328. this.castShadow = false;
  4329. this.receiveShadow = false;
  4330. this.frustumCulled = true;
  4331. this.userData = {};
  4332. };
  4333. THREE.Object3D.prototype = {
  4334. constructor: THREE.Object3D,
  4335. get rotation () {
  4336. return this._rotation;
  4337. },
  4338. set rotation ( value ) {
  4339. this._rotation = value;
  4340. this._rotation._quaternion = this._quaternion;
  4341. this._quaternion._euler = this._rotation;
  4342. this._rotation._updateQuaternion();
  4343. },
  4344. get quaternion () {
  4345. return this._quaternion;
  4346. },
  4347. set quaternion ( value ) {
  4348. this._quaternion = value;
  4349. this._quaternion._euler = this._rotation;
  4350. this._rotation._quaternion = this._quaternion;
  4351. this._quaternion._updateEuler();
  4352. },
  4353. get eulerOrder () {
  4354. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4355. return this.rotation.order;
  4356. },
  4357. set eulerOrder ( value ) {
  4358. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4359. this.rotation.order = value;
  4360. },
  4361. get useQuaternion () {
  4362. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4363. },
  4364. set useQuaternion ( value ) {
  4365. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4366. },
  4367. applyMatrix: function ( matrix ) {
  4368. this.matrix.multiplyMatrices( matrix, this.matrix );
  4369. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4370. },
  4371. setRotationFromAxisAngle: function ( axis, angle ) {
  4372. // assumes axis is normalized
  4373. this.quaternion.setFromAxisAngle( axis, angle );
  4374. },
  4375. setRotationFromEuler: function ( euler ) {
  4376. this.quaternion.setFromEuler( euler, true );
  4377. },
  4378. setRotationFromMatrix: function ( m ) {
  4379. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4380. this.quaternion.setFromRotationMatrix( m );
  4381. },
  4382. setRotationFromQuaternion: function ( q ) {
  4383. // assumes q is normalized
  4384. this.quaternion.copy( q );
  4385. },
  4386. rotateOnAxis: function() {
  4387. // rotate object on axis in object space
  4388. // axis is assumed to be normalized
  4389. var q1 = new THREE.Quaternion();
  4390. return function ( axis, angle ) {
  4391. q1.setFromAxisAngle( axis, angle );
  4392. this.quaternion.multiply( q1 );
  4393. return this;
  4394. }
  4395. }(),
  4396. rotateX: function () {
  4397. var v1 = new THREE.Vector3( 1, 0, 0 );
  4398. return function ( angle ) {
  4399. return this.rotateOnAxis( v1, angle );
  4400. };
  4401. }(),
  4402. rotateY: function () {
  4403. var v1 = new THREE.Vector3( 0, 1, 0 );
  4404. return function ( angle ) {
  4405. return this.rotateOnAxis( v1, angle );
  4406. };
  4407. }(),
  4408. rotateZ: function () {
  4409. var v1 = new THREE.Vector3( 0, 0, 1 );
  4410. return function ( angle ) {
  4411. return this.rotateOnAxis( v1, angle );
  4412. };
  4413. }(),
  4414. translateOnAxis: function () {
  4415. // translate object by distance along axis in object space
  4416. // axis is assumed to be normalized
  4417. var v1 = new THREE.Vector3();
  4418. return function ( axis, distance ) {
  4419. v1.copy( axis );
  4420. v1.applyQuaternion( this.quaternion );
  4421. this.position.add( v1.multiplyScalar( distance ) );
  4422. return this;
  4423. }
  4424. }(),
  4425. translate: function ( distance, axis ) {
  4426. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  4427. return this.translateOnAxis( axis, distance );
  4428. },
  4429. translateX: function () {
  4430. var v1 = new THREE.Vector3( 1, 0, 0 );
  4431. return function ( distance ) {
  4432. return this.translateOnAxis( v1, distance );
  4433. };
  4434. }(),
  4435. translateY: function () {
  4436. var v1 = new THREE.Vector3( 0, 1, 0 );
  4437. return function ( distance ) {
  4438. return this.translateOnAxis( v1, distance );
  4439. };
  4440. }(),
  4441. translateZ: function () {
  4442. var v1 = new THREE.Vector3( 0, 0, 1 );
  4443. return function ( distance ) {
  4444. return this.translateOnAxis( v1, distance );
  4445. };
  4446. }(),
  4447. localToWorld: function ( vector ) {
  4448. return vector.applyMatrix4( this.matrixWorld );
  4449. },
  4450. worldToLocal: function () {
  4451. var m1 = new THREE.Matrix4();
  4452. return function ( vector ) {
  4453. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4454. };
  4455. }(),
  4456. lookAt: function () {
  4457. // This routine does not support objects with rotated and/or translated parent(s)
  4458. var m1 = new THREE.Matrix4();
  4459. return function ( vector ) {
  4460. m1.lookAt( vector, this.position, this.up );
  4461. this.quaternion.setFromRotationMatrix( m1 );
  4462. };
  4463. }(),
  4464. add: function ( object ) {
  4465. if ( object === this ) {
  4466. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  4467. return;
  4468. }
  4469. if ( object instanceof THREE.Object3D ) {
  4470. if ( object.parent !== undefined ) {
  4471. object.parent.remove( object );
  4472. }
  4473. object.parent = this;
  4474. object.dispatchEvent( { type: 'added' } );
  4475. this.children.push( object );
  4476. // add to scene
  4477. var scene = this;
  4478. while ( scene.parent !== undefined ) {
  4479. scene = scene.parent;
  4480. }
  4481. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4482. scene.__addObject( object );
  4483. }
  4484. }
  4485. },
  4486. remove: function ( object ) {
  4487. var index = this.children.indexOf( object );
  4488. if ( index !== - 1 ) {
  4489. object.parent = undefined;
  4490. object.dispatchEvent( { type: 'removed' } );
  4491. this.children.splice( index, 1 );
  4492. // remove from scene
  4493. var scene = this;
  4494. while ( scene.parent !== undefined ) {
  4495. scene = scene.parent;
  4496. }
  4497. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4498. scene.__removeObject( object );
  4499. }
  4500. }
  4501. },
  4502. traverse: function ( callback ) {
  4503. callback( this );
  4504. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4505. this.children[ i ].traverse( callback );
  4506. }
  4507. },
  4508. getObjectById: function ( id, recursive ) {
  4509. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4510. var child = this.children[ i ];
  4511. if ( child.id === id ) {
  4512. return child;
  4513. }
  4514. if ( recursive === true ) {
  4515. child = child.getObjectById( id, recursive );
  4516. if ( child !== undefined ) {
  4517. return child;
  4518. }
  4519. }
  4520. }
  4521. return undefined;
  4522. },
  4523. getObjectByName: function ( name, recursive ) {
  4524. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4525. var child = this.children[ i ];
  4526. if ( child.name === name ) {
  4527. return child;
  4528. }
  4529. if ( recursive === true ) {
  4530. child = child.getObjectByName( name, recursive );
  4531. if ( child !== undefined ) {
  4532. return child;
  4533. }
  4534. }
  4535. }
  4536. return undefined;
  4537. },
  4538. getChildByName: function ( name, recursive ) {
  4539. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  4540. return this.getObjectByName( name, recursive );
  4541. },
  4542. getDescendants: function ( array ) {
  4543. if ( array === undefined ) array = [];
  4544. Array.prototype.push.apply( array, this.children );
  4545. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4546. this.children[ i ].getDescendants( array );
  4547. }
  4548. return array;
  4549. },
  4550. updateMatrix: function () {
  4551. this.matrix.compose( this.position, this.quaternion, this.scale );
  4552. this.matrixWorldNeedsUpdate = true;
  4553. },
  4554. updateMatrixWorld: function ( force ) {
  4555. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4556. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4557. if ( this.parent === undefined ) {
  4558. this.matrixWorld.copy( this.matrix );
  4559. } else {
  4560. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4561. }
  4562. this.matrixWorldNeedsUpdate = false;
  4563. force = true;
  4564. }
  4565. // update children
  4566. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4567. this.children[ i ].updateMatrixWorld( force );
  4568. }
  4569. },
  4570. clone: function ( object, recursive ) {
  4571. if ( object === undefined ) object = new THREE.Object3D();
  4572. if ( recursive === undefined ) recursive = true;
  4573. object.name = this.name;
  4574. object.up.copy( this.up );
  4575. object.position.copy( this.position );
  4576. object.quaternion.copy( this.quaternion );
  4577. object.scale.copy( this.scale );
  4578. object.renderDepth = this.renderDepth;
  4579. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4580. object.matrix.copy( this.matrix );
  4581. object.matrixWorld.copy( this.matrixWorld );
  4582. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4583. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4584. object.visible = this.visible;
  4585. object.castShadow = this.castShadow;
  4586. object.receiveShadow = this.receiveShadow;
  4587. object.frustumCulled = this.frustumCulled;
  4588. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4589. if ( recursive === true ) {
  4590. for ( var i = 0; i < this.children.length; i ++ ) {
  4591. var child = this.children[ i ];
  4592. object.add( child.clone() );
  4593. }
  4594. }
  4595. return object;
  4596. }
  4597. };
  4598. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4599. THREE.Object3DIdCount = 0;
  4600. /**
  4601. * @author mrdoob / http://mrdoob.com/
  4602. * @author supereggbert / http://www.paulbrunt.co.uk/
  4603. * @author julianwa / https://github.com/julianwa
  4604. */
  4605. THREE.Projector = function () {
  4606. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4607. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4608. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  4609. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4610. _sprite, _spriteCount, _spritePool = [], _spritePoolLength = 0,
  4611. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  4612. _vA = new THREE.Vector3(),
  4613. _vB = new THREE.Vector3(),
  4614. _vC = new THREE.Vector3(),
  4615. _vector3 = new THREE.Vector3(),
  4616. _vector4 = new THREE.Vector4(),
  4617. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4618. _boundingBox = new THREE.Box3(),
  4619. _points3 = new Array( 3 ),
  4620. _points4 = new Array( 4 ),
  4621. _viewMatrix = new THREE.Matrix4(),
  4622. _viewProjectionMatrix = new THREE.Matrix4(),
  4623. _modelMatrix,
  4624. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4625. _normalMatrix = new THREE.Matrix3(),
  4626. _normalViewMatrix = new THREE.Matrix3(),
  4627. _centroid = new THREE.Vector3(),
  4628. _frustum = new THREE.Frustum(),
  4629. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4630. _clippedVertex2PositionScreen = new THREE.Vector4();
  4631. this.projectVector = function ( vector, camera ) {
  4632. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4633. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4634. return vector.applyProjection( _viewProjectionMatrix );
  4635. };
  4636. this.unprojectVector = function () {
  4637. var projectionMatrixInverse = new THREE.Matrix4();
  4638. return function ( vector, camera ) {
  4639. projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4640. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, projectionMatrixInverse );
  4641. return vector.applyProjection( _viewProjectionMatrix );
  4642. };
  4643. }();
  4644. this.pickingRay = function ( vector, camera ) {
  4645. // set two vectors with opposing z values
  4646. vector.z = -1.0;
  4647. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4648. this.unprojectVector( vector, camera );
  4649. this.unprojectVector( end, camera );
  4650. // find direction from vector to end
  4651. end.sub( vector ).normalize();
  4652. return new THREE.Raycaster( vector, end );
  4653. };
  4654. var getObject = function ( object ) {
  4655. _object = getNextObjectInPool();
  4656. _object.id = object.id;
  4657. _object.object = object;
  4658. if ( object.renderDepth !== null ) {
  4659. _object.z = object.renderDepth;
  4660. } else {
  4661. _vector3.setFromMatrixPosition( object.matrixWorld );
  4662. _vector3.applyProjection( _viewProjectionMatrix );
  4663. _object.z = _vector3.z;
  4664. }
  4665. return _object;
  4666. };
  4667. var projectObject = function ( object ) {
  4668. if ( object.visible === false ) return;
  4669. if ( object instanceof THREE.Light ) {
  4670. _renderData.lights.push( object );
  4671. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  4672. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4673. _renderData.objects.push( getObject( object ) );
  4674. }
  4675. } else if ( object instanceof THREE.Sprite ) {
  4676. _renderData.sprites.push( getObject( object ) );
  4677. }
  4678. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4679. projectObject( object.children[ i ] );
  4680. }
  4681. };
  4682. var projectGraph = function ( root, sortObjects ) {
  4683. _objectCount = 0;
  4684. _renderData.objects.length = 0;
  4685. _renderData.sprites.length = 0;
  4686. _renderData.lights.length = 0;
  4687. projectObject( root );
  4688. if ( sortObjects === true ) {
  4689. _renderData.objects.sort( painterSort );
  4690. }
  4691. };
  4692. var RenderList = function () {
  4693. var object = null;
  4694. var setObject = function ( value ) {
  4695. object = value;
  4696. };
  4697. var projectVertex = function ( vertex ) {
  4698. var position = vertex.position;
  4699. var positionWorld = vertex.positionWorld;
  4700. var positionScreen = vertex.positionScreen;
  4701. positionWorld.copy( position ).applyMatrix4( _modelMatrix );
  4702. positionScreen.copy( positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4703. var invW = 1 / positionScreen.w;
  4704. positionScreen.x *= invW;
  4705. positionScreen.y *= invW;
  4706. positionScreen.z *= invW;
  4707. vertex.visible = positionScreen.x >= -1 && positionScreen.x <= 1 &&
  4708. positionScreen.y >= -1 && positionScreen.y <= 1 &&
  4709. positionScreen.z >= -1 && positionScreen.z <= 1;
  4710. };
  4711. var pushVertex = function ( x, y, z ) {
  4712. _vertex = getNextVertexInPool();
  4713. _vertex.position.set( x, y, z );
  4714. projectVertex( _vertex );
  4715. };
  4716. var checkTriangleVisibility = function ( v1, v2, v3 ) {
  4717. _points3[ 0 ] = v1.positionScreen;
  4718. _points3[ 1 ] = v2.positionScreen;
  4719. _points3[ 2 ] = v3.positionScreen;
  4720. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4721. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4722. return ( ( v3.positionScreen.x - v1.positionScreen.x ) *
  4723. ( v2.positionScreen.y - v1.positionScreen.y ) -
  4724. ( v3.positionScreen.y - v1.positionScreen.y ) *
  4725. ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4726. }
  4727. return false;
  4728. };
  4729. var pushLine = function ( a, b ) {
  4730. var v1 = _vertexPool[ a ];
  4731. var v2 = _vertexPool[ b ];
  4732. _line = getNextLineInPool();
  4733. _line.id = object.id;
  4734. _line.v1.copy( v1 );
  4735. _line.v2.copy( v2 );
  4736. _face.z = ( v1.positionScreen.z + v2.positionScreen.z ) / 2;
  4737. _line.material = object.material;
  4738. _renderData.elements.push( _line );
  4739. };
  4740. var pushTriangle = function ( a, b, c ) {
  4741. var v1 = _vertexPool[ a ];
  4742. var v2 = _vertexPool[ b ];
  4743. var v3 = _vertexPool[ c ];
  4744. if ( checkTriangleVisibility( v1, v2, v3 ) === true ) {
  4745. _face = getNextFace3InPool();
  4746. _face.id = object.id;
  4747. _face.v1.copy( v1 );
  4748. _face.v2.copy( v2 );
  4749. _face.v3.copy( v3 );
  4750. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  4751. _face.material = object.material;
  4752. _renderData.elements.push( _face );
  4753. }
  4754. };
  4755. return {
  4756. setObject: setObject,
  4757. projectVertex: projectVertex,
  4758. checkTriangleVisibility: checkTriangleVisibility,
  4759. pushVertex: pushVertex,
  4760. pushLine: pushLine,
  4761. pushTriangle: pushTriangle
  4762. }
  4763. };
  4764. var renderList = new RenderList();
  4765. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4766. var object, geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  4767. isFaceMaterial, objectMaterials;
  4768. _face3Count = 0;
  4769. _lineCount = 0;
  4770. _spriteCount = 0;
  4771. _renderData.elements.length = 0;
  4772. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4773. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4774. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4775. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4776. _normalViewMatrix.getNormalMatrix( _viewMatrix );
  4777. _frustum.setFromMatrix( _viewProjectionMatrix );
  4778. projectGraph( scene, sortObjects );
  4779. for ( var o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4780. object = _renderData.objects[ o ].object;
  4781. geometry = object.geometry;
  4782. renderList.setObject( object );
  4783. _modelMatrix = object.matrixWorld;
  4784. _vertexCount = 0;
  4785. if ( object instanceof THREE.Mesh ) {
  4786. if ( geometry instanceof THREE.BufferGeometry ) {
  4787. var attributes = geometry.attributes;
  4788. if ( attributes.position !== undefined ) {
  4789. var positions = attributes.position.array;
  4790. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  4791. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  4792. }
  4793. if ( attributes.index !== undefined ) {
  4794. var indices = attributes.index.array;
  4795. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  4796. renderList.pushTriangle( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  4797. }
  4798. } else {
  4799. for ( var i = 0, l = positions.length / 3; i < l; i += 3 ) {
  4800. renderList.pushTriangle( i, i + 1, i + 2 );
  4801. }
  4802. }
  4803. }
  4804. } else if ( geometry instanceof THREE.Geometry2 ) {
  4805. vertices = geometry.vertices;
  4806. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  4807. renderList.pushVertex( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] );
  4808. }
  4809. for ( var i = 0, l = vertices.length / 3; i < l; i += 3 ) {
  4810. renderList.pushTriangle( i, i + 1, i + 2 );
  4811. }
  4812. } else if ( geometry instanceof THREE.Geometry ) {
  4813. vertices = geometry.vertices;
  4814. faces = geometry.faces;
  4815. faceVertexUvs = geometry.faceVertexUvs;
  4816. _normalMatrix.getNormalMatrix( _modelMatrix );
  4817. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4818. objectMaterials = isFaceMaterial === true ? object.material : null;
  4819. for ( var v = 0, vl = vertices.length; v < vl; v ++ ) {
  4820. var vertex = vertices[ v ];
  4821. renderList.pushVertex( vertex.x, vertex.y, vertex.z );
  4822. }
  4823. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  4824. face = faces[ f ];
  4825. var material = isFaceMaterial === true
  4826. ? objectMaterials.materials[ face.materialIndex ]
  4827. : object.material;
  4828. if ( material === undefined ) continue;
  4829. var side = material.side;
  4830. var v1 = _vertexPool[ face.a ];
  4831. var v2 = _vertexPool[ face.b ];
  4832. var v3 = _vertexPool[ face.c ];
  4833. if ( material.morphTargets === true ) {
  4834. var morphTargets = geometry.morphTargets;
  4835. var morphInfluences = object.morphTargetInfluences;
  4836. var v1p = v1.position;
  4837. var v2p = v2.position;
  4838. var v3p = v3.position;
  4839. _vA.set( 0, 0, 0 );
  4840. _vB.set( 0, 0, 0 );
  4841. _vC.set( 0, 0, 0 );
  4842. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  4843. var influence = morphInfluences[ t ];
  4844. if ( influence === 0 ) continue;
  4845. var targets = morphTargets[ t ].vertices;
  4846. _vA.x += ( targets[ face.a ].x - v1p.x ) * influence;
  4847. _vA.y += ( targets[ face.a ].y - v1p.y ) * influence;
  4848. _vA.z += ( targets[ face.a ].z - v1p.z ) * influence;
  4849. _vB.x += ( targets[ face.b ].x - v2p.x ) * influence;
  4850. _vB.y += ( targets[ face.b ].y - v2p.y ) * influence;
  4851. _vB.z += ( targets[ face.b ].z - v2p.z ) * influence;
  4852. _vC.x += ( targets[ face.c ].x - v3p.x ) * influence;
  4853. _vC.y += ( targets[ face.c ].y - v3p.y ) * influence;
  4854. _vC.z += ( targets[ face.c ].z - v3p.z ) * influence;
  4855. }
  4856. v1.position.add( _vA );
  4857. v2.position.add( _vB );
  4858. v3.position.add( _vC );
  4859. renderList.projectVertex( v1 );
  4860. renderList.projectVertex( v2 );
  4861. renderList.projectVertex( v3 );
  4862. }
  4863. var visible = renderList.checkTriangleVisibility( v1, v2, v3 );
  4864. if ( visible === ( side === THREE.BackSide ) ) continue;
  4865. _face = getNextFace3InPool();
  4866. _face.id = object.id;
  4867. _face.v1.copy( v1 );
  4868. _face.v2.copy( v2 );
  4869. _face.v3.copy( v3 );
  4870. _face.normalModel.copy( face.normal );
  4871. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4872. _face.normalModel.negate();
  4873. }
  4874. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4875. _face.normalModelView.copy( _face.normalModel ).applyMatrix3( _normalViewMatrix );
  4876. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4877. faceVertexNormals = face.vertexNormals;
  4878. for ( var n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) {
  4879. var normalModel = _face.vertexNormalsModel[ n ];
  4880. normalModel.copy( faceVertexNormals[ n ] );
  4881. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4882. normalModel.negate();
  4883. }
  4884. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4885. var normalModelView = _face.vertexNormalsModelView[ n ];
  4886. normalModelView.copy( normalModel ).applyMatrix3( _normalViewMatrix );
  4887. }
  4888. _face.vertexNormalsLength = faceVertexNormals.length;
  4889. for ( var c = 0, cl = Math.min( faceVertexUvs.length, 3 ); c < cl; c ++ ) {
  4890. uvs = faceVertexUvs[ c ][ f ];
  4891. if ( uvs === undefined ) continue;
  4892. for ( var u = 0, ul = uvs.length; u < ul; u ++ ) {
  4893. _face.uvs[ c ][ u ] = uvs[ u ];
  4894. }
  4895. }
  4896. _face.color = face.color;
  4897. _face.material = material;
  4898. _centroid.copy( _face.centroidModel ).applyProjection( _viewProjectionMatrix );
  4899. _face.z = _centroid.z;
  4900. _renderData.elements.push( _face );
  4901. }
  4902. }
  4903. } else if ( object instanceof THREE.Line ) {
  4904. if ( geometry instanceof THREE.BufferGeometry ) {
  4905. var attributes = geometry.attributes;
  4906. if ( attributes.position !== undefined ) {
  4907. var positions = attributes.position.array;
  4908. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  4909. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  4910. }
  4911. if ( attributes.index !== undefined ) {
  4912. var indices = attributes.index.array;
  4913. for ( var i = 0, l = indices.length; i < l; i += 2 ) {
  4914. renderList.pushLine( indices[ i ], indices[ i + 1 ] );
  4915. }
  4916. } else {
  4917. for ( var i = 0, l = ( positions.length / 3 ) - 1; i < l; i ++ ) {
  4918. renderList.pushLine( i, i + 1 );
  4919. }
  4920. }
  4921. }
  4922. } else if ( geometry instanceof THREE.Geometry ) {
  4923. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4924. vertices = object.geometry.vertices;
  4925. v1 = getNextVertexInPool();
  4926. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4927. // Handle LineStrip and LinePieces
  4928. var step = object.type === THREE.LinePieces ? 2 : 1;
  4929. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  4930. v1 = getNextVertexInPool();
  4931. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4932. if ( ( v + 1 ) % step > 0 ) continue;
  4933. v2 = _vertexPool[ _vertexCount - 2 ];
  4934. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4935. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4936. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4937. // Perform the perspective divide
  4938. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4939. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4940. _line = getNextLineInPool();
  4941. _line.id = object.id;
  4942. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4943. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4944. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4945. _line.material = object.material;
  4946. if ( object.material.vertexColors === THREE.VertexColors ) {
  4947. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  4948. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  4949. }
  4950. _renderData.elements.push( _line );
  4951. }
  4952. }
  4953. }
  4954. }
  4955. }
  4956. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  4957. object = _renderData.sprites[ o ].object;
  4958. _modelMatrix = object.matrixWorld;
  4959. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4960. _vector4.applyMatrix4( _viewProjectionMatrix );
  4961. var invW = 1 / _vector4.w;
  4962. _vector4.z *= invW;
  4963. if ( _vector4.z >= -1 && _vector4.z <= 1 ) {
  4964. _sprite = getNextSpriteInPool();
  4965. _sprite.id = object.id;
  4966. _sprite.x = _vector4.x * invW;
  4967. _sprite.y = _vector4.y * invW;
  4968. _sprite.z = _vector4.z;
  4969. _sprite.object = object;
  4970. _sprite.rotation = object.rotation;
  4971. _sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4972. _sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4973. _sprite.material = object.material;
  4974. _renderData.elements.push( _sprite );
  4975. }
  4976. }
  4977. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4978. return _renderData;
  4979. };
  4980. // Pools
  4981. function getNextObjectInPool() {
  4982. if ( _objectCount === _objectPoolLength ) {
  4983. var object = new THREE.RenderableObject();
  4984. _objectPool.push( object );
  4985. _objectPoolLength ++;
  4986. _objectCount ++;
  4987. return object;
  4988. }
  4989. return _objectPool[ _objectCount ++ ];
  4990. }
  4991. function getNextVertexInPool() {
  4992. if ( _vertexCount === _vertexPoolLength ) {
  4993. var vertex = new THREE.RenderableVertex();
  4994. _vertexPool.push( vertex );
  4995. _vertexPoolLength ++;
  4996. _vertexCount ++;
  4997. return vertex;
  4998. }
  4999. return _vertexPool[ _vertexCount ++ ];
  5000. }
  5001. function getNextFace3InPool() {
  5002. if ( _face3Count === _face3PoolLength ) {
  5003. var face = new THREE.RenderableFace3();
  5004. _face3Pool.push( face );
  5005. _face3PoolLength ++;
  5006. _face3Count ++;
  5007. return face;
  5008. }
  5009. return _face3Pool[ _face3Count ++ ];
  5010. }
  5011. function getNextLineInPool() {
  5012. if ( _lineCount === _linePoolLength ) {
  5013. var line = new THREE.RenderableLine();
  5014. _linePool.push( line );
  5015. _linePoolLength ++;
  5016. _lineCount ++
  5017. return line;
  5018. }
  5019. return _linePool[ _lineCount ++ ];
  5020. }
  5021. function getNextSpriteInPool() {
  5022. if ( _spriteCount === _spritePoolLength ) {
  5023. var sprite = new THREE.RenderableSprite();
  5024. _spritePool.push( sprite );
  5025. _spritePoolLength ++;
  5026. _spriteCount ++
  5027. return sprite;
  5028. }
  5029. return _spritePool[ _spriteCount ++ ];
  5030. }
  5031. //
  5032. function painterSort( a, b ) {
  5033. if ( a.z !== b.z ) {
  5034. return b.z - a.z;
  5035. } else if ( a.id !== b.id ) {
  5036. return a.id - b.id;
  5037. } else {
  5038. return 0;
  5039. }
  5040. }
  5041. function clipLine( s1, s2 ) {
  5042. var alpha1 = 0, alpha2 = 1,
  5043. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  5044. // Z = -1 and Z = +1, respectively.
  5045. bc1near = s1.z + s1.w,
  5046. bc2near = s2.z + s2.w,
  5047. bc1far = - s1.z + s1.w,
  5048. bc2far = - s2.z + s2.w;
  5049. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  5050. // Both vertices lie entirely within all clip planes.
  5051. return true;
  5052. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  5053. // Both vertices lie entirely outside one of the clip planes.
  5054. return false;
  5055. } else {
  5056. // The line segment spans at least one clip plane.
  5057. if ( bc1near < 0 ) {
  5058. // v1 lies outside the near plane, v2 inside
  5059. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  5060. } else if ( bc2near < 0 ) {
  5061. // v2 lies outside the near plane, v1 inside
  5062. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  5063. }
  5064. if ( bc1far < 0 ) {
  5065. // v1 lies outside the far plane, v2 inside
  5066. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  5067. } else if ( bc2far < 0 ) {
  5068. // v2 lies outside the far plane, v2 inside
  5069. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  5070. }
  5071. if ( alpha2 < alpha1 ) {
  5072. // The line segment spans two boundaries, but is outside both of them.
  5073. // (This can't happen when we're only clipping against just near/far but good
  5074. // to leave the check here for future usage if other clip planes are added.)
  5075. return false;
  5076. } else {
  5077. // Update the s1 and s2 vertices to match the clipped line segment.
  5078. s1.lerp( s2, alpha1 );
  5079. s2.lerp( s1, 1 - alpha2 );
  5080. return true;
  5081. }
  5082. }
  5083. }
  5084. };
  5085. /**
  5086. * @author mrdoob / http://mrdoob.com/
  5087. * @author alteredq / http://alteredqualia.com/
  5088. */
  5089. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  5090. this.a = a;
  5091. this.b = b;
  5092. this.c = c;
  5093. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  5094. this.vertexNormals = normal instanceof Array ? normal : [ ];
  5095. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  5096. this.vertexColors = color instanceof Array ? color : [];
  5097. this.vertexTangents = [];
  5098. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5099. this.centroid = new THREE.Vector3();
  5100. };
  5101. THREE.Face3.prototype = {
  5102. constructor: THREE.Face3,
  5103. clone: function () {
  5104. var face = new THREE.Face3( this.a, this.b, this.c );
  5105. face.normal.copy( this.normal );
  5106. face.color.copy( this.color );
  5107. face.centroid.copy( this.centroid );
  5108. face.materialIndex = this.materialIndex;
  5109. var i, il;
  5110. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  5111. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  5112. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  5113. return face;
  5114. }
  5115. };
  5116. /**
  5117. * @author mrdoob / http://mrdoob.com/
  5118. */
  5119. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  5120. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.')
  5121. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  5122. };
  5123. /**
  5124. * @author mrdoob / http://mrdoob.com/
  5125. * @author kile / http://kile.stravaganza.org/
  5126. * @author alteredq / http://alteredqualia.com/
  5127. * @author mikael emtinger / http://gomo.se/
  5128. * @author zz85 / http://www.lab4games.net/zz85/blog
  5129. * @author bhouston / http://exocortex.com
  5130. */
  5131. THREE.Geometry = function () {
  5132. this.id = THREE.GeometryIdCount ++;
  5133. this.uuid = THREE.Math.generateUUID();
  5134. this.name = '';
  5135. this.vertices = [];
  5136. this.colors = []; // one-to-one vertex colors, used in ParticleSystem and Line
  5137. this.faces = [];
  5138. this.faceVertexUvs = [[]];
  5139. this.morphTargets = [];
  5140. this.morphColors = [];
  5141. this.morphNormals = [];
  5142. this.skinWeights = [];
  5143. this.skinIndices = [];
  5144. this.lineDistances = [];
  5145. this.boundingBox = null;
  5146. this.boundingSphere = null;
  5147. this.hasTangents = false;
  5148. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  5149. // update flags
  5150. this.verticesNeedUpdate = false;
  5151. this.elementsNeedUpdate = false;
  5152. this.uvsNeedUpdate = false;
  5153. this.normalsNeedUpdate = false;
  5154. this.tangentsNeedUpdate = false;
  5155. this.colorsNeedUpdate = false;
  5156. this.lineDistancesNeedUpdate = false;
  5157. this.buffersNeedUpdate = false;
  5158. };
  5159. THREE.Geometry.prototype = {
  5160. constructor: THREE.Geometry,
  5161. applyMatrix: function ( matrix ) {
  5162. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5163. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5164. var vertex = this.vertices[ i ];
  5165. vertex.applyMatrix4( matrix );
  5166. }
  5167. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5168. var face = this.faces[ i ];
  5169. face.normal.applyMatrix3( normalMatrix ).normalize();
  5170. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5171. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5172. }
  5173. face.centroid.applyMatrix4( matrix );
  5174. }
  5175. if ( this.boundingBox instanceof THREE.Box3 ) {
  5176. this.computeBoundingBox();
  5177. }
  5178. if ( this.boundingSphere instanceof THREE.Sphere ) {
  5179. this.computeBoundingSphere();
  5180. }
  5181. },
  5182. computeCentroids: function () {
  5183. var f, fl, face;
  5184. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5185. face = this.faces[ f ];
  5186. face.centroid.set( 0, 0, 0 );
  5187. face.centroid.add( this.vertices[ face.a ] );
  5188. face.centroid.add( this.vertices[ face.b ] );
  5189. face.centroid.add( this.vertices[ face.c ] );
  5190. face.centroid.divideScalar( 3 );
  5191. }
  5192. },
  5193. computeFaceNormals: function () {
  5194. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5195. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5196. var face = this.faces[ f ];
  5197. var vA = this.vertices[ face.a ];
  5198. var vB = this.vertices[ face.b ];
  5199. var vC = this.vertices[ face.c ];
  5200. cb.subVectors( vC, vB );
  5201. ab.subVectors( vA, vB );
  5202. cb.cross( ab );
  5203. cb.normalize();
  5204. face.normal.copy( cb );
  5205. }
  5206. },
  5207. computeVertexNormals: function ( areaWeighted ) {
  5208. var v, vl, f, fl, face, vertices;
  5209. vertices = new Array( this.vertices.length );
  5210. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5211. vertices[ v ] = new THREE.Vector3();
  5212. }
  5213. if ( areaWeighted ) {
  5214. // vertex normals weighted by triangle areas
  5215. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5216. var vA, vB, vC, vD;
  5217. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  5218. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  5219. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5220. face = this.faces[ f ];
  5221. vA = this.vertices[ face.a ];
  5222. vB = this.vertices[ face.b ];
  5223. vC = this.vertices[ face.c ];
  5224. cb.subVectors( vC, vB );
  5225. ab.subVectors( vA, vB );
  5226. cb.cross( ab );
  5227. vertices[ face.a ].add( cb );
  5228. vertices[ face.b ].add( cb );
  5229. vertices[ face.c ].add( cb );
  5230. }
  5231. } else {
  5232. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5233. face = this.faces[ f ];
  5234. vertices[ face.a ].add( face.normal );
  5235. vertices[ face.b ].add( face.normal );
  5236. vertices[ face.c ].add( face.normal );
  5237. }
  5238. }
  5239. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5240. vertices[ v ].normalize();
  5241. }
  5242. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5243. face = this.faces[ f ];
  5244. face.vertexNormals[ 0 ] = vertices[ face.a ].clone();
  5245. face.vertexNormals[ 1 ] = vertices[ face.b ].clone();
  5246. face.vertexNormals[ 2 ] = vertices[ face.c ].clone();
  5247. }
  5248. },
  5249. computeMorphNormals: function () {
  5250. var i, il, f, fl, face;
  5251. // save original normals
  5252. // - create temp variables on first access
  5253. // otherwise just copy (for faster repeated calls)
  5254. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5255. face = this.faces[ f ];
  5256. if ( ! face.__originalFaceNormal ) {
  5257. face.__originalFaceNormal = face.normal.clone();
  5258. } else {
  5259. face.__originalFaceNormal.copy( face.normal );
  5260. }
  5261. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5262. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5263. if ( ! face.__originalVertexNormals[ i ] ) {
  5264. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5265. } else {
  5266. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  5267. }
  5268. }
  5269. }
  5270. // use temp geometry to compute face and vertex normals for each morph
  5271. var tmpGeo = new THREE.Geometry();
  5272. tmpGeo.faces = this.faces;
  5273. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  5274. // create on first access
  5275. if ( ! this.morphNormals[ i ] ) {
  5276. this.morphNormals[ i ] = {};
  5277. this.morphNormals[ i ].faceNormals = [];
  5278. this.morphNormals[ i ].vertexNormals = [];
  5279. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  5280. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  5281. var faceNormal, vertexNormals;
  5282. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5283. face = this.faces[ f ];
  5284. faceNormal = new THREE.Vector3();
  5285. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5286. dstNormalsFace.push( faceNormal );
  5287. dstNormalsVertex.push( vertexNormals );
  5288. }
  5289. }
  5290. var morphNormals = this.morphNormals[ i ];
  5291. // set vertices to morph target
  5292. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5293. // compute morph normals
  5294. tmpGeo.computeFaceNormals();
  5295. tmpGeo.computeVertexNormals();
  5296. // store morph normals
  5297. var faceNormal, vertexNormals;
  5298. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5299. face = this.faces[ f ];
  5300. faceNormal = morphNormals.faceNormals[ f ];
  5301. vertexNormals = morphNormals.vertexNormals[ f ];
  5302. faceNormal.copy( face.normal );
  5303. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5304. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5305. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5306. }
  5307. }
  5308. // restore original normals
  5309. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5310. face = this.faces[ f ];
  5311. face.normal = face.__originalFaceNormal;
  5312. face.vertexNormals = face.__originalVertexNormals;
  5313. }
  5314. },
  5315. computeTangents: function () {
  5316. // based on http://www.terathon.com/code/tangent.html
  5317. // tangents go to vertices
  5318. var f, fl, v, vl, i, il, vertexIndex,
  5319. face, uv, vA, vB, vC, uvA, uvB, uvC,
  5320. x1, x2, y1, y2, z1, z2,
  5321. s1, s2, t1, t2, r, t, test,
  5322. tan1 = [], tan2 = [],
  5323. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  5324. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  5325. n = new THREE.Vector3(), w;
  5326. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5327. tan1[ v ] = new THREE.Vector3();
  5328. tan2[ v ] = new THREE.Vector3();
  5329. }
  5330. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  5331. vA = context.vertices[ a ];
  5332. vB = context.vertices[ b ];
  5333. vC = context.vertices[ c ];
  5334. uvA = uv[ ua ];
  5335. uvB = uv[ ub ];
  5336. uvC = uv[ uc ];
  5337. x1 = vB.x - vA.x;
  5338. x2 = vC.x - vA.x;
  5339. y1 = vB.y - vA.y;
  5340. y2 = vC.y - vA.y;
  5341. z1 = vB.z - vA.z;
  5342. z2 = vC.z - vA.z;
  5343. s1 = uvB.x - uvA.x;
  5344. s2 = uvC.x - uvA.x;
  5345. t1 = uvB.y - uvA.y;
  5346. t2 = uvC.y - uvA.y;
  5347. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5348. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  5349. ( t2 * y1 - t1 * y2 ) * r,
  5350. ( t2 * z1 - t1 * z2 ) * r );
  5351. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  5352. ( s1 * y2 - s2 * y1 ) * r,
  5353. ( s1 * z2 - s2 * z1 ) * r );
  5354. tan1[ a ].add( sdir );
  5355. tan1[ b ].add( sdir );
  5356. tan1[ c ].add( sdir );
  5357. tan2[ a ].add( tdir );
  5358. tan2[ b ].add( tdir );
  5359. tan2[ c ].add( tdir );
  5360. }
  5361. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5362. face = this.faces[ f ];
  5363. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  5364. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  5365. }
  5366. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  5367. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5368. face = this.faces[ f ];
  5369. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i++ ) {
  5370. n.copy( face.vertexNormals[ i ] );
  5371. vertexIndex = face[ faceIndex[ i ] ];
  5372. t = tan1[ vertexIndex ];
  5373. // Gram-Schmidt orthogonalize
  5374. tmp.copy( t );
  5375. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5376. // Calculate handedness
  5377. tmp2.crossVectors( face.vertexNormals[ i ], t );
  5378. test = tmp2.dot( tan2[ vertexIndex ] );
  5379. w = (test < 0.0) ? -1.0 : 1.0;
  5380. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  5381. }
  5382. }
  5383. this.hasTangents = true;
  5384. },
  5385. computeLineDistances: function ( ) {
  5386. var d = 0;
  5387. var vertices = this.vertices;
  5388. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5389. if ( i > 0 ) {
  5390. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  5391. }
  5392. this.lineDistances[ i ] = d;
  5393. }
  5394. },
  5395. computeBoundingBox: function () {
  5396. if ( this.boundingBox === null ) {
  5397. this.boundingBox = new THREE.Box3();
  5398. }
  5399. this.boundingBox.setFromPoints( this.vertices );
  5400. },
  5401. computeBoundingSphere: function () {
  5402. if ( this.boundingSphere === null ) {
  5403. this.boundingSphere = new THREE.Sphere();
  5404. }
  5405. this.boundingSphere.setFromPoints( this.vertices );
  5406. },
  5407. /*
  5408. * Checks for duplicate vertices with hashmap.
  5409. * Duplicated vertices are removed
  5410. * and faces' vertices are updated.
  5411. */
  5412. mergeVertices: function () {
  5413. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  5414. var unique = [], changes = [];
  5415. var v, key;
  5416. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  5417. var precision = Math.pow( 10, precisionPoints );
  5418. var i,il, face;
  5419. var indices, k, j, jl, u;
  5420. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  5421. v = this.vertices[ i ];
  5422. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  5423. if ( verticesMap[ key ] === undefined ) {
  5424. verticesMap[ key ] = i;
  5425. unique.push( this.vertices[ i ] );
  5426. changes[ i ] = unique.length - 1;
  5427. } else {
  5428. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  5429. changes[ i ] = changes[ verticesMap[ key ] ];
  5430. }
  5431. };
  5432. // if faces are completely degenerate after merging vertices, we
  5433. // have to remove them from the geometry.
  5434. var faceIndicesToRemove = [];
  5435. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  5436. face = this.faces[ i ];
  5437. face.a = changes[ face.a ];
  5438. face.b = changes[ face.b ];
  5439. face.c = changes[ face.c ];
  5440. indices = [ face.a, face.b, face.c ];
  5441. var dupIndex = -1;
  5442. // if any duplicate vertices are found in a Face3
  5443. // we have to remove the face as nothing can be saved
  5444. for ( var n = 0; n < 3; n ++ ) {
  5445. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  5446. dupIndex = n;
  5447. faceIndicesToRemove.push( i );
  5448. break;
  5449. }
  5450. }
  5451. }
  5452. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  5453. var idx = faceIndicesToRemove[ i ];
  5454. this.faces.splice( idx, 1 );
  5455. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5456. this.faceVertexUvs[ j ].splice( idx, 1 );
  5457. }
  5458. }
  5459. // Use unique set of vertices
  5460. var diff = this.vertices.length - unique.length;
  5461. this.vertices = unique;
  5462. return diff;
  5463. },
  5464. clone: function () {
  5465. var geometry = new THREE.Geometry();
  5466. var vertices = this.vertices;
  5467. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5468. geometry.vertices.push( vertices[ i ].clone() );
  5469. }
  5470. var faces = this.faces;
  5471. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  5472. geometry.faces.push( faces[ i ].clone() );
  5473. }
  5474. var uvs = this.faceVertexUvs[ 0 ];
  5475. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  5476. var uv = uvs[ i ], uvCopy = [];
  5477. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5478. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  5479. }
  5480. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  5481. }
  5482. return geometry;
  5483. },
  5484. dispose: function () {
  5485. this.dispatchEvent( { type: 'dispose' } );
  5486. }
  5487. };
  5488. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  5489. THREE.GeometryIdCount = 0;
  5490. /**
  5491. * @author mrdoob / http://mrdoob.com/
  5492. */
  5493. THREE.Geometry2 = function ( size ) {
  5494. this.id = THREE.GeometryIdCount ++;
  5495. this.uuid = THREE.Math.generateUUID();
  5496. this.name = '';
  5497. this.vertices = size !== undefined ? new Float32Array( size * 3 ) : [];
  5498. this.normals = size !== undefined ? new Float32Array( size * 3 ) : [];
  5499. this.uvs = size !== undefined ? new Float32Array( size * 2 ) : [];
  5500. this.boundingBox = null;
  5501. this.boundingSphere = null;
  5502. };
  5503. THREE.Geometry2.prototype = {
  5504. constructor: THREE.Geometry2,
  5505. applyMatrix: function ( matrix ) {
  5506. matrix.multiplyVector3Array( this.vertices );
  5507. },
  5508. computeBoundingSphere: function () {
  5509. var box = new THREE.Box3();
  5510. var vector = new THREE.Vector3();
  5511. return function () {
  5512. if ( this.boundingSphere === null ) {
  5513. this.boundingSphere = new THREE.Sphere();
  5514. }
  5515. box.makeEmpty();
  5516. var vertices = this.vertices;
  5517. var center = this.boundingSphere.center;
  5518. for ( var i = 0, il = vertices.length; i < il; i += 3 ) {
  5519. vector.set( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] );
  5520. box.addPoint( vector );
  5521. }
  5522. box.center( center );
  5523. var maxRadiusSq = 0;
  5524. for ( var i = 0, il = vertices.length; i < il; i += 3 ) {
  5525. vector.set( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] );
  5526. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5527. }
  5528. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5529. }
  5530. }(),
  5531. dispose: function () {
  5532. this.dispatchEvent( { type: 'dispose' } );
  5533. }
  5534. };
  5535. THREE.EventDispatcher.prototype.apply( THREE.Geometry2.prototype );
  5536. /**
  5537. * @author alteredq / http://alteredqualia.com/
  5538. */
  5539. THREE.BufferGeometry = function () {
  5540. this.id = THREE.GeometryIdCount ++;
  5541. this.uuid = THREE.Math.generateUUID();
  5542. this.name = '';
  5543. // attributes
  5544. this.attributes = {};
  5545. // attributes typed arrays are kept only if dynamic flag is set
  5546. this.dynamic = true;
  5547. // offsets for chunks when using indexed elements
  5548. this.offsets = [];
  5549. // boundings
  5550. this.boundingBox = null;
  5551. this.boundingSphere = null;
  5552. this.hasTangents = false;
  5553. };
  5554. THREE.BufferGeometry.prototype = {
  5555. constructor: THREE.BufferGeometry,
  5556. addAttribute: function ( name, type, numItems, itemSize ) {
  5557. this.attributes[ name ] = {
  5558. itemSize: itemSize,
  5559. array: new type( numItems * itemSize )
  5560. };
  5561. },
  5562. applyMatrix: function ( matrix ) {
  5563. var positionArray;
  5564. var normalArray;
  5565. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  5566. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  5567. if ( positionArray !== undefined ) {
  5568. matrix.multiplyVector3Array( positionArray );
  5569. this.verticesNeedUpdate = true;
  5570. }
  5571. if ( normalArray !== undefined ) {
  5572. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5573. normalMatrix.multiplyVector3Array( normalArray );
  5574. this.normalizeNormals();
  5575. this.normalsNeedUpdate = true;
  5576. }
  5577. },
  5578. computeBoundingBox: function () {
  5579. if ( this.boundingBox === null ) {
  5580. this.boundingBox = new THREE.Box3();
  5581. }
  5582. var positions = this.attributes[ "position" ].array;
  5583. if ( positions ) {
  5584. var bb = this.boundingBox;
  5585. var x, y, z;
  5586. if( positions.length >= 3 ) {
  5587. bb.min.x = bb.max.x = positions[ 0 ];
  5588. bb.min.y = bb.max.y = positions[ 1 ];
  5589. bb.min.z = bb.max.z = positions[ 2 ];
  5590. }
  5591. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5592. x = positions[ i ];
  5593. y = positions[ i + 1 ];
  5594. z = positions[ i + 2 ];
  5595. // bounding box
  5596. if ( x < bb.min.x ) {
  5597. bb.min.x = x;
  5598. } else if ( x > bb.max.x ) {
  5599. bb.max.x = x;
  5600. }
  5601. if ( y < bb.min.y ) {
  5602. bb.min.y = y;
  5603. } else if ( y > bb.max.y ) {
  5604. bb.max.y = y;
  5605. }
  5606. if ( z < bb.min.z ) {
  5607. bb.min.z = z;
  5608. } else if ( z > bb.max.z ) {
  5609. bb.max.z = z;
  5610. }
  5611. }
  5612. }
  5613. if ( positions === undefined || positions.length === 0 ) {
  5614. this.boundingBox.min.set( 0, 0, 0 );
  5615. this.boundingBox.max.set( 0, 0, 0 );
  5616. }
  5617. },
  5618. computeBoundingSphere: function () {
  5619. var box = new THREE.Box3();
  5620. var vector = new THREE.Vector3();
  5621. return function () {
  5622. if ( this.boundingSphere === null ) {
  5623. this.boundingSphere = new THREE.Sphere();
  5624. }
  5625. var positions = this.attributes[ "position" ].array;
  5626. if ( positions ) {
  5627. box.makeEmpty();
  5628. var center = this.boundingSphere.center;
  5629. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5630. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5631. box.addPoint( vector );
  5632. }
  5633. box.center( center );
  5634. var maxRadiusSq = 0;
  5635. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5636. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5637. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5638. }
  5639. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5640. }
  5641. }
  5642. }(),
  5643. computeVertexNormals: function () {
  5644. if ( this.attributes[ "position" ] ) {
  5645. var i, il;
  5646. var j, jl;
  5647. var nVertexElements = this.attributes[ "position" ].array.length;
  5648. if ( this.attributes[ "normal" ] === undefined ) {
  5649. this.attributes[ "normal" ] = {
  5650. itemSize: 3,
  5651. array: new Float32Array( nVertexElements )
  5652. };
  5653. } else {
  5654. // reset existing normals to zero
  5655. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5656. this.attributes[ "normal" ].array[ i ] = 0;
  5657. }
  5658. }
  5659. var positions = this.attributes[ "position" ].array;
  5660. var normals = this.attributes[ "normal" ].array;
  5661. var vA, vB, vC, x, y, z,
  5662. pA = new THREE.Vector3(),
  5663. pB = new THREE.Vector3(),
  5664. pC = new THREE.Vector3(),
  5665. cb = new THREE.Vector3(),
  5666. ab = new THREE.Vector3();
  5667. // indexed elements
  5668. if ( this.attributes[ "index" ] ) {
  5669. var indices = this.attributes[ "index" ].array;
  5670. var offsets = this.offsets;
  5671. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5672. var start = offsets[ j ].start;
  5673. var count = offsets[ j ].count;
  5674. var index = offsets[ j ].index;
  5675. for ( i = start, il = start + count; i < il; i += 3 ) {
  5676. vA = index + indices[ i ];
  5677. vB = index + indices[ i + 1 ];
  5678. vC = index + indices[ i + 2 ];
  5679. x = positions[ vA * 3 ];
  5680. y = positions[ vA * 3 + 1 ];
  5681. z = positions[ vA * 3 + 2 ];
  5682. pA.set( x, y, z );
  5683. x = positions[ vB * 3 ];
  5684. y = positions[ vB * 3 + 1 ];
  5685. z = positions[ vB * 3 + 2 ];
  5686. pB.set( x, y, z );
  5687. x = positions[ vC * 3 ];
  5688. y = positions[ vC * 3 + 1 ];
  5689. z = positions[ vC * 3 + 2 ];
  5690. pC.set( x, y, z );
  5691. cb.subVectors( pC, pB );
  5692. ab.subVectors( pA, pB );
  5693. cb.cross( ab );
  5694. normals[ vA * 3 ] += cb.x;
  5695. normals[ vA * 3 + 1 ] += cb.y;
  5696. normals[ vA * 3 + 2 ] += cb.z;
  5697. normals[ vB * 3 ] += cb.x;
  5698. normals[ vB * 3 + 1 ] += cb.y;
  5699. normals[ vB * 3 + 2 ] += cb.z;
  5700. normals[ vC * 3 ] += cb.x;
  5701. normals[ vC * 3 + 1 ] += cb.y;
  5702. normals[ vC * 3 + 2 ] += cb.z;
  5703. }
  5704. }
  5705. // non-indexed elements (unconnected triangle soup)
  5706. } else {
  5707. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5708. x = positions[ i ];
  5709. y = positions[ i + 1 ];
  5710. z = positions[ i + 2 ];
  5711. pA.set( x, y, z );
  5712. x = positions[ i + 3 ];
  5713. y = positions[ i + 4 ];
  5714. z = positions[ i + 5 ];
  5715. pB.set( x, y, z );
  5716. x = positions[ i + 6 ];
  5717. y = positions[ i + 7 ];
  5718. z = positions[ i + 8 ];
  5719. pC.set( x, y, z );
  5720. cb.subVectors( pC, pB );
  5721. ab.subVectors( pA, pB );
  5722. cb.cross( ab );
  5723. normals[ i ] = cb.x;
  5724. normals[ i + 1 ] = cb.y;
  5725. normals[ i + 2 ] = cb.z;
  5726. normals[ i + 3 ] = cb.x;
  5727. normals[ i + 4 ] = cb.y;
  5728. normals[ i + 5 ] = cb.z;
  5729. normals[ i + 6 ] = cb.x;
  5730. normals[ i + 7 ] = cb.y;
  5731. normals[ i + 8 ] = cb.z;
  5732. }
  5733. }
  5734. this.normalizeNormals();
  5735. this.normalsNeedUpdate = true;
  5736. }
  5737. },
  5738. normalizeNormals: function () {
  5739. var normals = this.attributes[ "normal" ].array;
  5740. var x, y, z, n;
  5741. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5742. x = normals[ i ];
  5743. y = normals[ i + 1 ];
  5744. z = normals[ i + 2 ];
  5745. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5746. normals[ i ] *= n;
  5747. normals[ i + 1 ] *= n;
  5748. normals[ i + 2 ] *= n;
  5749. }
  5750. },
  5751. computeTangents: function () {
  5752. // based on http://www.terathon.com/code/tangent.html
  5753. // (per vertex tangents)
  5754. if ( this.attributes[ "index" ] === undefined ||
  5755. this.attributes[ "position" ] === undefined ||
  5756. this.attributes[ "normal" ] === undefined ||
  5757. this.attributes[ "uv" ] === undefined ) {
  5758. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5759. return;
  5760. }
  5761. var indices = this.attributes[ "index" ].array;
  5762. var positions = this.attributes[ "position" ].array;
  5763. var normals = this.attributes[ "normal" ].array;
  5764. var uvs = this.attributes[ "uv" ].array;
  5765. var nVertices = positions.length / 3;
  5766. if ( this.attributes[ "tangent" ] === undefined ) {
  5767. var nTangentElements = 4 * nVertices;
  5768. this.attributes[ "tangent" ] = {
  5769. itemSize: 4,
  5770. array: new Float32Array( nTangentElements )
  5771. };
  5772. }
  5773. var tangents = this.attributes[ "tangent" ].array;
  5774. var tan1 = [], tan2 = [];
  5775. for ( var k = 0; k < nVertices; k ++ ) {
  5776. tan1[ k ] = new THREE.Vector3();
  5777. tan2[ k ] = new THREE.Vector3();
  5778. }
  5779. var xA, yA, zA,
  5780. xB, yB, zB,
  5781. xC, yC, zC,
  5782. uA, vA,
  5783. uB, vB,
  5784. uC, vC,
  5785. x1, x2, y1, y2, z1, z2,
  5786. s1, s2, t1, t2, r;
  5787. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5788. function handleTriangle( a, b, c ) {
  5789. xA = positions[ a * 3 ];
  5790. yA = positions[ a * 3 + 1 ];
  5791. zA = positions[ a * 3 + 2 ];
  5792. xB = positions[ b * 3 ];
  5793. yB = positions[ b * 3 + 1 ];
  5794. zB = positions[ b * 3 + 2 ];
  5795. xC = positions[ c * 3 ];
  5796. yC = positions[ c * 3 + 1 ];
  5797. zC = positions[ c * 3 + 2 ];
  5798. uA = uvs[ a * 2 ];
  5799. vA = uvs[ a * 2 + 1 ];
  5800. uB = uvs[ b * 2 ];
  5801. vB = uvs[ b * 2 + 1 ];
  5802. uC = uvs[ c * 2 ];
  5803. vC = uvs[ c * 2 + 1 ];
  5804. x1 = xB - xA;
  5805. x2 = xC - xA;
  5806. y1 = yB - yA;
  5807. y2 = yC - yA;
  5808. z1 = zB - zA;
  5809. z2 = zC - zA;
  5810. s1 = uB - uA;
  5811. s2 = uC - uA;
  5812. t1 = vB - vA;
  5813. t2 = vC - vA;
  5814. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5815. sdir.set(
  5816. ( t2 * x1 - t1 * x2 ) * r,
  5817. ( t2 * y1 - t1 * y2 ) * r,
  5818. ( t2 * z1 - t1 * z2 ) * r
  5819. );
  5820. tdir.set(
  5821. ( s1 * x2 - s2 * x1 ) * r,
  5822. ( s1 * y2 - s2 * y1 ) * r,
  5823. ( s1 * z2 - s2 * z1 ) * r
  5824. );
  5825. tan1[ a ].add( sdir );
  5826. tan1[ b ].add( sdir );
  5827. tan1[ c ].add( sdir );
  5828. tan2[ a ].add( tdir );
  5829. tan2[ b ].add( tdir );
  5830. tan2[ c ].add( tdir );
  5831. }
  5832. var i, il;
  5833. var j, jl;
  5834. var iA, iB, iC;
  5835. var offsets = this.offsets;
  5836. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5837. var start = offsets[ j ].start;
  5838. var count = offsets[ j ].count;
  5839. var index = offsets[ j ].index;
  5840. for ( i = start, il = start + count; i < il; i += 3 ) {
  5841. iA = index + indices[ i ];
  5842. iB = index + indices[ i + 1 ];
  5843. iC = index + indices[ i + 2 ];
  5844. handleTriangle( iA, iB, iC );
  5845. }
  5846. }
  5847. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5848. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5849. var w, t, test;
  5850. function handleVertex( v ) {
  5851. n.x = normals[ v * 3 ];
  5852. n.y = normals[ v * 3 + 1 ];
  5853. n.z = normals[ v * 3 + 2 ];
  5854. n2.copy( n );
  5855. t = tan1[ v ];
  5856. // Gram-Schmidt orthogonalize
  5857. tmp.copy( t );
  5858. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5859. // Calculate handedness
  5860. tmp2.crossVectors( n2, t );
  5861. test = tmp2.dot( tan2[ v ] );
  5862. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5863. tangents[ v * 4 ] = tmp.x;
  5864. tangents[ v * 4 + 1 ] = tmp.y;
  5865. tangents[ v * 4 + 2 ] = tmp.z;
  5866. tangents[ v * 4 + 3 ] = w;
  5867. }
  5868. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5869. var start = offsets[ j ].start;
  5870. var count = offsets[ j ].count;
  5871. var index = offsets[ j ].index;
  5872. for ( i = start, il = start + count; i < il; i += 3 ) {
  5873. iA = index + indices[ i ];
  5874. iB = index + indices[ i + 1 ];
  5875. iC = index + indices[ i + 2 ];
  5876. handleVertex( iA );
  5877. handleVertex( iB );
  5878. handleVertex( iC );
  5879. }
  5880. }
  5881. this.hasTangents = true;
  5882. this.tangentsNeedUpdate = true;
  5883. },
  5884. clone: function () {
  5885. var geometry = new THREE.BufferGeometry();
  5886. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5887. for ( var attr in this.attributes ) {
  5888. var sourceAttr = this.attributes[ attr ];
  5889. var sourceArray = sourceAttr.array;
  5890. var attribute = {
  5891. itemSize: sourceAttr.itemSize,
  5892. array: null
  5893. };
  5894. for ( var i = 0, il = types.length; i < il; i ++ ) {
  5895. var type = types[ i ];
  5896. if ( sourceArray instanceof type ) {
  5897. attribute.array = new type( sourceArray );
  5898. break;
  5899. }
  5900. }
  5901. geometry.attributes[ attr ] = attribute;
  5902. }
  5903. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  5904. var offset = this.offsets[ i ];
  5905. geometry.offsets.push( {
  5906. start: offset.start,
  5907. index: offset.index,
  5908. count: offset.count
  5909. } );
  5910. }
  5911. return geometry;
  5912. },
  5913. dispose: function () {
  5914. this.dispatchEvent( { type: 'dispose' } );
  5915. }
  5916. };
  5917. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  5918. /**
  5919. * @author mrdoob / http://mrdoob.com/
  5920. * @author mikael emtinger / http://gomo.se/
  5921. * @author WestLangley / http://github.com/WestLangley
  5922. */
  5923. THREE.Camera = function () {
  5924. THREE.Object3D.call( this );
  5925. this.matrixWorldInverse = new THREE.Matrix4();
  5926. this.projectionMatrix = new THREE.Matrix4();
  5927. };
  5928. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5929. THREE.Camera.prototype.lookAt = function () {
  5930. // This routine does not support cameras with rotated and/or translated parent(s)
  5931. var m1 = new THREE.Matrix4();
  5932. return function ( vector ) {
  5933. m1.lookAt( this.position, vector, this.up );
  5934. this.quaternion.setFromRotationMatrix( m1 );
  5935. };
  5936. }();
  5937. THREE.Camera.prototype.clone = function (camera) {
  5938. if ( camera === undefined ) camera = new THREE.Camera();
  5939. THREE.Object3D.prototype.clone.call( this, camera );
  5940. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  5941. camera.projectionMatrix.copy( this.projectionMatrix );
  5942. return camera;
  5943. };
  5944. /**
  5945. * @author alteredq / http://alteredqualia.com/
  5946. */
  5947. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5948. THREE.Camera.call( this );
  5949. this.left = left;
  5950. this.right = right;
  5951. this.top = top;
  5952. this.bottom = bottom;
  5953. this.near = ( near !== undefined ) ? near : 0.1;
  5954. this.far = ( far !== undefined ) ? far : 2000;
  5955. this.updateProjectionMatrix();
  5956. };
  5957. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5958. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5959. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5960. };
  5961. THREE.OrthographicCamera.prototype.clone = function () {
  5962. var camera = new THREE.OrthographicCamera();
  5963. THREE.Camera.prototype.clone.call( this, camera );
  5964. camera.left = this.left;
  5965. camera.right = this.right;
  5966. camera.top = this.top;
  5967. camera.bottom = this.bottom;
  5968. camera.near = this.near;
  5969. camera.far = this.far;
  5970. return camera;
  5971. };
  5972. /**
  5973. * @author mrdoob / http://mrdoob.com/
  5974. * @author greggman / http://games.greggman.com/
  5975. * @author zz85 / http://www.lab4games.net/zz85/blog
  5976. */
  5977. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5978. THREE.Camera.call( this );
  5979. this.fov = fov !== undefined ? fov : 50;
  5980. this.aspect = aspect !== undefined ? aspect : 1;
  5981. this.near = near !== undefined ? near : 0.1;
  5982. this.far = far !== undefined ? far : 2000;
  5983. this.updateProjectionMatrix();
  5984. };
  5985. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5986. /**
  5987. * Uses Focal Length (in mm) to estimate and set FOV
  5988. * 35mm (fullframe) camera is used if frame size is not specified;
  5989. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5990. */
  5991. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5992. if ( frameHeight === undefined ) frameHeight = 24;
  5993. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5994. this.updateProjectionMatrix();
  5995. }
  5996. /**
  5997. * Sets an offset in a larger frustum. This is useful for multi-window or
  5998. * multi-monitor/multi-machine setups.
  5999. *
  6000. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6001. * the monitors are in grid like this
  6002. *
  6003. * +---+---+---+
  6004. * | A | B | C |
  6005. * +---+---+---+
  6006. * | D | E | F |
  6007. * +---+---+---+
  6008. *
  6009. * then for each monitor you would call it like this
  6010. *
  6011. * var w = 1920;
  6012. * var h = 1080;
  6013. * var fullWidth = w * 3;
  6014. * var fullHeight = h * 2;
  6015. *
  6016. * --A--
  6017. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6018. * --B--
  6019. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6020. * --C--
  6021. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6022. * --D--
  6023. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6024. * --E--
  6025. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6026. * --F--
  6027. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6028. *
  6029. * Note there is no reason monitors have to be the same size or in a grid.
  6030. */
  6031. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  6032. this.fullWidth = fullWidth;
  6033. this.fullHeight = fullHeight;
  6034. this.x = x;
  6035. this.y = y;
  6036. this.width = width;
  6037. this.height = height;
  6038. this.updateProjectionMatrix();
  6039. };
  6040. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  6041. if ( this.fullWidth ) {
  6042. var aspect = this.fullWidth / this.fullHeight;
  6043. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  6044. var bottom = -top;
  6045. var left = aspect * bottom;
  6046. var right = aspect * top;
  6047. var width = Math.abs( right - left );
  6048. var height = Math.abs( top - bottom );
  6049. this.projectionMatrix.makeFrustum(
  6050. left + this.x * width / this.fullWidth,
  6051. left + ( this.x + this.width ) * width / this.fullWidth,
  6052. top - ( this.y + this.height ) * height / this.fullHeight,
  6053. top - this.y * height / this.fullHeight,
  6054. this.near,
  6055. this.far
  6056. );
  6057. } else {
  6058. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  6059. }
  6060. };
  6061. THREE.PerspectiveCamera.prototype.clone = function () {
  6062. var camera = new THREE.PerspectiveCamera();
  6063. THREE.Camera.prototype.clone.call( this, camera );
  6064. camera.fov = this.fov;
  6065. camera.aspect = this.aspect;
  6066. camera.near = this.near;
  6067. camera.far = this.far;
  6068. return camera;
  6069. };
  6070. /**
  6071. * @author mrdoob / http://mrdoob.com/
  6072. * @author alteredq / http://alteredqualia.com/
  6073. */
  6074. THREE.Light = function ( color ) {
  6075. THREE.Object3D.call( this );
  6076. this.color = new THREE.Color( color );
  6077. };
  6078. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  6079. THREE.Light.prototype.clone = function ( light ) {
  6080. if ( light === undefined ) light = new THREE.Light();
  6081. THREE.Object3D.prototype.clone.call( this, light );
  6082. light.color.copy( this.color );
  6083. return light;
  6084. };
  6085. /**
  6086. * @author mrdoob / http://mrdoob.com/
  6087. */
  6088. THREE.AmbientLight = function ( color ) {
  6089. THREE.Light.call( this, color );
  6090. };
  6091. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  6092. THREE.AmbientLight.prototype.clone = function () {
  6093. var light = new THREE.AmbientLight();
  6094. THREE.Light.prototype.clone.call( this, light );
  6095. return light;
  6096. };
  6097. /**
  6098. * @author MPanknin / http://www.redplant.de/
  6099. * @author alteredq / http://alteredqualia.com/
  6100. */
  6101. THREE.AreaLight = function ( color, intensity ) {
  6102. THREE.Light.call( this, color );
  6103. this.normal = new THREE.Vector3( 0, -1, 0 );
  6104. this.right = new THREE.Vector3( 1, 0, 0 );
  6105. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6106. this.width = 1.0;
  6107. this.height = 1.0;
  6108. this.constantAttenuation = 1.5;
  6109. this.linearAttenuation = 0.5;
  6110. this.quadraticAttenuation = 0.1;
  6111. };
  6112. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  6113. /**
  6114. * @author mrdoob / http://mrdoob.com/
  6115. * @author alteredq / http://alteredqualia.com/
  6116. */
  6117. THREE.DirectionalLight = function ( color, intensity ) {
  6118. THREE.Light.call( this, color );
  6119. this.position.set( 0, 1, 0 );
  6120. this.target = new THREE.Object3D();
  6121. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6122. this.castShadow = false;
  6123. this.onlyShadow = false;
  6124. //
  6125. this.shadowCameraNear = 50;
  6126. this.shadowCameraFar = 5000;
  6127. this.shadowCameraLeft = -500;
  6128. this.shadowCameraRight = 500;
  6129. this.shadowCameraTop = 500;
  6130. this.shadowCameraBottom = -500;
  6131. this.shadowCameraVisible = false;
  6132. this.shadowBias = 0;
  6133. this.shadowDarkness = 0.5;
  6134. this.shadowMapWidth = 512;
  6135. this.shadowMapHeight = 512;
  6136. //
  6137. this.shadowCascade = false;
  6138. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  6139. this.shadowCascadeCount = 2;
  6140. this.shadowCascadeBias = [ 0, 0, 0 ];
  6141. this.shadowCascadeWidth = [ 512, 512, 512 ];
  6142. this.shadowCascadeHeight = [ 512, 512, 512 ];
  6143. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  6144. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  6145. this.shadowCascadeArray = [];
  6146. //
  6147. this.shadowMap = null;
  6148. this.shadowMapSize = null;
  6149. this.shadowCamera = null;
  6150. this.shadowMatrix = null;
  6151. };
  6152. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  6153. THREE.DirectionalLight.prototype.clone = function () {
  6154. var light = new THREE.DirectionalLight();
  6155. THREE.Light.prototype.clone.call( this, light );
  6156. light.target = this.target.clone();
  6157. light.intensity = this.intensity;
  6158. light.castShadow = this.castShadow;
  6159. light.onlyShadow = this.onlyShadow;
  6160. return light;
  6161. };
  6162. /**
  6163. * @author alteredq / http://alteredqualia.com/
  6164. */
  6165. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  6166. THREE.Light.call( this, skyColor );
  6167. this.position.set( 0, 100, 0 );
  6168. this.groundColor = new THREE.Color( groundColor );
  6169. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6170. };
  6171. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  6172. THREE.HemisphereLight.prototype.clone = function () {
  6173. var light = new THREE.HemisphereLight();
  6174. THREE.Light.prototype.clone.call( this, light );
  6175. light.groundColor.copy( this.groundColor );
  6176. light.intensity = this.intensity;
  6177. return light;
  6178. };
  6179. /**
  6180. * @author mrdoob / http://mrdoob.com/
  6181. */
  6182. THREE.PointLight = function ( color, intensity, distance ) {
  6183. THREE.Light.call( this, color );
  6184. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6185. this.distance = ( distance !== undefined ) ? distance : 0;
  6186. };
  6187. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  6188. THREE.PointLight.prototype.clone = function () {
  6189. var light = new THREE.PointLight();
  6190. THREE.Light.prototype.clone.call( this, light );
  6191. light.intensity = this.intensity;
  6192. light.distance = this.distance;
  6193. return light;
  6194. };
  6195. /**
  6196. * @author alteredq / http://alteredqualia.com/
  6197. */
  6198. THREE.SpotLight = function ( color, intensity, distance, angle, exponent ) {
  6199. THREE.Light.call( this, color );
  6200. this.position.set( 0, 1, 0 );
  6201. this.target = new THREE.Object3D();
  6202. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6203. this.distance = ( distance !== undefined ) ? distance : 0;
  6204. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  6205. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  6206. this.castShadow = false;
  6207. this.onlyShadow = false;
  6208. //
  6209. this.shadowCameraNear = 50;
  6210. this.shadowCameraFar = 5000;
  6211. this.shadowCameraFov = 50;
  6212. this.shadowCameraVisible = false;
  6213. this.shadowBias = 0;
  6214. this.shadowDarkness = 0.5;
  6215. this.shadowMapWidth = 512;
  6216. this.shadowMapHeight = 512;
  6217. //
  6218. this.shadowMap = null;
  6219. this.shadowMapSize = null;
  6220. this.shadowCamera = null;
  6221. this.shadowMatrix = null;
  6222. };
  6223. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  6224. THREE.SpotLight.prototype.clone = function () {
  6225. var light = new THREE.SpotLight();
  6226. THREE.Light.prototype.clone.call( this, light );
  6227. light.target = this.target.clone();
  6228. light.intensity = this.intensity;
  6229. light.distance = this.distance;
  6230. light.angle = this.angle;
  6231. light.exponent = this.exponent;
  6232. light.castShadow = this.castShadow;
  6233. light.onlyShadow = this.onlyShadow;
  6234. return light;
  6235. };
  6236. /**
  6237. * @author alteredq / http://alteredqualia.com/
  6238. */
  6239. THREE.Loader = function ( showStatus ) {
  6240. this.showStatus = showStatus;
  6241. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6242. this.onLoadStart = function () {};
  6243. this.onLoadProgress = function () {};
  6244. this.onLoadComplete = function () {};
  6245. };
  6246. THREE.Loader.prototype = {
  6247. constructor: THREE.Loader,
  6248. crossOrigin: undefined,
  6249. addStatusElement: function () {
  6250. var e = document.createElement( "div" );
  6251. e.style.position = "absolute";
  6252. e.style.right = "0px";
  6253. e.style.top = "0px";
  6254. e.style.fontSize = "0.8em";
  6255. e.style.textAlign = "left";
  6256. e.style.background = "rgba(0,0,0,0.25)";
  6257. e.style.color = "#fff";
  6258. e.style.width = "120px";
  6259. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  6260. e.style.zIndex = 1000;
  6261. e.innerHTML = "Loading ...";
  6262. return e;
  6263. },
  6264. updateProgress: function ( progress ) {
  6265. var message = "Loaded ";
  6266. if ( progress.total ) {
  6267. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  6268. } else {
  6269. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  6270. }
  6271. this.statusDomElement.innerHTML = message;
  6272. },
  6273. extractUrlBase: function ( url ) {
  6274. var parts = url.split( '/' );
  6275. if ( parts.length === 1 ) return './';
  6276. parts.pop();
  6277. return parts.join( '/' ) + '/';
  6278. },
  6279. initMaterials: function ( materials, texturePath ) {
  6280. var array = [];
  6281. for ( var i = 0; i < materials.length; ++ i ) {
  6282. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  6283. }
  6284. return array;
  6285. },
  6286. needsTangents: function ( materials ) {
  6287. for( var i = 0, il = materials.length; i < il; i ++ ) {
  6288. var m = materials[ i ];
  6289. if ( m instanceof THREE.ShaderMaterial ) return true;
  6290. }
  6291. return false;
  6292. },
  6293. createMaterial: function ( m, texturePath ) {
  6294. var _this = this;
  6295. function is_pow2( n ) {
  6296. var l = Math.log( n ) / Math.LN2;
  6297. return Math.floor( l ) == l;
  6298. }
  6299. function nearest_pow2( n ) {
  6300. var l = Math.log( n ) / Math.LN2;
  6301. return Math.pow( 2, Math.round( l ) );
  6302. }
  6303. function load_image( where, url ) {
  6304. var image = new Image();
  6305. image.onload = function () {
  6306. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  6307. var width = nearest_pow2( this.width );
  6308. var height = nearest_pow2( this.height );
  6309. where.image.width = width;
  6310. where.image.height = height;
  6311. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  6312. } else {
  6313. where.image = this;
  6314. }
  6315. where.needsUpdate = true;
  6316. };
  6317. if ( _this.crossOrigin !== undefined ) image.crossOrigin = _this.crossOrigin;
  6318. image.src = url;
  6319. }
  6320. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  6321. var isCompressed = /\.dds$/i.test( sourceFile );
  6322. var fullPath = texturePath + sourceFile;
  6323. if ( isCompressed ) {
  6324. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  6325. where[ name ] = texture;
  6326. } else {
  6327. var texture = document.createElement( 'canvas' );
  6328. where[ name ] = new THREE.Texture( texture );
  6329. }
  6330. where[ name ].sourceFile = sourceFile;
  6331. if( repeat ) {
  6332. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6333. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  6334. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  6335. }
  6336. if ( offset ) {
  6337. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  6338. }
  6339. if ( wrap ) {
  6340. var wrapMap = {
  6341. "repeat": THREE.RepeatWrapping,
  6342. "mirror": THREE.MirroredRepeatWrapping
  6343. }
  6344. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  6345. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  6346. }
  6347. if ( anisotropy ) {
  6348. where[ name ].anisotropy = anisotropy;
  6349. }
  6350. if ( ! isCompressed ) {
  6351. load_image( where[ name ], fullPath );
  6352. }
  6353. }
  6354. function rgb2hex( rgb ) {
  6355. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6356. }
  6357. // defaults
  6358. var mtype = "MeshLambertMaterial";
  6359. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  6360. // parameters from model file
  6361. if ( m.shading ) {
  6362. var shading = m.shading.toLowerCase();
  6363. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  6364. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  6365. }
  6366. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6367. mpars.blending = THREE[ m.blending ];
  6368. }
  6369. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  6370. mpars.transparent = m.transparent;
  6371. }
  6372. if ( m.depthTest !== undefined ) {
  6373. mpars.depthTest = m.depthTest;
  6374. }
  6375. if ( m.depthWrite !== undefined ) {
  6376. mpars.depthWrite = m.depthWrite;
  6377. }
  6378. if ( m.visible !== undefined ) {
  6379. mpars.visible = m.visible;
  6380. }
  6381. if ( m.flipSided !== undefined ) {
  6382. mpars.side = THREE.BackSide;
  6383. }
  6384. if ( m.doubleSided !== undefined ) {
  6385. mpars.side = THREE.DoubleSide;
  6386. }
  6387. if ( m.wireframe !== undefined ) {
  6388. mpars.wireframe = m.wireframe;
  6389. }
  6390. if ( m.vertexColors !== undefined ) {
  6391. if ( m.vertexColors === "face" ) {
  6392. mpars.vertexColors = THREE.FaceColors;
  6393. } else if ( m.vertexColors ) {
  6394. mpars.vertexColors = THREE.VertexColors;
  6395. }
  6396. }
  6397. // colors
  6398. if ( m.colorDiffuse ) {
  6399. mpars.color = rgb2hex( m.colorDiffuse );
  6400. } else if ( m.DbgColor ) {
  6401. mpars.color = m.DbgColor;
  6402. }
  6403. if ( m.colorSpecular ) {
  6404. mpars.specular = rgb2hex( m.colorSpecular );
  6405. }
  6406. if ( m.colorAmbient ) {
  6407. mpars.ambient = rgb2hex( m.colorAmbient );
  6408. }
  6409. // modifiers
  6410. if ( m.transparency ) {
  6411. mpars.opacity = m.transparency;
  6412. }
  6413. if ( m.specularCoef ) {
  6414. mpars.shininess = m.specularCoef;
  6415. }
  6416. // textures
  6417. if ( m.mapDiffuse && texturePath ) {
  6418. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  6419. }
  6420. if ( m.mapLight && texturePath ) {
  6421. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  6422. }
  6423. if ( m.mapBump && texturePath ) {
  6424. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  6425. }
  6426. if ( m.mapNormal && texturePath ) {
  6427. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  6428. }
  6429. if ( m.mapSpecular && texturePath ) {
  6430. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  6431. }
  6432. //
  6433. if ( m.mapBumpScale ) {
  6434. mpars.bumpScale = m.mapBumpScale;
  6435. }
  6436. // special case for normal mapped material
  6437. if ( m.mapNormal ) {
  6438. var shader = THREE.ShaderLib[ "normalmap" ];
  6439. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6440. uniforms[ "tNormal" ].value = mpars.normalMap;
  6441. if ( m.mapNormalFactor ) {
  6442. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  6443. }
  6444. if ( mpars.map ) {
  6445. uniforms[ "tDiffuse" ].value = mpars.map;
  6446. uniforms[ "enableDiffuse" ].value = true;
  6447. }
  6448. if ( mpars.specularMap ) {
  6449. uniforms[ "tSpecular" ].value = mpars.specularMap;
  6450. uniforms[ "enableSpecular" ].value = true;
  6451. }
  6452. if ( mpars.lightMap ) {
  6453. uniforms[ "tAO" ].value = mpars.lightMap;
  6454. uniforms[ "enableAO" ].value = true;
  6455. }
  6456. // for the moment don't handle displacement texture
  6457. uniforms[ "diffuse" ].value.setHex( mpars.color );
  6458. uniforms[ "specular" ].value.setHex( mpars.specular );
  6459. uniforms[ "ambient" ].value.setHex( mpars.ambient );
  6460. uniforms[ "shininess" ].value = mpars.shininess;
  6461. if ( mpars.opacity !== undefined ) {
  6462. uniforms[ "opacity" ].value = mpars.opacity;
  6463. }
  6464. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6465. var material = new THREE.ShaderMaterial( parameters );
  6466. if ( mpars.transparent ) {
  6467. material.transparent = true;
  6468. }
  6469. } else {
  6470. var material = new THREE[ mtype ]( mpars );
  6471. }
  6472. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6473. return material;
  6474. }
  6475. };
  6476. /**
  6477. * @author mrdoob / http://mrdoob.com/
  6478. */
  6479. THREE.XHRLoader = function ( manager ) {
  6480. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6481. };
  6482. THREE.XHRLoader.prototype = {
  6483. constructor: THREE.XHRLoader,
  6484. load: function ( url, onLoad, onProgress, onError ) {
  6485. var scope = this;
  6486. var request = new XMLHttpRequest();
  6487. if ( onLoad !== undefined ) {
  6488. request.addEventListener( 'load', function ( event ) {
  6489. onLoad( event.target.responseText );
  6490. scope.manager.itemEnd( url );
  6491. }, false );
  6492. }
  6493. if ( onProgress !== undefined ) {
  6494. request.addEventListener( 'progress', function ( event ) {
  6495. onProgress( event );
  6496. }, false );
  6497. }
  6498. if ( onError !== undefined ) {
  6499. request.addEventListener( 'error', function ( event ) {
  6500. onError( event );
  6501. }, false );
  6502. }
  6503. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6504. request.open( 'GET', url, true );
  6505. request.send( null );
  6506. scope.manager.itemStart( url );
  6507. },
  6508. setCrossOrigin: function ( value ) {
  6509. this.crossOrigin = value;
  6510. }
  6511. };
  6512. /**
  6513. * @author mrdoob / http://mrdoob.com/
  6514. */
  6515. THREE.ImageLoader = function ( manager ) {
  6516. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6517. };
  6518. THREE.ImageLoader.prototype = {
  6519. constructor: THREE.ImageLoader,
  6520. load: function ( url, onLoad, onProgress, onError ) {
  6521. var scope = this;
  6522. var image = document.createElement( 'img' );
  6523. if ( onLoad !== undefined ) {
  6524. image.addEventListener( 'load', function ( event ) {
  6525. scope.manager.itemEnd( url );
  6526. onLoad( this );
  6527. }, false );
  6528. }
  6529. if ( onProgress !== undefined ) {
  6530. image.addEventListener( 'progress', function ( event ) {
  6531. onProgress( event );
  6532. }, false );
  6533. }
  6534. if ( onError !== undefined ) {
  6535. image.addEventListener( 'error', function ( event ) {
  6536. onError( event );
  6537. }, false );
  6538. }
  6539. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  6540. image.src = url;
  6541. scope.manager.itemStart( url );
  6542. return image;
  6543. },
  6544. setCrossOrigin: function ( value ) {
  6545. this.crossOrigin = value;
  6546. }
  6547. }
  6548. /**
  6549. * @author mrdoob / http://mrdoob.com/
  6550. * @author alteredq / http://alteredqualia.com/
  6551. */
  6552. THREE.JSONLoader = function ( showStatus ) {
  6553. THREE.Loader.call( this, showStatus );
  6554. this.withCredentials = false;
  6555. };
  6556. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  6557. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  6558. var scope = this;
  6559. // todo: unify load API to for easier SceneLoader use
  6560. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  6561. this.onLoadStart();
  6562. this.loadAjaxJSON( this, url, callback, texturePath );
  6563. };
  6564. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  6565. var xhr = new XMLHttpRequest();
  6566. var length = 0;
  6567. xhr.onreadystatechange = function () {
  6568. if ( xhr.readyState === xhr.DONE ) {
  6569. if ( xhr.status === 200 || xhr.status === 0 ) {
  6570. if ( xhr.responseText ) {
  6571. var json = JSON.parse( xhr.responseText );
  6572. var result = context.parse( json, texturePath );
  6573. callback( result.geometry, result.materials );
  6574. } else {
  6575. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  6576. }
  6577. // in context of more complex asset initialization
  6578. // do not block on single failed file
  6579. // maybe should go even one more level up
  6580. context.onLoadComplete();
  6581. } else {
  6582. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  6583. }
  6584. } else if ( xhr.readyState === xhr.LOADING ) {
  6585. if ( callbackProgress ) {
  6586. if ( length === 0 ) {
  6587. length = xhr.getResponseHeader( "Content-Length" );
  6588. }
  6589. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  6590. }
  6591. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  6592. if ( callbackProgress !== undefined ) {
  6593. length = xhr.getResponseHeader( "Content-Length" );
  6594. }
  6595. }
  6596. };
  6597. xhr.open( "GET", url, true );
  6598. xhr.withCredentials = this.withCredentials;
  6599. xhr.send( null );
  6600. };
  6601. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  6602. var scope = this,
  6603. geometry = new THREE.Geometry(),
  6604. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  6605. parseModel( scale );
  6606. parseSkin();
  6607. parseMorphing( scale );
  6608. geometry.computeCentroids();
  6609. geometry.computeFaceNormals();
  6610. geometry.computeBoundingSphere();
  6611. function parseModel( scale ) {
  6612. function isBitSet( value, position ) {
  6613. return value & ( 1 << position );
  6614. }
  6615. var i, j, fi,
  6616. offset, zLength,
  6617. colorIndex, normalIndex, uvIndex, materialIndex,
  6618. type,
  6619. isQuad,
  6620. hasMaterial,
  6621. hasFaceVertexUv,
  6622. hasFaceNormal, hasFaceVertexNormal,
  6623. hasFaceColor, hasFaceVertexColor,
  6624. vertex, face, faceA, faceB, color, hex, normal,
  6625. uvLayer, uv, u, v,
  6626. faces = json.faces,
  6627. vertices = json.vertices,
  6628. normals = json.normals,
  6629. colors = json.colors,
  6630. nUvLayers = 0;
  6631. if ( json.uvs !== undefined ) {
  6632. // disregard empty arrays
  6633. for ( i = 0; i < json.uvs.length; i++ ) {
  6634. if ( json.uvs[ i ].length ) nUvLayers ++;
  6635. }
  6636. for ( i = 0; i < nUvLayers; i++ ) {
  6637. geometry.faceVertexUvs[ i ] = [];
  6638. }
  6639. }
  6640. offset = 0;
  6641. zLength = vertices.length;
  6642. while ( offset < zLength ) {
  6643. vertex = new THREE.Vector3();
  6644. vertex.x = vertices[ offset ++ ] * scale;
  6645. vertex.y = vertices[ offset ++ ] * scale;
  6646. vertex.z = vertices[ offset ++ ] * scale;
  6647. geometry.vertices.push( vertex );
  6648. }
  6649. offset = 0;
  6650. zLength = faces.length;
  6651. while ( offset < zLength ) {
  6652. type = faces[ offset ++ ];
  6653. isQuad = isBitSet( type, 0 );
  6654. hasMaterial = isBitSet( type, 1 );
  6655. hasFaceVertexUv = isBitSet( type, 3 );
  6656. hasFaceNormal = isBitSet( type, 4 );
  6657. hasFaceVertexNormal = isBitSet( type, 5 );
  6658. hasFaceColor = isBitSet( type, 6 );
  6659. hasFaceVertexColor = isBitSet( type, 7 );
  6660. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  6661. if ( isQuad ) {
  6662. faceA = new THREE.Face3();
  6663. faceA.a = faces[ offset ];
  6664. faceA.b = faces[ offset + 1 ];
  6665. faceA.c = faces[ offset + 3 ];
  6666. faceB = new THREE.Face3();
  6667. faceB.a = faces[ offset + 1 ];
  6668. faceB.b = faces[ offset + 2 ];
  6669. faceB.c = faces[ offset + 3 ];
  6670. offset += 4;
  6671. if ( hasMaterial ) {
  6672. materialIndex = faces[ offset ++ ];
  6673. faceA.materialIndex = materialIndex;
  6674. faceB.materialIndex = materialIndex;
  6675. }
  6676. // to get face <=> uv index correspondence
  6677. fi = geometry.faces.length;
  6678. if ( hasFaceVertexUv ) {
  6679. for ( i = 0; i < nUvLayers; i++ ) {
  6680. uvLayer = json.uvs[ i ];
  6681. geometry.faceVertexUvs[ i ][ fi ] = [];
  6682. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  6683. for ( j = 0; j < 4; j ++ ) {
  6684. uvIndex = faces[ offset ++ ];
  6685. u = uvLayer[ uvIndex * 2 ];
  6686. v = uvLayer[ uvIndex * 2 + 1 ];
  6687. uv = new THREE.Vector2( u, v );
  6688. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  6689. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  6690. }
  6691. }
  6692. }
  6693. if ( hasFaceNormal ) {
  6694. normalIndex = faces[ offset ++ ] * 3;
  6695. faceA.normal.set(
  6696. normals[ normalIndex ++ ],
  6697. normals[ normalIndex ++ ],
  6698. normals[ normalIndex ]
  6699. );
  6700. faceB.normal.copy( faceA.normal );
  6701. }
  6702. if ( hasFaceVertexNormal ) {
  6703. for ( i = 0; i < 4; i++ ) {
  6704. normalIndex = faces[ offset ++ ] * 3;
  6705. normal = new THREE.Vector3(
  6706. normals[ normalIndex ++ ],
  6707. normals[ normalIndex ++ ],
  6708. normals[ normalIndex ]
  6709. );
  6710. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  6711. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  6712. }
  6713. }
  6714. if ( hasFaceColor ) {
  6715. colorIndex = faces[ offset ++ ];
  6716. hex = colors[ colorIndex ];
  6717. faceA.color.setHex( hex );
  6718. faceB.color.setHex( hex );
  6719. }
  6720. if ( hasFaceVertexColor ) {
  6721. for ( i = 0; i < 4; i++ ) {
  6722. colorIndex = faces[ offset ++ ];
  6723. hex = colors[ colorIndex ];
  6724. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  6725. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  6726. }
  6727. }
  6728. geometry.faces.push( faceA );
  6729. geometry.faces.push( faceB );
  6730. } else {
  6731. face = new THREE.Face3();
  6732. face.a = faces[ offset ++ ];
  6733. face.b = faces[ offset ++ ];
  6734. face.c = faces[ offset ++ ];
  6735. if ( hasMaterial ) {
  6736. materialIndex = faces[ offset ++ ];
  6737. face.materialIndex = materialIndex;
  6738. }
  6739. // to get face <=> uv index correspondence
  6740. fi = geometry.faces.length;
  6741. if ( hasFaceVertexUv ) {
  6742. for ( i = 0; i < nUvLayers; i++ ) {
  6743. uvLayer = json.uvs[ i ];
  6744. geometry.faceVertexUvs[ i ][ fi ] = [];
  6745. for ( j = 0; j < 3; j ++ ) {
  6746. uvIndex = faces[ offset ++ ];
  6747. u = uvLayer[ uvIndex * 2 ];
  6748. v = uvLayer[ uvIndex * 2 + 1 ];
  6749. uv = new THREE.Vector2( u, v );
  6750. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  6751. }
  6752. }
  6753. }
  6754. if ( hasFaceNormal ) {
  6755. normalIndex = faces[ offset ++ ] * 3;
  6756. face.normal.set(
  6757. normals[ normalIndex ++ ],
  6758. normals[ normalIndex ++ ],
  6759. normals[ normalIndex ]
  6760. );
  6761. }
  6762. if ( hasFaceVertexNormal ) {
  6763. for ( i = 0; i < 3; i++ ) {
  6764. normalIndex = faces[ offset ++ ] * 3;
  6765. normal = new THREE.Vector3(
  6766. normals[ normalIndex ++ ],
  6767. normals[ normalIndex ++ ],
  6768. normals[ normalIndex ]
  6769. );
  6770. face.vertexNormals.push( normal );
  6771. }
  6772. }
  6773. if ( hasFaceColor ) {
  6774. colorIndex = faces[ offset ++ ];
  6775. face.color.setHex( colors[ colorIndex ] );
  6776. }
  6777. if ( hasFaceVertexColor ) {
  6778. for ( i = 0; i < 3; i++ ) {
  6779. colorIndex = faces[ offset ++ ];
  6780. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  6781. }
  6782. }
  6783. geometry.faces.push( face );
  6784. }
  6785. }
  6786. };
  6787. function parseSkin() {
  6788. var i, l, x, y, z, w, a, b, c, d;
  6789. if ( json.skinWeights ) {
  6790. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  6791. x = json.skinWeights[ i ];
  6792. y = json.skinWeights[ i + 1 ];
  6793. z = 0;
  6794. w = 0;
  6795. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  6796. }
  6797. }
  6798. if ( json.skinIndices ) {
  6799. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  6800. a = json.skinIndices[ i ];
  6801. b = json.skinIndices[ i + 1 ];
  6802. c = 0;
  6803. d = 0;
  6804. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  6805. }
  6806. }
  6807. geometry.bones = json.bones;
  6808. // could change this to json.animations[0] or remove completely
  6809. geometry.animation = json.animation;
  6810. geometry.animations = json.animations;
  6811. };
  6812. function parseMorphing( scale ) {
  6813. if ( json.morphTargets !== undefined ) {
  6814. var i, l, v, vl, dstVertices, srcVertices;
  6815. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  6816. geometry.morphTargets[ i ] = {};
  6817. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  6818. geometry.morphTargets[ i ].vertices = [];
  6819. dstVertices = geometry.morphTargets[ i ].vertices;
  6820. srcVertices = json.morphTargets [ i ].vertices;
  6821. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  6822. var vertex = new THREE.Vector3();
  6823. vertex.x = srcVertices[ v ] * scale;
  6824. vertex.y = srcVertices[ v + 1 ] * scale;
  6825. vertex.z = srcVertices[ v + 2 ] * scale;
  6826. dstVertices.push( vertex );
  6827. }
  6828. }
  6829. }
  6830. if ( json.morphColors !== undefined ) {
  6831. var i, l, c, cl, dstColors, srcColors, color;
  6832. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  6833. geometry.morphColors[ i ] = {};
  6834. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  6835. geometry.morphColors[ i ].colors = [];
  6836. dstColors = geometry.morphColors[ i ].colors;
  6837. srcColors = json.morphColors [ i ].colors;
  6838. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  6839. color = new THREE.Color( 0xffaa00 );
  6840. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  6841. dstColors.push( color );
  6842. }
  6843. }
  6844. }
  6845. };
  6846. if ( json.materials === undefined ) {
  6847. return { geometry: geometry };
  6848. } else {
  6849. var materials = this.initMaterials( json.materials, texturePath );
  6850. if ( this.needsTangents( materials ) ) {
  6851. geometry.computeTangents();
  6852. }
  6853. return { geometry: geometry, materials: materials };
  6854. }
  6855. };
  6856. /**
  6857. * @author mrdoob / http://mrdoob.com/
  6858. */
  6859. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  6860. var scope = this;
  6861. var loaded = 0, total = 0;
  6862. this.onLoad = onLoad;
  6863. this.onProgress = onProgress;
  6864. this.onError = onError;
  6865. this.itemStart = function ( url ) {
  6866. total ++;
  6867. };
  6868. this.itemEnd = function ( url ) {
  6869. loaded ++;
  6870. if ( scope.onProgress !== undefined ) {
  6871. scope.onProgress( url, loaded, total );
  6872. }
  6873. if ( loaded === total && scope.onLoad !== undefined ) {
  6874. scope.onLoad();
  6875. }
  6876. };
  6877. };
  6878. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  6879. /**
  6880. * @author mrdoob / http://mrdoob.com/
  6881. */
  6882. THREE.BufferGeometryLoader = function ( manager ) {
  6883. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6884. };
  6885. THREE.BufferGeometryLoader.prototype = {
  6886. constructor: THREE.BufferGeometryLoader,
  6887. load: function ( url, onLoad, onProgress, onError ) {
  6888. var scope = this;
  6889. var loader = new THREE.XHRLoader();
  6890. loader.setCrossOrigin( this.crossOrigin );
  6891. loader.load( url, function ( text ) {
  6892. onLoad( scope.parse( JSON.parse( text ) ) );
  6893. } );
  6894. },
  6895. setCrossOrigin: function ( value ) {
  6896. this.crossOrigin = value;
  6897. },
  6898. parse: function ( json ) {
  6899. var geometry = new THREE.BufferGeometry();
  6900. var attributes = json.attributes;
  6901. var offsets = json.offsets;
  6902. var boundingSphere = json.boundingSphere;
  6903. for ( var key in attributes ) {
  6904. var attribute = attributes[ key ];
  6905. geometry.attributes[ key ] = {
  6906. itemSize: attribute.itemSize,
  6907. array: new self[ attribute.type ]( attribute.array )
  6908. }
  6909. }
  6910. if ( offsets !== undefined ) {
  6911. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  6912. }
  6913. if ( boundingSphere !== undefined ) {
  6914. geometry.boundingSphere = new THREE.Sphere(
  6915. new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
  6916. boundingSphere.radius
  6917. );
  6918. }
  6919. return geometry;
  6920. }
  6921. };
  6922. /**
  6923. * @author mrdoob / http://mrdoob.com/
  6924. */
  6925. THREE.GeometryLoader = function ( manager ) {
  6926. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6927. };
  6928. THREE.GeometryLoader.prototype = {
  6929. constructor: THREE.GeometryLoader,
  6930. load: function ( url, onLoad, onProgress, onError ) {
  6931. var scope = this;
  6932. var loader = new THREE.XHRLoader();
  6933. loader.setCrossOrigin( this.crossOrigin );
  6934. loader.load( url, function ( text ) {
  6935. onLoad( scope.parse( JSON.parse( text ) ) );
  6936. } );
  6937. },
  6938. setCrossOrigin: function ( value ) {
  6939. this.crossOrigin = value;
  6940. },
  6941. parse: function ( json ) {
  6942. }
  6943. };
  6944. /**
  6945. * @author mrdoob / http://mrdoob.com/
  6946. */
  6947. THREE.MaterialLoader = function ( manager ) {
  6948. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6949. };
  6950. THREE.MaterialLoader.prototype = {
  6951. constructor: THREE.MaterialLoader,
  6952. load: function ( url, onLoad, onProgress, onError ) {
  6953. var scope = this;
  6954. var loader = new THREE.XHRLoader();
  6955. loader.setCrossOrigin( this.crossOrigin );
  6956. loader.load( url, function ( text ) {
  6957. onLoad( scope.parse( JSON.parse( text ) ) );
  6958. } );
  6959. },
  6960. setCrossOrigin: function ( value ) {
  6961. this.crossOrigin = value;
  6962. },
  6963. parse: function ( json ) {
  6964. var material = new THREE[ json.type ];
  6965. if ( json.color !== undefined ) material.color.setHex( json.color );
  6966. if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient );
  6967. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  6968. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  6969. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  6970. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  6971. if ( json.blending !== undefined ) material.blending = json.blending;
  6972. if ( json.side !== undefined ) material.side = json.side;
  6973. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  6974. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  6975. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  6976. if ( json.materials !== undefined ) {
  6977. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  6978. material.materials.push( this.parse( json.materials[ i ] ) );
  6979. }
  6980. }
  6981. return material;
  6982. }
  6983. };
  6984. /**
  6985. * @author mrdoob / http://mrdoob.com/
  6986. */
  6987. THREE.ObjectLoader = function ( manager ) {
  6988. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6989. };
  6990. THREE.ObjectLoader.prototype = {
  6991. constructor: THREE.ObjectLoader,
  6992. load: function ( url, onLoad, onProgress, onError ) {
  6993. var scope = this;
  6994. var loader = new THREE.XHRLoader( scope.manager );
  6995. loader.setCrossOrigin( this.crossOrigin );
  6996. loader.load( url, function ( text ) {
  6997. onLoad( scope.parse( JSON.parse( text ) ) );
  6998. } );
  6999. },
  7000. setCrossOrigin: function ( value ) {
  7001. this.crossOrigin = value;
  7002. },
  7003. parse: function ( json ) {
  7004. var geometries = this.parseGeometries( json.geometries );
  7005. var materials = this.parseMaterials( json.materials );
  7006. var object = this.parseObject( json.object, geometries, materials );
  7007. return object;
  7008. },
  7009. parseGeometries: function ( json ) {
  7010. var geometries = {};
  7011. if ( json !== undefined ) {
  7012. var geometryLoader = new THREE.JSONLoader();
  7013. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  7014. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7015. var geometry;
  7016. var data = json[ i ];
  7017. switch ( data.type ) {
  7018. case 'PlaneGeometry':
  7019. geometry = new THREE.PlaneGeometry(
  7020. data.width,
  7021. data.height,
  7022. data.widthSegments,
  7023. data.heightSegments
  7024. );
  7025. break;
  7026. case 'BoxGeometry':
  7027. case 'CubeGeometry': // DEPRECATED
  7028. geometry = new THREE.BoxGeometry(
  7029. data.width,
  7030. data.height,
  7031. data.depth,
  7032. data.widthSegments,
  7033. data.heightSegments,
  7034. data.depthSegments
  7035. );
  7036. break;
  7037. case 'CircleGeometry':
  7038. geometry = new THREE.CircleGeometry(
  7039. data.radius,
  7040. data.segments
  7041. );
  7042. break;
  7043. case 'CylinderGeometry':
  7044. geometry = new THREE.CylinderGeometry(
  7045. data.radiusTop,
  7046. data.radiusBottom,
  7047. data.height,
  7048. data.radialSegments,
  7049. data.heightSegments,
  7050. data.openEnded
  7051. );
  7052. break;
  7053. case 'SphereGeometry':
  7054. geometry = new THREE.SphereGeometry(
  7055. data.radius,
  7056. data.widthSegments,
  7057. data.heightSegments,
  7058. data.phiStart,
  7059. data.phiLength,
  7060. data.thetaStart,
  7061. data.thetaLength
  7062. );
  7063. break;
  7064. case 'IcosahedronGeometry':
  7065. geometry = new THREE.IcosahedronGeometry(
  7066. data.radius,
  7067. data.detail
  7068. );
  7069. break;
  7070. case 'TorusGeometry':
  7071. geometry = new THREE.TorusGeometry(
  7072. data.radius,
  7073. data.tube,
  7074. data.radialSegments,
  7075. data.tubularSegments,
  7076. data.arc
  7077. );
  7078. break;
  7079. case 'TorusKnotGeometry':
  7080. geometry = new THREE.TorusKnotGeometry(
  7081. data.radius,
  7082. data.tube,
  7083. data.radialSegments,
  7084. data.tubularSegments,
  7085. data.p,
  7086. data.q,
  7087. data.heightScale
  7088. );
  7089. break;
  7090. case 'BufferGeometry':
  7091. geometry = bufferGeometryLoader.parse( data.data );
  7092. break;
  7093. case 'Geometry':
  7094. geometry = geometryLoader.parse( data.data ).geometry;
  7095. break;
  7096. }
  7097. geometry.uuid = data.uuid;
  7098. if ( data.name !== undefined ) geometry.name = data.name;
  7099. geometries[ data.uuid ] = geometry;
  7100. }
  7101. }
  7102. return geometries;
  7103. },
  7104. parseMaterials: function ( json ) {
  7105. var materials = {};
  7106. if ( json !== undefined ) {
  7107. var loader = new THREE.MaterialLoader();
  7108. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7109. var data = json[ i ];
  7110. var material = loader.parse( data );
  7111. material.uuid = data.uuid;
  7112. if ( data.name !== undefined ) material.name = data.name;
  7113. materials[ data.uuid ] = material;
  7114. }
  7115. }
  7116. return materials;
  7117. },
  7118. parseObject: function () {
  7119. var matrix = new THREE.Matrix4();
  7120. return function ( data, geometries, materials ) {
  7121. var object;
  7122. switch ( data.type ) {
  7123. case 'Scene':
  7124. object = new THREE.Scene();
  7125. break;
  7126. case 'PerspectiveCamera':
  7127. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  7128. break;
  7129. case 'OrthographicCamera':
  7130. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  7131. break;
  7132. case 'AmbientLight':
  7133. object = new THREE.AmbientLight( data.color );
  7134. break;
  7135. case 'DirectionalLight':
  7136. object = new THREE.DirectionalLight( data.color, data.intensity );
  7137. break;
  7138. case 'PointLight':
  7139. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  7140. break;
  7141. case 'SpotLight':
  7142. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  7143. break;
  7144. case 'HemisphereLight':
  7145. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  7146. break;
  7147. case 'Mesh':
  7148. var geometry = geometries[ data.geometry ];
  7149. var material = materials[ data.material ];
  7150. if ( geometry === undefined ) {
  7151. console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry );
  7152. }
  7153. if ( material === undefined ) {
  7154. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7155. }
  7156. object = new THREE.Mesh( geometry, material );
  7157. break;
  7158. case 'Sprite':
  7159. var material = materials[ data.material ];
  7160. if ( material === undefined ) {
  7161. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7162. }
  7163. object = new THREE.Sprite( material );
  7164. break;
  7165. default:
  7166. object = new THREE.Object3D();
  7167. }
  7168. object.uuid = data.uuid;
  7169. if ( data.name !== undefined ) object.name = data.name;
  7170. if ( data.matrix !== undefined ) {
  7171. matrix.fromArray( data.matrix );
  7172. matrix.decompose( object.position, object.quaternion, object.scale );
  7173. } else {
  7174. if ( data.position !== undefined ) object.position.fromArray( data.position );
  7175. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  7176. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  7177. }
  7178. if ( data.visible !== undefined ) object.visible = data.visible;
  7179. if ( data.userData !== undefined ) object.userData = data.userData;
  7180. if ( data.children !== undefined ) {
  7181. for ( var child in data.children ) {
  7182. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  7183. }
  7184. }
  7185. return object;
  7186. }
  7187. }()
  7188. };
  7189. /**
  7190. * @author alteredq / http://alteredqualia.com/
  7191. */
  7192. THREE.SceneLoader = function () {
  7193. this.onLoadStart = function () {};
  7194. this.onLoadProgress = function() {};
  7195. this.onLoadComplete = function () {};
  7196. this.callbackSync = function () {};
  7197. this.callbackProgress = function () {};
  7198. this.geometryHandlers = {};
  7199. this.hierarchyHandlers = {};
  7200. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  7201. };
  7202. THREE.SceneLoader.prototype = {
  7203. constructor: THREE.SceneLoader,
  7204. load: function ( url, onLoad, onProgress, onError ) {
  7205. var scope = this;
  7206. var loader = new THREE.XHRLoader( scope.manager );
  7207. loader.setCrossOrigin( this.crossOrigin );
  7208. loader.load( url, function ( text ) {
  7209. scope.parse( JSON.parse( text ), onLoad, url );
  7210. } );
  7211. },
  7212. setCrossOrigin: function ( value ) {
  7213. this.crossOrigin = value;
  7214. },
  7215. addGeometryHandler: function ( typeID, loaderClass ) {
  7216. this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass };
  7217. },
  7218. addHierarchyHandler: function ( typeID, loaderClass ) {
  7219. this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass };
  7220. },
  7221. parse: function ( json, callbackFinished, url ) {
  7222. var scope = this;
  7223. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  7224. var geometry, material, camera, fog,
  7225. texture, images, color,
  7226. light, hex, intensity,
  7227. counter_models, counter_textures,
  7228. total_models, total_textures,
  7229. result;
  7230. var target_array = [];
  7231. var data = json;
  7232. // async geometry loaders
  7233. for ( var typeID in this.geometryHandlers ) {
  7234. var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ];
  7235. this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7236. }
  7237. // async hierachy loaders
  7238. for ( var typeID in this.hierarchyHandlers ) {
  7239. var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ];
  7240. this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7241. }
  7242. counter_models = 0;
  7243. counter_textures = 0;
  7244. result = {
  7245. scene: new THREE.Scene(),
  7246. geometries: {},
  7247. face_materials: {},
  7248. materials: {},
  7249. textures: {},
  7250. objects: {},
  7251. cameras: {},
  7252. lights: {},
  7253. fogs: {},
  7254. empties: {},
  7255. groups: {}
  7256. };
  7257. if ( data.transform ) {
  7258. var position = data.transform.position,
  7259. rotation = data.transform.rotation,
  7260. scale = data.transform.scale;
  7261. if ( position ) {
  7262. result.scene.position.fromArray( position );
  7263. }
  7264. if ( rotation ) {
  7265. result.scene.rotation.fromArray( rotation );
  7266. }
  7267. if ( scale ) {
  7268. result.scene.scale.fromArray( scale );
  7269. }
  7270. if ( position || rotation || scale ) {
  7271. result.scene.updateMatrix();
  7272. result.scene.updateMatrixWorld();
  7273. }
  7274. }
  7275. function get_url( source_url, url_type ) {
  7276. if ( url_type == "relativeToHTML" ) {
  7277. return source_url;
  7278. } else {
  7279. return urlBase + "/" + source_url;
  7280. }
  7281. };
  7282. // toplevel loader function, delegates to handle_children
  7283. function handle_objects() {
  7284. handle_children( result.scene, data.objects );
  7285. }
  7286. // handle all the children from the loaded json and attach them to given parent
  7287. function handle_children( parent, children ) {
  7288. var mat, dst, pos, rot, scl, quat;
  7289. for ( var objID in children ) {
  7290. // check by id if child has already been handled,
  7291. // if not, create new object
  7292. var object = result.objects[ objID ];
  7293. var objJSON = children[ objID ];
  7294. if ( object === undefined ) {
  7295. // meshes
  7296. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7297. if ( objJSON.loading === undefined ) {
  7298. var reservedTypes = {
  7299. "type": 1, "url": 1, "material": 1,
  7300. "position": 1, "rotation": 1, "scale" : 1,
  7301. "visible": 1, "children": 1, "userData": 1,
  7302. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
  7303. };
  7304. var loaderParameters = {};
  7305. for ( var parType in objJSON ) {
  7306. if ( ! ( parType in reservedTypes ) ) {
  7307. loaderParameters[ parType ] = objJSON[ parType ];
  7308. }
  7309. }
  7310. material = result.materials[ objJSON.material ];
  7311. objJSON.loading = true;
  7312. var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
  7313. // ColladaLoader
  7314. if ( loader.options ) {
  7315. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  7316. // UTF8Loader
  7317. // OBJLoader
  7318. } else {
  7319. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  7320. }
  7321. }
  7322. } else if ( objJSON.geometry !== undefined ) {
  7323. geometry = result.geometries[ objJSON.geometry ];
  7324. // geometry already loaded
  7325. if ( geometry ) {
  7326. var needsTangents = false;
  7327. material = result.materials[ objJSON.material ];
  7328. needsTangents = material instanceof THREE.ShaderMaterial;
  7329. pos = objJSON.position;
  7330. rot = objJSON.rotation;
  7331. scl = objJSON.scale;
  7332. mat = objJSON.matrix;
  7333. quat = objJSON.quaternion;
  7334. // use materials from the model file
  7335. // if there is no material specified in the object
  7336. if ( ! objJSON.material ) {
  7337. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7338. }
  7339. // use materials from the model file
  7340. // if there is just empty face material
  7341. // (must create new material as each model has its own face material)
  7342. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  7343. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7344. }
  7345. if ( material instanceof THREE.MeshFaceMaterial ) {
  7346. for ( var i = 0; i < material.materials.length; i ++ ) {
  7347. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  7348. }
  7349. }
  7350. if ( needsTangents ) {
  7351. geometry.computeTangents();
  7352. }
  7353. if ( objJSON.skin ) {
  7354. object = new THREE.SkinnedMesh( geometry, material );
  7355. } else if ( objJSON.morph ) {
  7356. object = new THREE.MorphAnimMesh( geometry, material );
  7357. if ( objJSON.duration !== undefined ) {
  7358. object.duration = objJSON.duration;
  7359. }
  7360. if ( objJSON.time !== undefined ) {
  7361. object.time = objJSON.time;
  7362. }
  7363. if ( objJSON.mirroredLoop !== undefined ) {
  7364. object.mirroredLoop = objJSON.mirroredLoop;
  7365. }
  7366. if ( material.morphNormals ) {
  7367. geometry.computeMorphNormals();
  7368. }
  7369. } else {
  7370. object = new THREE.Mesh( geometry, material );
  7371. }
  7372. object.name = objID;
  7373. if ( mat ) {
  7374. object.matrixAutoUpdate = false;
  7375. object.matrix.set(
  7376. mat[0], mat[1], mat[2], mat[3],
  7377. mat[4], mat[5], mat[6], mat[7],
  7378. mat[8], mat[9], mat[10], mat[11],
  7379. mat[12], mat[13], mat[14], mat[15]
  7380. );
  7381. } else {
  7382. object.position.fromArray( pos );
  7383. if ( quat ) {
  7384. object.quaternion.fromArray( quat );
  7385. } else {
  7386. object.rotation.fromArray( rot );
  7387. }
  7388. object.scale.fromArray( scl );
  7389. }
  7390. object.visible = objJSON.visible;
  7391. object.castShadow = objJSON.castShadow;
  7392. object.receiveShadow = objJSON.receiveShadow;
  7393. parent.add( object );
  7394. result.objects[ objID ] = object;
  7395. }
  7396. // lights
  7397. } else if ( objJSON.type === "AmbientLight" || objJSON.type === "PointLight" ||
  7398. objJSON.type === "DirectionalLight" || objJSON.type === "SpotLight" ||
  7399. objJSON.type === "HemisphereLight" || objJSON.type === "AreaLight" ) {
  7400. var color = objJSON.color;
  7401. var intensity = objJSON.intensity;
  7402. var distance = objJSON.distance;
  7403. var position = objJSON.position;
  7404. var rotation = objJSON.rotation;
  7405. switch ( objJSON.type ) {
  7406. case 'AmbientLight':
  7407. light = new THREE.AmbientLight( color );
  7408. break;
  7409. case 'PointLight':
  7410. light = new THREE.PointLight( color, intensity, distance );
  7411. light.position.fromArray( position );
  7412. break;
  7413. case 'DirectionalLight':
  7414. light = new THREE.DirectionalLight( color, intensity );
  7415. light.position.fromArray( objJSON.direction );
  7416. break;
  7417. case 'SpotLight':
  7418. light = new THREE.SpotLight( color, intensity, distance, 1 );
  7419. light.angle = objJSON.angle;
  7420. light.position.fromArray( position );
  7421. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  7422. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  7423. break;
  7424. case 'HemisphereLight':
  7425. light = new THREE.DirectionalLight( color, intensity, distance );
  7426. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  7427. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  7428. break;
  7429. case 'AreaLight':
  7430. light = new THREE.AreaLight(color, intensity);
  7431. light.position.fromArray( position );
  7432. light.width = objJSON.size;
  7433. light.height = objJSON.size_y;
  7434. break;
  7435. }
  7436. parent.add( light );
  7437. light.name = objID;
  7438. result.lights[ objID ] = light;
  7439. result.objects[ objID ] = light;
  7440. // cameras
  7441. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  7442. pos = objJSON.position;
  7443. rot = objJSON.rotation;
  7444. quat = objJSON.quaternion;
  7445. if ( objJSON.type === "PerspectiveCamera" ) {
  7446. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  7447. } else if ( objJSON.type === "OrthographicCamera" ) {
  7448. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  7449. }
  7450. camera.name = objID;
  7451. camera.position.fromArray( pos );
  7452. if ( quat !== undefined ) {
  7453. camera.quaternion.fromArray( quat );
  7454. } else if ( rot !== undefined ) {
  7455. camera.rotation.fromArray( rot );
  7456. }
  7457. parent.add( camera );
  7458. result.cameras[ objID ] = camera;
  7459. result.objects[ objID ] = camera;
  7460. // pure Object3D
  7461. } else {
  7462. pos = objJSON.position;
  7463. rot = objJSON.rotation;
  7464. scl = objJSON.scale;
  7465. quat = objJSON.quaternion;
  7466. object = new THREE.Object3D();
  7467. object.name = objID;
  7468. object.position.fromArray( pos );
  7469. if ( quat ) {
  7470. object.quaternion.fromArray( quat );
  7471. } else {
  7472. object.rotation.fromArray( rot );
  7473. }
  7474. object.scale.fromArray( scl );
  7475. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  7476. parent.add( object );
  7477. result.objects[ objID ] = object;
  7478. result.empties[ objID ] = object;
  7479. }
  7480. if ( object ) {
  7481. if ( objJSON.userData !== undefined ) {
  7482. for ( var key in objJSON.userData ) {
  7483. var value = objJSON.userData[ key ];
  7484. object.userData[ key ] = value;
  7485. }
  7486. }
  7487. if ( objJSON.groups !== undefined ) {
  7488. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  7489. var groupID = objJSON.groups[ i ];
  7490. if ( result.groups[ groupID ] === undefined ) {
  7491. result.groups[ groupID ] = [];
  7492. }
  7493. result.groups[ groupID ].push( objID );
  7494. }
  7495. }
  7496. }
  7497. }
  7498. if ( object !== undefined && objJSON.children !== undefined ) {
  7499. handle_children( object, objJSON.children );
  7500. }
  7501. }
  7502. };
  7503. function handle_mesh( geo, mat, id ) {
  7504. result.geometries[ id ] = geo;
  7505. result.face_materials[ id ] = mat;
  7506. handle_objects();
  7507. };
  7508. function handle_hierarchy( node, id, parent, material, obj ) {
  7509. var p = obj.position;
  7510. var r = obj.rotation;
  7511. var q = obj.quaternion;
  7512. var s = obj.scale;
  7513. node.position.fromArray( p );
  7514. if ( q ) {
  7515. node.quaternion.fromArray( q );
  7516. } else {
  7517. node.rotation.fromArray( r );
  7518. }
  7519. node.scale.fromArray( s );
  7520. // override children materials
  7521. // if object material was specified in JSON explicitly
  7522. if ( material ) {
  7523. node.traverse( function ( child ) {
  7524. child.material = material;
  7525. } );
  7526. }
  7527. // override children visibility
  7528. // with root node visibility as specified in JSON
  7529. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  7530. node.traverse( function ( child ) {
  7531. child.visible = visible;
  7532. } );
  7533. parent.add( node );
  7534. node.name = id;
  7535. result.objects[ id ] = node;
  7536. handle_objects();
  7537. };
  7538. function create_callback_geometry( id ) {
  7539. return function ( geo, mat ) {
  7540. geo.name = id;
  7541. handle_mesh( geo, mat, id );
  7542. counter_models -= 1;
  7543. scope.onLoadComplete();
  7544. async_callback_gate();
  7545. }
  7546. };
  7547. function create_callback_hierachy( id, parent, material, obj ) {
  7548. return function ( event ) {
  7549. var result;
  7550. // loaders which use EventDispatcher
  7551. if ( event.content ) {
  7552. result = event.content;
  7553. // ColladaLoader
  7554. } else if ( event.dae ) {
  7555. result = event.scene;
  7556. // UTF8Loader
  7557. } else {
  7558. result = event;
  7559. }
  7560. handle_hierarchy( result, id, parent, material, obj );
  7561. counter_models -= 1;
  7562. scope.onLoadComplete();
  7563. async_callback_gate();
  7564. }
  7565. };
  7566. function create_callback_embed( id ) {
  7567. return function ( geo, mat ) {
  7568. geo.name = id;
  7569. result.geometries[ id ] = geo;
  7570. result.face_materials[ id ] = mat;
  7571. }
  7572. };
  7573. function async_callback_gate() {
  7574. var progress = {
  7575. totalModels : total_models,
  7576. totalTextures : total_textures,
  7577. loadedModels : total_models - counter_models,
  7578. loadedTextures : total_textures - counter_textures
  7579. };
  7580. scope.callbackProgress( progress, result );
  7581. scope.onLoadProgress();
  7582. if ( counter_models === 0 && counter_textures === 0 ) {
  7583. finalize();
  7584. callbackFinished( result );
  7585. }
  7586. };
  7587. function finalize() {
  7588. // take care of targets which could be asynchronously loaded objects
  7589. for ( var i = 0; i < target_array.length; i ++ ) {
  7590. var ta = target_array[ i ];
  7591. var target = result.objects[ ta.targetName ];
  7592. if ( target ) {
  7593. ta.object.target = target;
  7594. } else {
  7595. // if there was error and target of specified name doesn't exist in the scene file
  7596. // create instead dummy target
  7597. // (target must be added to scene explicitly as parent is already added)
  7598. ta.object.target = new THREE.Object3D();
  7599. result.scene.add( ta.object.target );
  7600. }
  7601. ta.object.target.userData.targetInverse = ta.object;
  7602. }
  7603. };
  7604. var callbackTexture = function ( count ) {
  7605. counter_textures -= count;
  7606. async_callback_gate();
  7607. scope.onLoadComplete();
  7608. };
  7609. // must use this instead of just directly calling callbackTexture
  7610. // because of closure in the calling context loop
  7611. var generateTextureCallback = function ( count ) {
  7612. return function () {
  7613. callbackTexture( count );
  7614. };
  7615. };
  7616. function traverse_json_hierarchy( objJSON, callback ) {
  7617. callback( objJSON );
  7618. if ( objJSON.children !== undefined ) {
  7619. for ( var objChildID in objJSON.children ) {
  7620. traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
  7621. }
  7622. }
  7623. };
  7624. // first go synchronous elements
  7625. // fogs
  7626. var fogID, fogJSON;
  7627. for ( fogID in data.fogs ) {
  7628. fogJSON = data.fogs[ fogID ];
  7629. if ( fogJSON.type === "linear" ) {
  7630. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  7631. } else if ( fogJSON.type === "exp2" ) {
  7632. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  7633. }
  7634. color = fogJSON.color;
  7635. fog.color.setRGB( color[0], color[1], color[2] );
  7636. result.fogs[ fogID ] = fog;
  7637. }
  7638. // now come potentially asynchronous elements
  7639. // geometries
  7640. // count how many geometries will be loaded asynchronously
  7641. var geoID, geoJSON;
  7642. for ( geoID in data.geometries ) {
  7643. geoJSON = data.geometries[ geoID ];
  7644. if ( geoJSON.type in this.geometryHandlers ) {
  7645. counter_models += 1;
  7646. scope.onLoadStart();
  7647. }
  7648. }
  7649. // count how many hierarchies will be loaded asynchronously
  7650. for ( var objID in data.objects ) {
  7651. traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
  7652. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7653. counter_models += 1;
  7654. scope.onLoadStart();
  7655. }
  7656. });
  7657. }
  7658. total_models = counter_models;
  7659. for ( geoID in data.geometries ) {
  7660. geoJSON = data.geometries[ geoID ];
  7661. if ( geoJSON.type === "cube" ) {
  7662. geometry = new THREE.BoxGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  7663. geometry.name = geoID;
  7664. result.geometries[ geoID ] = geometry;
  7665. } else if ( geoJSON.type === "plane" ) {
  7666. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  7667. geometry.name = geoID;
  7668. result.geometries[ geoID ] = geometry;
  7669. } else if ( geoJSON.type === "sphere" ) {
  7670. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  7671. geometry.name = geoID;
  7672. result.geometries[ geoID ] = geometry;
  7673. } else if ( geoJSON.type === "cylinder" ) {
  7674. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  7675. geometry.name = geoID;
  7676. result.geometries[ geoID ] = geometry;
  7677. } else if ( geoJSON.type === "torus" ) {
  7678. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  7679. geometry.name = geoID;
  7680. result.geometries[ geoID ] = geometry;
  7681. } else if ( geoJSON.type === "icosahedron" ) {
  7682. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  7683. geometry.name = geoID;
  7684. result.geometries[ geoID ] = geometry;
  7685. } else if ( geoJSON.type in this.geometryHandlers ) {
  7686. var loaderParameters = {};
  7687. for ( var parType in geoJSON ) {
  7688. if ( parType !== "type" && parType !== "url" ) {
  7689. loaderParameters[ parType ] = geoJSON[ parType ];
  7690. }
  7691. }
  7692. var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ];
  7693. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  7694. } else if ( geoJSON.type === "embedded" ) {
  7695. var modelJson = data.embeds[ geoJSON.id ],
  7696. texture_path = "";
  7697. // pass metadata along to jsonLoader so it knows the format version
  7698. modelJson.metadata = data.metadata;
  7699. if ( modelJson ) {
  7700. var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ];
  7701. var model = jsonLoader.parse( modelJson, texture_path );
  7702. create_callback_embed( geoID )( model.geometry, model.materials );
  7703. }
  7704. }
  7705. }
  7706. // textures
  7707. // count how many textures will be loaded asynchronously
  7708. var textureID, textureJSON;
  7709. for ( textureID in data.textures ) {
  7710. textureJSON = data.textures[ textureID ];
  7711. if ( textureJSON.url instanceof Array ) {
  7712. counter_textures += textureJSON.url.length;
  7713. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  7714. scope.onLoadStart();
  7715. }
  7716. } else {
  7717. counter_textures += 1;
  7718. scope.onLoadStart();
  7719. }
  7720. }
  7721. total_textures = counter_textures;
  7722. for ( textureID in data.textures ) {
  7723. textureJSON = data.textures[ textureID ];
  7724. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  7725. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  7726. }
  7727. if ( textureJSON.url instanceof Array ) {
  7728. var count = textureJSON.url.length;
  7729. var url_array = [];
  7730. for( var i = 0; i < count; i ++ ) {
  7731. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  7732. }
  7733. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  7734. if ( isCompressed ) {
  7735. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7736. } else {
  7737. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7738. }
  7739. } else {
  7740. var isCompressed = /\.dds$/i.test( textureJSON.url );
  7741. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  7742. var textureCallback = generateTextureCallback( 1 );
  7743. if ( isCompressed ) {
  7744. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  7745. } else {
  7746. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  7747. }
  7748. if ( THREE[ textureJSON.minFilter ] !== undefined )
  7749. texture.minFilter = THREE[ textureJSON.minFilter ];
  7750. if ( THREE[ textureJSON.magFilter ] !== undefined )
  7751. texture.magFilter = THREE[ textureJSON.magFilter ];
  7752. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  7753. if ( textureJSON.repeat ) {
  7754. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  7755. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  7756. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  7757. }
  7758. if ( textureJSON.offset ) {
  7759. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  7760. }
  7761. // handle wrap after repeat so that default repeat can be overriden
  7762. if ( textureJSON.wrap ) {
  7763. var wrapMap = {
  7764. "repeat": THREE.RepeatWrapping,
  7765. "mirror": THREE.MirroredRepeatWrapping
  7766. }
  7767. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  7768. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  7769. }
  7770. }
  7771. result.textures[ textureID ] = texture;
  7772. }
  7773. // materials
  7774. var matID, matJSON;
  7775. var parID;
  7776. for ( matID in data.materials ) {
  7777. matJSON = data.materials[ matID ];
  7778. for ( parID in matJSON.parameters ) {
  7779. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  7780. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  7781. } else if ( parID === "shading" ) {
  7782. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  7783. } else if ( parID === "side" ) {
  7784. if ( matJSON.parameters[ parID ] == "double" ) {
  7785. matJSON.parameters[ parID ] = THREE.DoubleSide;
  7786. } else if ( matJSON.parameters[ parID ] == "back" ) {
  7787. matJSON.parameters[ parID ] = THREE.BackSide;
  7788. } else {
  7789. matJSON.parameters[ parID ] = THREE.FrontSide;
  7790. }
  7791. } else if ( parID === "blending" ) {
  7792. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  7793. } else if ( parID === "combine" ) {
  7794. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  7795. } else if ( parID === "vertexColors" ) {
  7796. if ( matJSON.parameters[ parID ] == "face" ) {
  7797. matJSON.parameters[ parID ] = THREE.FaceColors;
  7798. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  7799. } else if ( matJSON.parameters[ parID ] ) {
  7800. matJSON.parameters[ parID ] = THREE.VertexColors;
  7801. }
  7802. } else if ( parID === "wrapRGB" ) {
  7803. var v3 = matJSON.parameters[ parID ];
  7804. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  7805. }
  7806. }
  7807. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  7808. matJSON.parameters.transparent = true;
  7809. }
  7810. if ( matJSON.parameters.normalMap ) {
  7811. var shader = THREE.ShaderLib[ "normalmap" ];
  7812. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  7813. var diffuse = matJSON.parameters.color;
  7814. var specular = matJSON.parameters.specular;
  7815. var ambient = matJSON.parameters.ambient;
  7816. var shininess = matJSON.parameters.shininess;
  7817. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  7818. if ( matJSON.parameters.normalScale ) {
  7819. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  7820. }
  7821. if ( matJSON.parameters.map ) {
  7822. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  7823. uniforms[ "enableDiffuse" ].value = true;
  7824. }
  7825. if ( matJSON.parameters.envMap ) {
  7826. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  7827. uniforms[ "enableReflection" ].value = true;
  7828. uniforms[ "reflectivity" ].value = matJSON.parameters.reflectivity;
  7829. }
  7830. if ( matJSON.parameters.lightMap ) {
  7831. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  7832. uniforms[ "enableAO" ].value = true;
  7833. }
  7834. if ( matJSON.parameters.specularMap ) {
  7835. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  7836. uniforms[ "enableSpecular" ].value = true;
  7837. }
  7838. if ( matJSON.parameters.displacementMap ) {
  7839. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  7840. uniforms[ "enableDisplacement" ].value = true;
  7841. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  7842. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  7843. }
  7844. uniforms[ "diffuse" ].value.setHex( diffuse );
  7845. uniforms[ "specular" ].value.setHex( specular );
  7846. uniforms[ "ambient" ].value.setHex( ambient );
  7847. uniforms[ "shininess" ].value = shininess;
  7848. if ( matJSON.parameters.opacity ) {
  7849. uniforms[ "opacity" ].value = matJSON.parameters.opacity;
  7850. }
  7851. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  7852. material = new THREE.ShaderMaterial( parameters );
  7853. } else {
  7854. material = new THREE[ matJSON.type ]( matJSON.parameters );
  7855. }
  7856. material.name = matID;
  7857. result.materials[ matID ] = material;
  7858. }
  7859. // second pass through all materials to initialize MeshFaceMaterials
  7860. // that could be referring to other materials out of order
  7861. for ( matID in data.materials ) {
  7862. matJSON = data.materials[ matID ];
  7863. if ( matJSON.parameters.materials ) {
  7864. var materialArray = [];
  7865. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  7866. var label = matJSON.parameters.materials[ i ];
  7867. materialArray.push( result.materials[ label ] );
  7868. }
  7869. result.materials[ matID ].materials = materialArray;
  7870. }
  7871. }
  7872. // objects ( synchronous init of procedural primitives )
  7873. handle_objects();
  7874. // defaults
  7875. if ( result.cameras && data.defaults.camera ) {
  7876. result.currentCamera = result.cameras[ data.defaults.camera ];
  7877. }
  7878. if ( result.fogs && data.defaults.fog ) {
  7879. result.scene.fog = result.fogs[ data.defaults.fog ];
  7880. }
  7881. // synchronous callback
  7882. scope.callbackSync( result );
  7883. // just in case there are no async elements
  7884. async_callback_gate();
  7885. }
  7886. }
  7887. /**
  7888. * @author mrdoob / http://mrdoob.com/
  7889. */
  7890. THREE.TextureLoader = function ( manager ) {
  7891. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7892. };
  7893. THREE.TextureLoader.prototype = {
  7894. constructor: THREE.TextureLoader,
  7895. load: function ( url, onLoad, onProgress, onError ) {
  7896. var scope = this;
  7897. var loader = new THREE.ImageLoader( scope.manager );
  7898. loader.setCrossOrigin( this.crossOrigin );
  7899. loader.load( url, function ( image ) {
  7900. var texture = new THREE.Texture( image );
  7901. texture.needsUpdate = true;
  7902. if ( onLoad !== undefined ) {
  7903. onLoad( texture );
  7904. }
  7905. } );
  7906. },
  7907. setCrossOrigin: function ( value ) {
  7908. this.crossOrigin = value;
  7909. }
  7910. };
  7911. /**
  7912. * @author mrdoob / http://mrdoob.com/
  7913. * @author alteredq / http://alteredqualia.com/
  7914. */
  7915. THREE.Material = function () {
  7916. this.id = THREE.MaterialIdCount ++;
  7917. this.uuid = THREE.Math.generateUUID();
  7918. this.name = '';
  7919. this.side = THREE.FrontSide;
  7920. this.opacity = 1;
  7921. this.transparent = false;
  7922. this.blending = THREE.NormalBlending;
  7923. this.blendSrc = THREE.SrcAlphaFactor;
  7924. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  7925. this.blendEquation = THREE.AddEquation;
  7926. this.depthTest = true;
  7927. this.depthWrite = true;
  7928. this.polygonOffset = false;
  7929. this.polygonOffsetFactor = 0;
  7930. this.polygonOffsetUnits = 0;
  7931. this.alphaTest = 0;
  7932. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  7933. this.visible = true;
  7934. this.needsUpdate = true;
  7935. };
  7936. THREE.Material.prototype = {
  7937. constructor: THREE.Material,
  7938. setValues: function ( values ) {
  7939. if ( values === undefined ) return;
  7940. for ( var key in values ) {
  7941. var newValue = values[ key ];
  7942. if ( newValue === undefined ) {
  7943. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  7944. continue;
  7945. }
  7946. if ( key in this ) {
  7947. var currentValue = this[ key ];
  7948. if ( currentValue instanceof THREE.Color ) {
  7949. currentValue.set( newValue );
  7950. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  7951. currentValue.copy( newValue );
  7952. } else if ( key == 'overdraw') {
  7953. // ensure overdraw is backwards-compatable with legacy boolean type
  7954. this[ key ] = Number(newValue);
  7955. } else {
  7956. this[ key ] = newValue;
  7957. }
  7958. }
  7959. }
  7960. },
  7961. clone: function ( material ) {
  7962. if ( material === undefined ) material = new THREE.Material();
  7963. material.name = this.name;
  7964. material.side = this.side;
  7965. material.opacity = this.opacity;
  7966. material.transparent = this.transparent;
  7967. material.blending = this.blending;
  7968. material.blendSrc = this.blendSrc;
  7969. material.blendDst = this.blendDst;
  7970. material.blendEquation = this.blendEquation;
  7971. material.depthTest = this.depthTest;
  7972. material.depthWrite = this.depthWrite;
  7973. material.polygonOffset = this.polygonOffset;
  7974. material.polygonOffsetFactor = this.polygonOffsetFactor;
  7975. material.polygonOffsetUnits = this.polygonOffsetUnits;
  7976. material.alphaTest = this.alphaTest;
  7977. material.overdraw = this.overdraw;
  7978. material.visible = this.visible;
  7979. return material;
  7980. },
  7981. dispose: function () {
  7982. this.dispatchEvent( { type: 'dispose' } );
  7983. }
  7984. };
  7985. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  7986. THREE.MaterialIdCount = 0;
  7987. /**
  7988. * @author mrdoob / http://mrdoob.com/
  7989. * @author alteredq / http://alteredqualia.com/
  7990. *
  7991. * parameters = {
  7992. * color: <hex>,
  7993. * opacity: <float>,
  7994. *
  7995. * blending: THREE.NormalBlending,
  7996. * depthTest: <bool>,
  7997. * depthWrite: <bool>,
  7998. *
  7999. * linewidth: <float>,
  8000. * linecap: "round",
  8001. * linejoin: "round",
  8002. *
  8003. * vertexColors: <bool>
  8004. *
  8005. * fog: <bool>
  8006. * }
  8007. */
  8008. THREE.LineBasicMaterial = function ( parameters ) {
  8009. THREE.Material.call( this );
  8010. this.color = new THREE.Color( 0xffffff );
  8011. this.linewidth = 1;
  8012. this.linecap = 'round';
  8013. this.linejoin = 'round';
  8014. this.vertexColors = false;
  8015. this.fog = true;
  8016. this.setValues( parameters );
  8017. };
  8018. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8019. THREE.LineBasicMaterial.prototype.clone = function () {
  8020. var material = new THREE.LineBasicMaterial();
  8021. THREE.Material.prototype.clone.call( this, material );
  8022. material.color.copy( this.color );
  8023. material.linewidth = this.linewidth;
  8024. material.linecap = this.linecap;
  8025. material.linejoin = this.linejoin;
  8026. material.vertexColors = this.vertexColors;
  8027. material.fog = this.fog;
  8028. return material;
  8029. };
  8030. /**
  8031. * @author alteredq / http://alteredqualia.com/
  8032. *
  8033. * parameters = {
  8034. * color: <hex>,
  8035. * opacity: <float>,
  8036. *
  8037. * blending: THREE.NormalBlending,
  8038. * depthTest: <bool>,
  8039. * depthWrite: <bool>,
  8040. *
  8041. * linewidth: <float>,
  8042. *
  8043. * scale: <float>,
  8044. * dashSize: <float>,
  8045. * gapSize: <float>,
  8046. *
  8047. * vertexColors: <bool>
  8048. *
  8049. * fog: <bool>
  8050. * }
  8051. */
  8052. THREE.LineDashedMaterial = function ( parameters ) {
  8053. THREE.Material.call( this );
  8054. this.color = new THREE.Color( 0xffffff );
  8055. this.linewidth = 1;
  8056. this.scale = 1;
  8057. this.dashSize = 3;
  8058. this.gapSize = 1;
  8059. this.vertexColors = false;
  8060. this.fog = true;
  8061. this.setValues( parameters );
  8062. };
  8063. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  8064. THREE.LineDashedMaterial.prototype.clone = function () {
  8065. var material = new THREE.LineDashedMaterial();
  8066. THREE.Material.prototype.clone.call( this, material );
  8067. material.color.copy( this.color );
  8068. material.linewidth = this.linewidth;
  8069. material.scale = this.scale;
  8070. material.dashSize = this.dashSize;
  8071. material.gapSize = this.gapSize;
  8072. material.vertexColors = this.vertexColors;
  8073. material.fog = this.fog;
  8074. return material;
  8075. };
  8076. /**
  8077. * @author mrdoob / http://mrdoob.com/
  8078. * @author alteredq / http://alteredqualia.com/
  8079. *
  8080. * parameters = {
  8081. * color: <hex>,
  8082. * opacity: <float>,
  8083. * map: new THREE.Texture( <Image> ),
  8084. *
  8085. * lightMap: new THREE.Texture( <Image> ),
  8086. *
  8087. * specularMap: new THREE.Texture( <Image> ),
  8088. *
  8089. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8090. * combine: THREE.Multiply,
  8091. * reflectivity: <float>,
  8092. * refractionRatio: <float>,
  8093. *
  8094. * shading: THREE.SmoothShading,
  8095. * blending: THREE.NormalBlending,
  8096. * depthTest: <bool>,
  8097. * depthWrite: <bool>,
  8098. *
  8099. * wireframe: <boolean>,
  8100. * wireframeLinewidth: <float>,
  8101. *
  8102. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8103. *
  8104. * skinning: <bool>,
  8105. * morphTargets: <bool>,
  8106. *
  8107. * fog: <bool>
  8108. * }
  8109. */
  8110. THREE.MeshBasicMaterial = function ( parameters ) {
  8111. THREE.Material.call( this );
  8112. this.color = new THREE.Color( 0xffffff ); // emissive
  8113. this.map = null;
  8114. this.lightMap = null;
  8115. this.specularMap = null;
  8116. this.envMap = null;
  8117. this.combine = THREE.MultiplyOperation;
  8118. this.reflectivity = 1;
  8119. this.refractionRatio = 0.98;
  8120. this.fog = true;
  8121. this.shading = THREE.SmoothShading;
  8122. this.wireframe = false;
  8123. this.wireframeLinewidth = 1;
  8124. this.wireframeLinecap = 'round';
  8125. this.wireframeLinejoin = 'round';
  8126. this.vertexColors = THREE.NoColors;
  8127. this.skinning = false;
  8128. this.morphTargets = false;
  8129. this.setValues( parameters );
  8130. };
  8131. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8132. THREE.MeshBasicMaterial.prototype.clone = function () {
  8133. var material = new THREE.MeshBasicMaterial();
  8134. THREE.Material.prototype.clone.call( this, material );
  8135. material.color.copy( this.color );
  8136. material.map = this.map;
  8137. material.lightMap = this.lightMap;
  8138. material.specularMap = this.specularMap;
  8139. material.envMap = this.envMap;
  8140. material.combine = this.combine;
  8141. material.reflectivity = this.reflectivity;
  8142. material.refractionRatio = this.refractionRatio;
  8143. material.fog = this.fog;
  8144. material.shading = this.shading;
  8145. material.wireframe = this.wireframe;
  8146. material.wireframeLinewidth = this.wireframeLinewidth;
  8147. material.wireframeLinecap = this.wireframeLinecap;
  8148. material.wireframeLinejoin = this.wireframeLinejoin;
  8149. material.vertexColors = this.vertexColors;
  8150. material.skinning = this.skinning;
  8151. material.morphTargets = this.morphTargets;
  8152. return material;
  8153. };
  8154. /**
  8155. * @author mrdoob / http://mrdoob.com/
  8156. * @author alteredq / http://alteredqualia.com/
  8157. *
  8158. * parameters = {
  8159. * color: <hex>,
  8160. * ambient: <hex>,
  8161. * emissive: <hex>,
  8162. * opacity: <float>,
  8163. *
  8164. * map: new THREE.Texture( <Image> ),
  8165. *
  8166. * lightMap: new THREE.Texture( <Image> ),
  8167. *
  8168. * specularMap: new THREE.Texture( <Image> ),
  8169. *
  8170. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8171. * combine: THREE.Multiply,
  8172. * reflectivity: <float>,
  8173. * refractionRatio: <float>,
  8174. *
  8175. * shading: THREE.SmoothShading,
  8176. * blending: THREE.NormalBlending,
  8177. * depthTest: <bool>,
  8178. * depthWrite: <bool>,
  8179. *
  8180. * wireframe: <boolean>,
  8181. * wireframeLinewidth: <float>,
  8182. *
  8183. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8184. *
  8185. * skinning: <bool>,
  8186. * morphTargets: <bool>,
  8187. * morphNormals: <bool>,
  8188. *
  8189. * fog: <bool>
  8190. * }
  8191. */
  8192. THREE.MeshLambertMaterial = function ( parameters ) {
  8193. THREE.Material.call( this );
  8194. this.color = new THREE.Color( 0xffffff ); // diffuse
  8195. this.ambient = new THREE.Color( 0xffffff );
  8196. this.emissive = new THREE.Color( 0x000000 );
  8197. this.wrapAround = false;
  8198. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8199. this.map = null;
  8200. this.lightMap = null;
  8201. this.specularMap = null;
  8202. this.envMap = null;
  8203. this.combine = THREE.MultiplyOperation;
  8204. this.reflectivity = 1;
  8205. this.refractionRatio = 0.98;
  8206. this.fog = true;
  8207. this.shading = THREE.SmoothShading;
  8208. this.wireframe = false;
  8209. this.wireframeLinewidth = 1;
  8210. this.wireframeLinecap = 'round';
  8211. this.wireframeLinejoin = 'round';
  8212. this.vertexColors = THREE.NoColors;
  8213. this.skinning = false;
  8214. this.morphTargets = false;
  8215. this.morphNormals = false;
  8216. this.setValues( parameters );
  8217. };
  8218. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  8219. THREE.MeshLambertMaterial.prototype.clone = function () {
  8220. var material = new THREE.MeshLambertMaterial();
  8221. THREE.Material.prototype.clone.call( this, material );
  8222. material.color.copy( this.color );
  8223. material.ambient.copy( this.ambient );
  8224. material.emissive.copy( this.emissive );
  8225. material.wrapAround = this.wrapAround;
  8226. material.wrapRGB.copy( this.wrapRGB );
  8227. material.map = this.map;
  8228. material.lightMap = this.lightMap;
  8229. material.specularMap = this.specularMap;
  8230. material.envMap = this.envMap;
  8231. material.combine = this.combine;
  8232. material.reflectivity = this.reflectivity;
  8233. material.refractionRatio = this.refractionRatio;
  8234. material.fog = this.fog;
  8235. material.shading = this.shading;
  8236. material.wireframe = this.wireframe;
  8237. material.wireframeLinewidth = this.wireframeLinewidth;
  8238. material.wireframeLinecap = this.wireframeLinecap;
  8239. material.wireframeLinejoin = this.wireframeLinejoin;
  8240. material.vertexColors = this.vertexColors;
  8241. material.skinning = this.skinning;
  8242. material.morphTargets = this.morphTargets;
  8243. material.morphNormals = this.morphNormals;
  8244. return material;
  8245. };
  8246. /**
  8247. * @author mrdoob / http://mrdoob.com/
  8248. * @author alteredq / http://alteredqualia.com/
  8249. *
  8250. * parameters = {
  8251. * color: <hex>,
  8252. * ambient: <hex>,
  8253. * emissive: <hex>,
  8254. * specular: <hex>,
  8255. * shininess: <float>,
  8256. * opacity: <float>,
  8257. *
  8258. * map: new THREE.Texture( <Image> ),
  8259. *
  8260. * lightMap: new THREE.Texture( <Image> ),
  8261. *
  8262. * bumpMap: new THREE.Texture( <Image> ),
  8263. * bumpScale: <float>,
  8264. *
  8265. * normalMap: new THREE.Texture( <Image> ),
  8266. * normalScale: <Vector2>,
  8267. *
  8268. * specularMap: new THREE.Texture( <Image> ),
  8269. *
  8270. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8271. * combine: THREE.Multiply,
  8272. * reflectivity: <float>,
  8273. * refractionRatio: <float>,
  8274. *
  8275. * shading: THREE.SmoothShading,
  8276. * blending: THREE.NormalBlending,
  8277. * depthTest: <bool>,
  8278. * depthWrite: <bool>,
  8279. *
  8280. * wireframe: <boolean>,
  8281. * wireframeLinewidth: <float>,
  8282. *
  8283. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8284. *
  8285. * skinning: <bool>,
  8286. * morphTargets: <bool>,
  8287. * morphNormals: <bool>,
  8288. *
  8289. * fog: <bool>
  8290. * }
  8291. */
  8292. THREE.MeshPhongMaterial = function ( parameters ) {
  8293. THREE.Material.call( this );
  8294. this.color = new THREE.Color( 0xffffff ); // diffuse
  8295. this.ambient = new THREE.Color( 0xffffff );
  8296. this.emissive = new THREE.Color( 0x000000 );
  8297. this.specular = new THREE.Color( 0x111111 );
  8298. this.shininess = 30;
  8299. this.metal = false;
  8300. this.wrapAround = false;
  8301. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8302. this.map = null;
  8303. this.lightMap = null;
  8304. this.bumpMap = null;
  8305. this.bumpScale = 1;
  8306. this.normalMap = null;
  8307. this.normalScale = new THREE.Vector2( 1, 1 );
  8308. this.specularMap = null;
  8309. this.envMap = null;
  8310. this.combine = THREE.MultiplyOperation;
  8311. this.reflectivity = 1;
  8312. this.refractionRatio = 0.98;
  8313. this.fog = true;
  8314. this.shading = THREE.SmoothShading;
  8315. this.wireframe = false;
  8316. this.wireframeLinewidth = 1;
  8317. this.wireframeLinecap = 'round';
  8318. this.wireframeLinejoin = 'round';
  8319. this.vertexColors = THREE.NoColors;
  8320. this.skinning = false;
  8321. this.morphTargets = false;
  8322. this.morphNormals = false;
  8323. this.setValues( parameters );
  8324. };
  8325. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8326. THREE.MeshPhongMaterial.prototype.clone = function () {
  8327. var material = new THREE.MeshPhongMaterial();
  8328. THREE.Material.prototype.clone.call( this, material );
  8329. material.color.copy( this.color );
  8330. material.ambient.copy( this.ambient );
  8331. material.emissive.copy( this.emissive );
  8332. material.specular.copy( this.specular );
  8333. material.shininess = this.shininess;
  8334. material.metal = this.metal;
  8335. material.wrapAround = this.wrapAround;
  8336. material.wrapRGB.copy( this.wrapRGB );
  8337. material.map = this.map;
  8338. material.lightMap = this.lightMap;
  8339. material.bumpMap = this.bumpMap;
  8340. material.bumpScale = this.bumpScale;
  8341. material.normalMap = this.normalMap;
  8342. material.normalScale.copy( this.normalScale );
  8343. material.specularMap = this.specularMap;
  8344. material.envMap = this.envMap;
  8345. material.combine = this.combine;
  8346. material.reflectivity = this.reflectivity;
  8347. material.refractionRatio = this.refractionRatio;
  8348. material.fog = this.fog;
  8349. material.shading = this.shading;
  8350. material.wireframe = this.wireframe;
  8351. material.wireframeLinewidth = this.wireframeLinewidth;
  8352. material.wireframeLinecap = this.wireframeLinecap;
  8353. material.wireframeLinejoin = this.wireframeLinejoin;
  8354. material.vertexColors = this.vertexColors;
  8355. material.skinning = this.skinning;
  8356. material.morphTargets = this.morphTargets;
  8357. material.morphNormals = this.morphNormals;
  8358. return material;
  8359. };
  8360. /**
  8361. * @author mrdoob / http://mrdoob.com/
  8362. * @author alteredq / http://alteredqualia.com/
  8363. *
  8364. * parameters = {
  8365. * opacity: <float>,
  8366. *
  8367. * blending: THREE.NormalBlending,
  8368. * depthTest: <bool>,
  8369. * depthWrite: <bool>,
  8370. *
  8371. * wireframe: <boolean>,
  8372. * wireframeLinewidth: <float>
  8373. * }
  8374. */
  8375. THREE.MeshDepthMaterial = function ( parameters ) {
  8376. THREE.Material.call( this );
  8377. this.wireframe = false;
  8378. this.wireframeLinewidth = 1;
  8379. this.setValues( parameters );
  8380. };
  8381. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  8382. THREE.MeshDepthMaterial.prototype.clone = function () {
  8383. var material = new THREE.MeshDepthMaterial();
  8384. THREE.Material.prototype.clone.call( this, material );
  8385. material.wireframe = this.wireframe;
  8386. material.wireframeLinewidth = this.wireframeLinewidth;
  8387. return material;
  8388. };
  8389. /**
  8390. * @author mrdoob / http://mrdoob.com/
  8391. *
  8392. * parameters = {
  8393. * opacity: <float>,
  8394. *
  8395. * shading: THREE.FlatShading,
  8396. * blending: THREE.NormalBlending,
  8397. * depthTest: <bool>,
  8398. * depthWrite: <bool>,
  8399. *
  8400. * wireframe: <boolean>,
  8401. * wireframeLinewidth: <float>
  8402. * }
  8403. */
  8404. THREE.MeshNormalMaterial = function ( parameters ) {
  8405. THREE.Material.call( this, parameters );
  8406. this.shading = THREE.FlatShading;
  8407. this.wireframe = false;
  8408. this.wireframeLinewidth = 1;
  8409. this.morphTargets = false;
  8410. this.setValues( parameters );
  8411. };
  8412. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  8413. THREE.MeshNormalMaterial.prototype.clone = function () {
  8414. var material = new THREE.MeshNormalMaterial();
  8415. THREE.Material.prototype.clone.call( this, material );
  8416. material.shading = this.shading;
  8417. material.wireframe = this.wireframe;
  8418. material.wireframeLinewidth = this.wireframeLinewidth;
  8419. return material;
  8420. };
  8421. /**
  8422. * @author mrdoob / http://mrdoob.com/
  8423. */
  8424. THREE.MeshFaceMaterial = function ( materials ) {
  8425. this.materials = materials instanceof Array ? materials : [];
  8426. };
  8427. THREE.MeshFaceMaterial.prototype.clone = function () {
  8428. var material = new THREE.MeshFaceMaterial();
  8429. for ( var i = 0; i < this.materials.length; i ++ ) {
  8430. material.materials.push( this.materials[ i ].clone() );
  8431. }
  8432. return material;
  8433. };
  8434. /**
  8435. * @author mrdoob / http://mrdoob.com/
  8436. * @author alteredq / http://alteredqualia.com/
  8437. *
  8438. * parameters = {
  8439. * color: <hex>,
  8440. * opacity: <float>,
  8441. * map: new THREE.Texture( <Image> ),
  8442. *
  8443. * size: <float>,
  8444. *
  8445. * blending: THREE.NormalBlending,
  8446. * depthTest: <bool>,
  8447. * depthWrite: <bool>,
  8448. *
  8449. * vertexColors: <bool>,
  8450. *
  8451. * fog: <bool>
  8452. * }
  8453. */
  8454. THREE.ParticleSystemMaterial = function ( parameters ) {
  8455. THREE.Material.call( this );
  8456. this.color = new THREE.Color( 0xffffff );
  8457. this.map = null;
  8458. this.size = 1;
  8459. this.sizeAttenuation = true;
  8460. this.vertexColors = false;
  8461. this.fog = true;
  8462. this.setValues( parameters );
  8463. };
  8464. THREE.ParticleSystemMaterial.prototype = Object.create( THREE.Material.prototype );
  8465. THREE.ParticleSystemMaterial.prototype.clone = function () {
  8466. var material = new THREE.ParticleSystemMaterial();
  8467. THREE.Material.prototype.clone.call( this, material );
  8468. material.color.copy( this.color );
  8469. material.map = this.map;
  8470. material.size = this.size;
  8471. material.sizeAttenuation = this.sizeAttenuation;
  8472. material.vertexColors = this.vertexColors;
  8473. material.fog = this.fog;
  8474. return material;
  8475. };
  8476. // backwards compatibility
  8477. THREE.ParticleBasicMaterial = THREE.ParticleSystemMaterial;
  8478. /**
  8479. * @author alteredq / http://alteredqualia.com/
  8480. *
  8481. * parameters = {
  8482. * fragmentShader: <string>,
  8483. * vertexShader: <string>,
  8484. *
  8485. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  8486. *
  8487. * defines: { "label" : "value" },
  8488. *
  8489. * shading: THREE.SmoothShading,
  8490. * blending: THREE.NormalBlending,
  8491. * depthTest: <bool>,
  8492. * depthWrite: <bool>,
  8493. *
  8494. * wireframe: <boolean>,
  8495. * wireframeLinewidth: <float>,
  8496. *
  8497. * lights: <bool>,
  8498. *
  8499. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8500. *
  8501. * skinning: <bool>,
  8502. * morphTargets: <bool>,
  8503. * morphNormals: <bool>,
  8504. *
  8505. * fog: <bool>
  8506. * }
  8507. */
  8508. THREE.ShaderMaterial = function ( parameters ) {
  8509. THREE.Material.call( this );
  8510. this.fragmentShader = "void main() {}";
  8511. this.vertexShader = "void main() {}";
  8512. this.uniforms = {};
  8513. this.defines = {};
  8514. this.attributes = null;
  8515. this.shading = THREE.SmoothShading;
  8516. this.linewidth = 1;
  8517. this.wireframe = false;
  8518. this.wireframeLinewidth = 1;
  8519. this.fog = false; // set to use scene fog
  8520. this.lights = false; // set to use scene lights
  8521. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  8522. this.skinning = false; // set to use skinning attribute streams
  8523. this.morphTargets = false; // set to use morph targets
  8524. this.morphNormals = false; // set to use morph normals
  8525. // When rendered geometry doesn't include these attributes but the material does,
  8526. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8527. this.defaultAttributeValues = {
  8528. "color" : [ 1, 1, 1],
  8529. "uv" : [ 0, 0 ],
  8530. "uv2" : [ 0, 0 ]
  8531. };
  8532. // By default, bind position to attribute index 0. In WebGL, attribute 0
  8533. // should always be used to avoid potentially expensive emulation.
  8534. this.index0AttributeName = "position";
  8535. this.setValues( parameters );
  8536. };
  8537. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  8538. THREE.ShaderMaterial.prototype.clone = function () {
  8539. var material = new THREE.ShaderMaterial();
  8540. THREE.Material.prototype.clone.call( this, material );
  8541. material.fragmentShader = this.fragmentShader;
  8542. material.vertexShader = this.vertexShader;
  8543. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  8544. material.attributes = this.attributes;
  8545. material.defines = this.defines;
  8546. material.shading = this.shading;
  8547. material.wireframe = this.wireframe;
  8548. material.wireframeLinewidth = this.wireframeLinewidth;
  8549. material.fog = this.fog;
  8550. material.lights = this.lights;
  8551. material.vertexColors = this.vertexColors;
  8552. material.skinning = this.skinning;
  8553. material.morphTargets = this.morphTargets;
  8554. material.morphNormals = this.morphNormals;
  8555. return material;
  8556. };
  8557. /**
  8558. * @author alteredq / http://alteredqualia.com/
  8559. *
  8560. * parameters = {
  8561. * color: <hex>,
  8562. * opacity: <float>,
  8563. * map: new THREE.Texture( <Image> ),
  8564. *
  8565. * blending: THREE.NormalBlending,
  8566. * depthTest: <bool>,
  8567. * depthWrite: <bool>,
  8568. *
  8569. * uvOffset: new THREE.Vector2(),
  8570. * uvScale: new THREE.Vector2(),
  8571. *
  8572. * fog: <bool>
  8573. * }
  8574. */
  8575. THREE.SpriteMaterial = function ( parameters ) {
  8576. THREE.Material.call( this );
  8577. // defaults
  8578. this.color = new THREE.Color( 0xffffff );
  8579. this.map = null;
  8580. this.rotation = 0;
  8581. this.fog = false;
  8582. // set parameters
  8583. this.setValues( parameters );
  8584. };
  8585. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8586. THREE.SpriteMaterial.prototype.clone = function () {
  8587. var material = new THREE.SpriteMaterial();
  8588. THREE.Material.prototype.clone.call( this, material );
  8589. material.color.copy( this.color );
  8590. material.map = this.map;
  8591. material.rotation = this.rotation;
  8592. material.fog = this.fog;
  8593. return material;
  8594. };
  8595. /**
  8596. * @author mrdoob / http://mrdoob.com/
  8597. *
  8598. * parameters = {
  8599. * color: <hex>,
  8600. * program: <function>,
  8601. * opacity: <float>,
  8602. * blending: THREE.NormalBlending
  8603. * }
  8604. */
  8605. THREE.SpriteCanvasMaterial = function ( parameters ) {
  8606. THREE.Material.call( this );
  8607. this.color = new THREE.Color( 0xffffff );
  8608. this.program = function ( context, color ) {};
  8609. this.setValues( parameters );
  8610. };
  8611. THREE.SpriteCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  8612. THREE.SpriteCanvasMaterial.prototype.clone = function () {
  8613. var material = new THREE.SpriteCanvasMaterial();
  8614. THREE.Material.prototype.clone.call( this, material );
  8615. material.color.copy( this.color );
  8616. material.program = this.program;
  8617. return material;
  8618. };
  8619. // backwards compatibility
  8620. THREE.ParticleCanvasMaterial = THREE.SpriteCanvasMaterial;
  8621. /**
  8622. * @author mrdoob / http://mrdoob.com/
  8623. * @author alteredq / http://alteredqualia.com/
  8624. * @author szimek / https://github.com/szimek/
  8625. */
  8626. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8627. this.id = THREE.TextureIdCount ++;
  8628. this.uuid = THREE.Math.generateUUID();
  8629. this.name = '';
  8630. this.image = image;
  8631. this.mipmaps = [];
  8632. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  8633. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8634. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8635. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8636. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8637. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8638. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8639. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8640. this.offset = new THREE.Vector2( 0, 0 );
  8641. this.repeat = new THREE.Vector2( 1, 1 );
  8642. this.generateMipmaps = true;
  8643. this.premultiplyAlpha = false;
  8644. this.flipY = true;
  8645. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8646. this._needsUpdate = false;
  8647. this.onUpdate = null;
  8648. };
  8649. THREE.Texture.prototype = {
  8650. constructor: THREE.Texture,
  8651. get needsUpdate () {
  8652. return this._needsUpdate;
  8653. },
  8654. set needsUpdate ( value ) {
  8655. if ( value === true ) this.update();
  8656. this._needsUpdate = value;
  8657. },
  8658. clone: function ( texture ) {
  8659. if ( texture === undefined ) texture = new THREE.Texture();
  8660. texture.image = this.image;
  8661. texture.mipmaps = this.mipmaps.slice(0);
  8662. texture.mapping = this.mapping;
  8663. texture.wrapS = this.wrapS;
  8664. texture.wrapT = this.wrapT;
  8665. texture.magFilter = this.magFilter;
  8666. texture.minFilter = this.minFilter;
  8667. texture.anisotropy = this.anisotropy;
  8668. texture.format = this.format;
  8669. texture.type = this.type;
  8670. texture.offset.copy( this.offset );
  8671. texture.repeat.copy( this.repeat );
  8672. texture.generateMipmaps = this.generateMipmaps;
  8673. texture.premultiplyAlpha = this.premultiplyAlpha;
  8674. texture.flipY = this.flipY;
  8675. texture.unpackAlignment = this.unpackAlignment;
  8676. return texture;
  8677. },
  8678. update: function () {
  8679. this.dispatchEvent( { type: 'update' } );
  8680. },
  8681. dispose: function () {
  8682. this.dispatchEvent( { type: 'dispose' } );
  8683. }
  8684. };
  8685. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  8686. THREE.TextureIdCount = 0;
  8687. /**
  8688. * @author alteredq / http://alteredqualia.com/
  8689. */
  8690. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8691. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8692. this.image = { width: width, height: height };
  8693. this.mipmaps = mipmaps;
  8694. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  8695. };
  8696. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8697. THREE.CompressedTexture.prototype.clone = function () {
  8698. var texture = new THREE.CompressedTexture();
  8699. THREE.Texture.prototype.clone.call( this, texture );
  8700. return texture;
  8701. };
  8702. /**
  8703. * @author alteredq / http://alteredqualia.com/
  8704. */
  8705. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8706. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8707. this.image = { data: data, width: width, height: height };
  8708. };
  8709. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8710. THREE.DataTexture.prototype.clone = function () {
  8711. var texture = new THREE.DataTexture();
  8712. THREE.Texture.prototype.clone.call( this, texture );
  8713. return texture;
  8714. };
  8715. /**
  8716. * @author alteredq / http://alteredqualia.com/
  8717. */
  8718. THREE.ParticleSystem = function ( geometry, material ) {
  8719. THREE.Object3D.call( this );
  8720. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8721. this.material = material !== undefined ? material : new THREE.ParticleSystemMaterial( { color: Math.random() * 0xffffff } );
  8722. this.sortParticles = false;
  8723. this.frustumCulled = false;
  8724. };
  8725. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  8726. THREE.ParticleSystem.prototype.clone = function ( object ) {
  8727. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  8728. object.sortParticles = this.sortParticles;
  8729. THREE.Object3D.prototype.clone.call( this, object );
  8730. return object;
  8731. };
  8732. /**
  8733. * @author mrdoob / http://mrdoob.com/
  8734. */
  8735. THREE.Line = function ( geometry, material, type ) {
  8736. THREE.Object3D.call( this );
  8737. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8738. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  8739. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  8740. };
  8741. THREE.LineStrip = 0;
  8742. THREE.LinePieces = 1;
  8743. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  8744. THREE.Line.prototype.clone = function ( object ) {
  8745. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  8746. THREE.Object3D.prototype.clone.call( this, object );
  8747. return object;
  8748. };
  8749. /**
  8750. * @author mrdoob / http://mrdoob.com/
  8751. * @author alteredq / http://alteredqualia.com/
  8752. * @author mikael emtinger / http://gomo.se/
  8753. * @author jonobr1 / http://jonobr1.com/
  8754. */
  8755. THREE.Mesh = function ( geometry, material ) {
  8756. THREE.Object3D.call( this );
  8757. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8758. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  8759. this.updateMorphTargets();
  8760. };
  8761. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  8762. THREE.Mesh.prototype.updateMorphTargets = function () {
  8763. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  8764. this.morphTargetBase = -1;
  8765. this.morphTargetForcedOrder = [];
  8766. this.morphTargetInfluences = [];
  8767. this.morphTargetDictionary = {};
  8768. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  8769. this.morphTargetInfluences.push( 0 );
  8770. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  8771. }
  8772. }
  8773. };
  8774. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  8775. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  8776. return this.morphTargetDictionary[ name ];
  8777. }
  8778. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  8779. return 0;
  8780. };
  8781. THREE.Mesh.prototype.clone = function ( object ) {
  8782. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  8783. THREE.Object3D.prototype.clone.call( this, object );
  8784. return object;
  8785. };
  8786. /**
  8787. * @author mikael emtinger / http://gomo.se/
  8788. * @author alteredq / http://alteredqualia.com/
  8789. */
  8790. THREE.Bone = function( belongsToSkin ) {
  8791. THREE.Object3D.call( this );
  8792. this.skin = belongsToSkin;
  8793. this.skinMatrix = new THREE.Matrix4();
  8794. };
  8795. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  8796. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  8797. // update local
  8798. if ( this.matrixAutoUpdate ) {
  8799. forceUpdate |= this.updateMatrix();
  8800. }
  8801. // update skin matrix
  8802. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  8803. if( parentSkinMatrix ) {
  8804. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  8805. } else {
  8806. this.skinMatrix.copy( this.matrix );
  8807. }
  8808. this.matrixWorldNeedsUpdate = false;
  8809. forceUpdate = true;
  8810. }
  8811. // update children
  8812. var child, i, l = this.children.length;
  8813. for ( i = 0; i < l; i ++ ) {
  8814. this.children[ i ].update( this.skinMatrix, forceUpdate );
  8815. }
  8816. };
  8817. /**
  8818. * @author mikael emtinger / http://gomo.se/
  8819. * @author alteredq / http://alteredqualia.com/
  8820. */
  8821. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  8822. THREE.Mesh.call( this, geometry, material );
  8823. //
  8824. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  8825. // init bones
  8826. this.identityMatrix = new THREE.Matrix4();
  8827. this.bones = [];
  8828. this.boneMatrices = [];
  8829. var b, bone, gbone, p, q, s;
  8830. if ( this.geometry && this.geometry.bones !== undefined ) {
  8831. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  8832. gbone = this.geometry.bones[ b ];
  8833. p = gbone.pos;
  8834. q = gbone.rotq;
  8835. s = gbone.scl;
  8836. bone = this.addBone();
  8837. bone.name = gbone.name;
  8838. bone.position.set( p[0], p[1], p[2] );
  8839. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  8840. if ( s !== undefined ) {
  8841. bone.scale.set( s[0], s[1], s[2] );
  8842. } else {
  8843. bone.scale.set( 1, 1, 1 );
  8844. }
  8845. }
  8846. for ( b = 0; b < this.bones.length; b ++ ) {
  8847. gbone = this.geometry.bones[ b ];
  8848. bone = this.bones[ b ];
  8849. if ( gbone.parent === -1 ) {
  8850. this.add( bone );
  8851. } else {
  8852. this.bones[ gbone.parent ].add( bone );
  8853. }
  8854. }
  8855. //
  8856. var nBones = this.bones.length;
  8857. if ( this.useVertexTexture ) {
  8858. // layout (1 matrix = 4 pixels)
  8859. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8860. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  8861. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  8862. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  8863. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  8864. var size;
  8865. if ( nBones > 256 )
  8866. size = 64;
  8867. else if ( nBones > 64 )
  8868. size = 32;
  8869. else if ( nBones > 16 )
  8870. size = 16;
  8871. else
  8872. size = 8;
  8873. this.boneTextureWidth = size;
  8874. this.boneTextureHeight = size;
  8875. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  8876. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  8877. this.boneTexture.minFilter = THREE.NearestFilter;
  8878. this.boneTexture.magFilter = THREE.NearestFilter;
  8879. this.boneTexture.generateMipmaps = false;
  8880. this.boneTexture.flipY = false;
  8881. } else {
  8882. this.boneMatrices = new Float32Array( 16 * nBones );
  8883. }
  8884. this.pose();
  8885. }
  8886. };
  8887. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  8888. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  8889. if ( bone === undefined ) {
  8890. bone = new THREE.Bone( this );
  8891. }
  8892. this.bones.push( bone );
  8893. return bone;
  8894. };
  8895. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  8896. var offsetMatrix = new THREE.Matrix4();
  8897. return function ( force ) {
  8898. this.matrixAutoUpdate && this.updateMatrix();
  8899. // update matrixWorld
  8900. if ( this.matrixWorldNeedsUpdate || force ) {
  8901. if ( this.parent ) {
  8902. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8903. } else {
  8904. this.matrixWorld.copy( this.matrix );
  8905. }
  8906. this.matrixWorldNeedsUpdate = false;
  8907. force = true;
  8908. }
  8909. // update children
  8910. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8911. var child = this.children[ i ];
  8912. if ( child instanceof THREE.Bone ) {
  8913. child.update( this.identityMatrix, false );
  8914. } else {
  8915. child.updateMatrixWorld( true );
  8916. }
  8917. }
  8918. // make a snapshot of the bones' rest position
  8919. if ( this.boneInverses == undefined ) {
  8920. this.boneInverses = [];
  8921. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8922. var inverse = new THREE.Matrix4();
  8923. inverse.getInverse( this.bones[ b ].skinMatrix );
  8924. this.boneInverses.push( inverse );
  8925. }
  8926. }
  8927. // flatten bone matrices to array
  8928. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8929. // compute the offset between the current and the original transform;
  8930. // TODO: we could get rid of this multiplication step if the skinMatrix
  8931. // was already representing the offset; however, this requires some
  8932. // major changes to the animation system
  8933. offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  8934. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  8935. }
  8936. if ( this.useVertexTexture ) {
  8937. this.boneTexture.needsUpdate = true;
  8938. }
  8939. };
  8940. }();
  8941. THREE.SkinnedMesh.prototype.pose = function () {
  8942. this.updateMatrixWorld( true );
  8943. this.normalizeSkinWeights();
  8944. };
  8945. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  8946. if ( this.geometry instanceof THREE.Geometry ) {
  8947. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  8948. var sw = this.geometry.skinWeights[ i ];
  8949. var scale = 1.0 / sw.lengthManhattan();
  8950. if ( scale !== Infinity ) {
  8951. sw.multiplyScalar( scale );
  8952. } else {
  8953. sw.set( 1 ); // this will be normalized by the shader anyway
  8954. }
  8955. }
  8956. } else {
  8957. // skinning weights assumed to be normalized for THREE.BufferGeometry
  8958. }
  8959. };
  8960. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  8961. if ( object === undefined ) {
  8962. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  8963. }
  8964. THREE.Mesh.prototype.clone.call( this, object );
  8965. return object;
  8966. };
  8967. /**
  8968. * @author alteredq / http://alteredqualia.com/
  8969. */
  8970. THREE.MorphAnimMesh = function ( geometry, material ) {
  8971. THREE.Mesh.call( this, geometry, material );
  8972. // API
  8973. this.duration = 1000; // milliseconds
  8974. this.mirroredLoop = false;
  8975. this.time = 0;
  8976. // internals
  8977. this.lastKeyframe = 0;
  8978. this.currentKeyframe = 0;
  8979. this.direction = 1;
  8980. this.directionBackwards = false;
  8981. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  8982. };
  8983. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  8984. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  8985. this.startKeyframe = start;
  8986. this.endKeyframe = end;
  8987. this.length = this.endKeyframe - this.startKeyframe + 1;
  8988. };
  8989. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  8990. this.direction = 1;
  8991. this.directionBackwards = false;
  8992. };
  8993. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  8994. this.direction = -1;
  8995. this.directionBackwards = true;
  8996. };
  8997. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  8998. var geometry = this.geometry;
  8999. if ( ! geometry.animations ) geometry.animations = {};
  9000. var firstAnimation, animations = geometry.animations;
  9001. var pattern = /([a-z]+)(\d+)/;
  9002. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  9003. var morph = geometry.morphTargets[ i ];
  9004. var parts = morph.name.match( pattern );
  9005. if ( parts && parts.length > 1 ) {
  9006. var label = parts[ 1 ];
  9007. var num = parts[ 2 ];
  9008. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  9009. var animation = animations[ label ];
  9010. if ( i < animation.start ) animation.start = i;
  9011. if ( i > animation.end ) animation.end = i;
  9012. if ( ! firstAnimation ) firstAnimation = label;
  9013. }
  9014. }
  9015. geometry.firstAnimation = firstAnimation;
  9016. };
  9017. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  9018. if ( ! this.geometry.animations ) this.geometry.animations = {};
  9019. this.geometry.animations[ label ] = { start: start, end: end };
  9020. };
  9021. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  9022. var animation = this.geometry.animations[ label ];
  9023. if ( animation ) {
  9024. this.setFrameRange( animation.start, animation.end );
  9025. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  9026. this.time = 0;
  9027. } else {
  9028. console.warn( "animation[" + label + "] undefined" );
  9029. }
  9030. };
  9031. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  9032. var frameTime = this.duration / this.length;
  9033. this.time += this.direction * delta;
  9034. if ( this.mirroredLoop ) {
  9035. if ( this.time > this.duration || this.time < 0 ) {
  9036. this.direction *= -1;
  9037. if ( this.time > this.duration ) {
  9038. this.time = this.duration;
  9039. this.directionBackwards = true;
  9040. }
  9041. if ( this.time < 0 ) {
  9042. this.time = 0;
  9043. this.directionBackwards = false;
  9044. }
  9045. }
  9046. } else {
  9047. this.time = this.time % this.duration;
  9048. if ( this.time < 0 ) this.time += this.duration;
  9049. }
  9050. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  9051. if ( keyframe !== this.currentKeyframe ) {
  9052. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  9053. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  9054. this.morphTargetInfluences[ keyframe ] = 0;
  9055. this.lastKeyframe = this.currentKeyframe;
  9056. this.currentKeyframe = keyframe;
  9057. }
  9058. var mix = ( this.time % frameTime ) / frameTime;
  9059. if ( this.directionBackwards ) {
  9060. mix = 1 - mix;
  9061. }
  9062. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  9063. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  9064. };
  9065. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  9066. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  9067. object.duration = this.duration;
  9068. object.mirroredLoop = this.mirroredLoop;
  9069. object.time = this.time;
  9070. object.lastKeyframe = this.lastKeyframe;
  9071. object.currentKeyframe = this.currentKeyframe;
  9072. object.direction = this.direction;
  9073. object.directionBackwards = this.directionBackwards;
  9074. THREE.Mesh.prototype.clone.call( this, object );
  9075. return object;
  9076. };
  9077. /**
  9078. * @author mikael emtinger / http://gomo.se/
  9079. * @author alteredq / http://alteredqualia.com/
  9080. * @author mrdoob / http://mrdoob.com/
  9081. */
  9082. THREE.LOD = function () {
  9083. THREE.Object3D.call( this );
  9084. this.objects = [];
  9085. };
  9086. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  9087. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  9088. if ( distance === undefined ) distance = 0;
  9089. distance = Math.abs( distance );
  9090. for ( var l = 0; l < this.objects.length; l ++ ) {
  9091. if ( distance < this.objects[ l ].distance ) {
  9092. break;
  9093. }
  9094. }
  9095. this.objects.splice( l, 0, { distance: distance, object: object } );
  9096. this.add( object );
  9097. };
  9098. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  9099. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9100. if ( distance < this.objects[ i ].distance ) {
  9101. break;
  9102. }
  9103. }
  9104. return this.objects[ i - 1 ].object;
  9105. };
  9106. THREE.LOD.prototype.update = function () {
  9107. var v1 = new THREE.Vector3();
  9108. var v2 = new THREE.Vector3();
  9109. return function ( camera ) {
  9110. if ( this.objects.length > 1 ) {
  9111. v1.setFromMatrixPosition( camera.matrixWorld );
  9112. v2.setFromMatrixPosition( this.matrixWorld );
  9113. var distance = v1.distanceTo( v2 );
  9114. this.objects[ 0 ].object.visible = true;
  9115. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9116. if ( distance >= this.objects[ i ].distance ) {
  9117. this.objects[ i - 1 ].object.visible = false;
  9118. this.objects[ i ].object.visible = true;
  9119. } else {
  9120. break;
  9121. }
  9122. }
  9123. for( ; i < l; i ++ ) {
  9124. this.objects[ i ].object.visible = false;
  9125. }
  9126. }
  9127. };
  9128. }();
  9129. THREE.LOD.prototype.clone = function ( object ) {
  9130. if ( object === undefined ) object = new THREE.LOD();
  9131. THREE.Object3D.prototype.clone.call( this, object );
  9132. for ( var i = 0, l = this.objects.length; i < l; i ++ ) {
  9133. var x = this.objects[i].object.clone();
  9134. x.visible = i === 0;
  9135. object.addLevel( x, this.objects[i].distance );
  9136. }
  9137. return object;
  9138. };
  9139. /**
  9140. * @author mikael emtinger / http://gomo.se/
  9141. * @author alteredq / http://alteredqualia.com/
  9142. */
  9143. THREE.Sprite = function ( material ) {
  9144. THREE.Object3D.call( this );
  9145. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  9146. };
  9147. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  9148. /*
  9149. * Custom update matrix
  9150. */
  9151. THREE.Sprite.prototype.updateMatrix = function () {
  9152. this.matrix.compose( this.position, this.quaternion, this.scale );
  9153. this.matrixWorldNeedsUpdate = true;
  9154. };
  9155. THREE.Sprite.prototype.clone = function ( object ) {
  9156. if ( object === undefined ) object = new THREE.Sprite( this.material );
  9157. THREE.Object3D.prototype.clone.call( this, object );
  9158. return object;
  9159. };
  9160. // Backwards compatibility
  9161. THREE.Particle = THREE.Sprite;
  9162. /**
  9163. * @author mrdoob / http://mrdoob.com/
  9164. */
  9165. THREE.Scene = function () {
  9166. THREE.Object3D.call( this );
  9167. this.fog = null;
  9168. this.overrideMaterial = null;
  9169. this.autoUpdate = true; // checked by the renderer
  9170. this.matrixAutoUpdate = false;
  9171. this.__lights = [];
  9172. this.__objectsAdded = [];
  9173. this.__objectsRemoved = [];
  9174. };
  9175. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  9176. THREE.Scene.prototype.__addObject = function ( object ) {
  9177. if ( object instanceof THREE.Light ) {
  9178. if ( this.__lights.indexOf( object ) === - 1 ) {
  9179. this.__lights.push( object );
  9180. }
  9181. if ( object.target && object.target.parent === undefined ) {
  9182. this.add( object.target );
  9183. }
  9184. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  9185. this.__objectsAdded.push( object );
  9186. // check if previously removed
  9187. var i = this.__objectsRemoved.indexOf( object );
  9188. if ( i !== -1 ) {
  9189. this.__objectsRemoved.splice( i, 1 );
  9190. }
  9191. }
  9192. this.dispatchEvent( { type: 'objectAdded', object: object } );
  9193. object.dispatchEvent( { type: 'addedToScene', scene: this } );
  9194. for ( var c = 0; c < object.children.length; c ++ ) {
  9195. this.__addObject( object.children[ c ] );
  9196. }
  9197. };
  9198. THREE.Scene.prototype.__removeObject = function ( object ) {
  9199. if ( object instanceof THREE.Light ) {
  9200. var i = this.__lights.indexOf( object );
  9201. if ( i !== -1 ) {
  9202. this.__lights.splice( i, 1 );
  9203. }
  9204. if ( object.shadowCascadeArray ) {
  9205. for ( var x = 0; x < object.shadowCascadeArray.length; x ++ ) {
  9206. this.__removeObject( object.shadowCascadeArray[ x ] );
  9207. }
  9208. }
  9209. } else if ( !( object instanceof THREE.Camera ) ) {
  9210. this.__objectsRemoved.push( object );
  9211. // check if previously added
  9212. var i = this.__objectsAdded.indexOf( object );
  9213. if ( i !== -1 ) {
  9214. this.__objectsAdded.splice( i, 1 );
  9215. }
  9216. }
  9217. this.dispatchEvent( { type: 'objectRemoved', object: object } );
  9218. object.dispatchEvent( { type: 'removedFromScene', scene: this } );
  9219. for ( var c = 0; c < object.children.length; c ++ ) {
  9220. this.__removeObject( object.children[ c ] );
  9221. }
  9222. };
  9223. THREE.Scene.prototype.clone = function ( object ) {
  9224. if ( object === undefined ) object = new THREE.Scene();
  9225. THREE.Object3D.prototype.clone.call(this, object);
  9226. if ( this.fog !== null ) object.fog = this.fog.clone();
  9227. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  9228. object.autoUpdate = this.autoUpdate;
  9229. object.matrixAutoUpdate = this.matrixAutoUpdate;
  9230. return object;
  9231. };
  9232. /**
  9233. * @author mrdoob / http://mrdoob.com/
  9234. * @author alteredq / http://alteredqualia.com/
  9235. */
  9236. THREE.Fog = function ( color, near, far ) {
  9237. this.name = '';
  9238. this.color = new THREE.Color( color );
  9239. this.near = ( near !== undefined ) ? near : 1;
  9240. this.far = ( far !== undefined ) ? far : 1000;
  9241. };
  9242. THREE.Fog.prototype.clone = function () {
  9243. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  9244. };
  9245. /**
  9246. * @author mrdoob / http://mrdoob.com/
  9247. * @author alteredq / http://alteredqualia.com/
  9248. */
  9249. THREE.FogExp2 = function ( color, density ) {
  9250. this.name = '';
  9251. this.color = new THREE.Color( color );
  9252. this.density = ( density !== undefined ) ? density : 0.00025;
  9253. };
  9254. THREE.FogExp2.prototype.clone = function () {
  9255. return new THREE.FogExp2( this.color.getHex(), this.density );
  9256. };
  9257. /**
  9258. * @author mrdoob / http://mrdoob.com/
  9259. */
  9260. THREE.CanvasRenderer = function ( parameters ) {
  9261. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  9262. var smoothstep = THREE.Math.smoothstep;
  9263. parameters = parameters || {};
  9264. var _this = this,
  9265. _renderData, _elements, _lights,
  9266. _projector = new THREE.Projector(),
  9267. _canvas = parameters.canvas !== undefined
  9268. ? parameters.canvas
  9269. : document.createElement( 'canvas' ),
  9270. _canvasWidth = _canvas.width,
  9271. _canvasHeight = _canvas.height,
  9272. _canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
  9273. _canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
  9274. _context = _canvas.getContext( '2d' ),
  9275. _clearColor = new THREE.Color( 0x000000 ),
  9276. _clearAlpha = 0,
  9277. _contextGlobalAlpha = 1,
  9278. _contextGlobalCompositeOperation = 0,
  9279. _contextStrokeStyle = null,
  9280. _contextFillStyle = null,
  9281. _contextLineWidth = null,
  9282. _contextLineCap = null,
  9283. _contextLineJoin = null,
  9284. _contextDashSize = null,
  9285. _contextGapSize = 0,
  9286. _camera,
  9287. _v1, _v2, _v3, _v4,
  9288. _v5 = new THREE.RenderableVertex(),
  9289. _v6 = new THREE.RenderableVertex(),
  9290. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  9291. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  9292. _color = new THREE.Color(),
  9293. _color1 = new THREE.Color(),
  9294. _color2 = new THREE.Color(),
  9295. _color3 = new THREE.Color(),
  9296. _color4 = new THREE.Color(),
  9297. _diffuseColor = new THREE.Color(),
  9298. _emissiveColor = new THREE.Color(),
  9299. _lightColor = new THREE.Color(),
  9300. _patterns = {},
  9301. _near, _far,
  9302. _image, _uvs,
  9303. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  9304. _clipBox = new THREE.Box2(),
  9305. _clearBox = new THREE.Box2(),
  9306. _elemBox = new THREE.Box2(),
  9307. _ambientLight = new THREE.Color(),
  9308. _directionalLights = new THREE.Color(),
  9309. _pointLights = new THREE.Color(),
  9310. _vector3 = new THREE.Vector3(), // Needed for PointLight
  9311. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  9312. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  9313. _pixelMap = document.createElement( 'canvas' );
  9314. _pixelMap.width = _pixelMap.height = 2;
  9315. _pixelMapContext = _pixelMap.getContext( '2d' );
  9316. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  9317. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  9318. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  9319. _pixelMapData = _pixelMapImage.data;
  9320. _gradientMap = document.createElement( 'canvas' );
  9321. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  9322. _gradientMapContext = _gradientMap.getContext( '2d' );
  9323. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  9324. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  9325. _gradientMapQuality --; // Fix UVs
  9326. // dash+gap fallbacks for Firefox and everything else
  9327. if ( _context.setLineDash === undefined ) {
  9328. if ( _context.mozDash !== undefined ) {
  9329. _context.setLineDash = function ( values ) {
  9330. _context.mozDash = values[ 0 ] !== null ? values : null;
  9331. }
  9332. } else {
  9333. _context.setLineDash = function () {}
  9334. }
  9335. }
  9336. this.domElement = _canvas;
  9337. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  9338. ? parameters.devicePixelRatio
  9339. : self.devicePixelRatio !== undefined
  9340. ? self.devicePixelRatio
  9341. : 1;
  9342. this.autoClear = true;
  9343. this.sortObjects = true;
  9344. this.sortElements = true;
  9345. this.info = {
  9346. render: {
  9347. vertices: 0,
  9348. faces: 0
  9349. }
  9350. }
  9351. // WebGLRenderer compatibility
  9352. this.supportsVertexTextures = function () {};
  9353. this.setFaceCulling = function () {};
  9354. this.setSize = function ( width, height, updateStyle ) {
  9355. _canvasWidth = width * this.devicePixelRatio;
  9356. _canvasHeight = height * this.devicePixelRatio;
  9357. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  9358. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  9359. _canvas.width = _canvasWidth;
  9360. _canvas.height = _canvasHeight;
  9361. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  9362. _canvas.style.width = width + 'px';
  9363. _canvas.style.height = height + 'px';
  9364. }
  9365. _clipBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf ),
  9366. _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9367. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9368. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9369. _contextGlobalAlpha = 1;
  9370. _contextGlobalCompositeOperation = 0;
  9371. _contextStrokeStyle = null;
  9372. _contextFillStyle = null;
  9373. _contextLineWidth = null;
  9374. _contextLineCap = null;
  9375. _contextLineJoin = null;
  9376. };
  9377. this.setClearColor = function ( color, alpha ) {
  9378. _clearColor.set( color );
  9379. _clearAlpha = alpha !== undefined ? alpha : 1;
  9380. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9381. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9382. };
  9383. this.setClearColorHex = function ( hex, alpha ) {
  9384. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  9385. this.setClearColor( hex, alpha );
  9386. };
  9387. this.getMaxAnisotropy = function () {
  9388. return 0;
  9389. };
  9390. this.clear = function () {
  9391. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  9392. if ( _clearBox.empty() === false ) {
  9393. _clearBox.intersect( _clipBox );
  9394. _clearBox.expandByScalar( 2 );
  9395. if ( _clearAlpha < 1 ) {
  9396. _context.clearRect(
  9397. _clearBox.min.x | 0,
  9398. _clearBox.min.y | 0,
  9399. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9400. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9401. );
  9402. }
  9403. if ( _clearAlpha > 0 ) {
  9404. setBlending( THREE.NormalBlending );
  9405. setOpacity( 1 );
  9406. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  9407. _context.fillRect(
  9408. _clearBox.min.x | 0,
  9409. _clearBox.min.y | 0,
  9410. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9411. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9412. );
  9413. }
  9414. _clearBox.makeEmpty();
  9415. }
  9416. };
  9417. // compatibility
  9418. this.clearColor = function () {};
  9419. this.clearDepth = function () {};
  9420. this.clearStencil = function () {};
  9421. this.render = function ( scene, camera ) {
  9422. if ( camera instanceof THREE.Camera === false ) {
  9423. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  9424. return;
  9425. }
  9426. if ( this.autoClear === true ) this.clear();
  9427. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  9428. _this.info.render.vertices = 0;
  9429. _this.info.render.faces = 0;
  9430. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  9431. _elements = _renderData.elements;
  9432. _lights = _renderData.lights;
  9433. _camera = camera;
  9434. /* DEBUG
  9435. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  9436. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  9437. */
  9438. calculateLights();
  9439. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  9440. var element = _elements[ e ];
  9441. var material = element.material;
  9442. if ( material === undefined || material.visible === false ) continue;
  9443. _elemBox.makeEmpty();
  9444. if ( element instanceof THREE.RenderableSprite ) {
  9445. _v1 = element;
  9446. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  9447. renderSprite( _v1, element, material );
  9448. } else if ( element instanceof THREE.RenderableLine ) {
  9449. _v1 = element.v1; _v2 = element.v2;
  9450. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9451. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9452. _elemBox.setFromPoints( [
  9453. _v1.positionScreen,
  9454. _v2.positionScreen
  9455. ] );
  9456. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9457. renderLine( _v1, _v2, element, material );
  9458. }
  9459. } else if ( element instanceof THREE.RenderableFace3 ) {
  9460. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  9461. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  9462. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  9463. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  9464. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9465. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9466. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  9467. if ( material.overdraw > 0 ) {
  9468. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  9469. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  9470. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  9471. }
  9472. _elemBox.setFromPoints( [
  9473. _v1.positionScreen,
  9474. _v2.positionScreen,
  9475. _v3.positionScreen
  9476. ] );
  9477. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9478. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  9479. }
  9480. }
  9481. /* DEBUG
  9482. setLineWidth( 1 );
  9483. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  9484. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  9485. */
  9486. _clearBox.union( _elemBox );
  9487. }
  9488. /* DEBUG
  9489. setLineWidth( 1 );
  9490. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  9491. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  9492. */
  9493. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  9494. };
  9495. //
  9496. function calculateLights() {
  9497. _ambientLight.setRGB( 0, 0, 0 );
  9498. _directionalLights.setRGB( 0, 0, 0 );
  9499. _pointLights.setRGB( 0, 0, 0 );
  9500. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9501. var light = _lights[ l ];
  9502. var lightColor = light.color;
  9503. if ( light instanceof THREE.AmbientLight ) {
  9504. _ambientLight.add( lightColor );
  9505. } else if ( light instanceof THREE.DirectionalLight ) {
  9506. // for sprites
  9507. _directionalLights.add( lightColor );
  9508. } else if ( light instanceof THREE.PointLight ) {
  9509. // for sprites
  9510. _pointLights.add( lightColor );
  9511. }
  9512. }
  9513. }
  9514. function calculateLight( position, normal, color ) {
  9515. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9516. var light = _lights[ l ];
  9517. _lightColor.copy( light.color );
  9518. if ( light instanceof THREE.DirectionalLight ) {
  9519. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld ).normalize();
  9520. var amount = normal.dot( lightPosition );
  9521. if ( amount <= 0 ) continue;
  9522. amount *= light.intensity;
  9523. color.add( _lightColor.multiplyScalar( amount ) );
  9524. } else if ( light instanceof THREE.PointLight ) {
  9525. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld );
  9526. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  9527. if ( amount <= 0 ) continue;
  9528. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  9529. if ( amount == 0 ) continue;
  9530. amount *= light.intensity;
  9531. color.add( _lightColor.multiplyScalar( amount ) );
  9532. }
  9533. }
  9534. }
  9535. function renderSprite( v1, element, material ) {
  9536. setOpacity( material.opacity );
  9537. setBlending( material.blending );
  9538. var scaleX = element.scale.x * _canvasWidthHalf;
  9539. var scaleY = element.scale.y * _canvasHeightHalf;
  9540. var dist = 0.5 * Math.sqrt( scaleX * scaleX + scaleY * scaleY ); // allow for rotated sprite
  9541. _elemBox.min.set( v1.x - dist, v1.y - dist );
  9542. _elemBox.max.set( v1.x + dist, v1.y + dist );
  9543. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9544. _elemBox.makeEmpty();
  9545. return;
  9546. }
  9547. if ( material instanceof THREE.SpriteMaterial ||
  9548. material instanceof THREE.ParticleSystemMaterial ) { // Backwards compatibility
  9549. var texture = material.map;
  9550. if ( texture !== null ) {
  9551. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  9552. if ( texture.image !== undefined && texture.image.width > 0 ) {
  9553. textureToPattern( texture );
  9554. }
  9555. texture.addEventListener( 'update', onTextureUpdate );
  9556. }
  9557. var pattern = _patterns[ texture.id ];
  9558. if ( pattern !== undefined ) {
  9559. setFillStyle( pattern );
  9560. } else {
  9561. setFillStyle( 'rgba( 0, 0, 0, 1 )' );
  9562. }
  9563. //
  9564. var bitmap = texture.image;
  9565. var ox = bitmap.width * texture.offset.x;
  9566. var oy = bitmap.height * texture.offset.y;
  9567. var sx = bitmap.width * texture.repeat.x;
  9568. var sy = bitmap.height * texture.repeat.y;
  9569. var cx = scaleX / sx;
  9570. var cy = scaleY / sy;
  9571. _context.save();
  9572. _context.translate( v1.x, v1.y );
  9573. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9574. _context.translate( - scaleX / 2, - scaleY / 2 );
  9575. _context.scale( cx, cy );
  9576. _context.translate( - ox, - oy );
  9577. _context.fillRect( ox, oy, sx, sy );
  9578. _context.restore();
  9579. } else { // no texture
  9580. setFillStyle( material.color.getStyle() );
  9581. _context.save();
  9582. _context.translate( v1.x, v1.y );
  9583. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9584. _context.scale( scaleX, - scaleY );
  9585. _context.fillRect( - 0.5, - 0.5, 1, 1 );
  9586. _context.restore();
  9587. }
  9588. } else if ( material instanceof THREE.SpriteCanvasMaterial ) {
  9589. setStrokeStyle( material.color.getStyle() );
  9590. setFillStyle( material.color.getStyle() );
  9591. _context.save();
  9592. _context.translate( v1.x, v1.y );
  9593. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9594. _context.scale( scaleX, scaleY );
  9595. material.program( _context );
  9596. _context.restore();
  9597. }
  9598. /* DEBUG
  9599. setStrokeStyle( 'rgb(255,255,0)' );
  9600. _context.beginPath();
  9601. _context.moveTo( v1.x - 10, v1.y );
  9602. _context.lineTo( v1.x + 10, v1.y );
  9603. _context.moveTo( v1.x, v1.y - 10 );
  9604. _context.lineTo( v1.x, v1.y + 10 );
  9605. _context.stroke();
  9606. */
  9607. }
  9608. function renderLine( v1, v2, element, material ) {
  9609. setOpacity( material.opacity );
  9610. setBlending( material.blending );
  9611. _context.beginPath();
  9612. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  9613. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  9614. if ( material instanceof THREE.LineBasicMaterial ) {
  9615. setLineWidth( material.linewidth );
  9616. setLineCap( material.linecap );
  9617. setLineJoin( material.linejoin );
  9618. if ( material.vertexColors !== THREE.VertexColors ) {
  9619. setStrokeStyle( material.color.getStyle() );
  9620. } else {
  9621. var colorStyle1 = element.vertexColors[0].getStyle();
  9622. var colorStyle2 = element.vertexColors[1].getStyle();
  9623. if ( colorStyle1 === colorStyle2 ) {
  9624. setStrokeStyle( colorStyle1 );
  9625. } else {
  9626. try {
  9627. var grad = _context.createLinearGradient(
  9628. v1.positionScreen.x,
  9629. v1.positionScreen.y,
  9630. v2.positionScreen.x,
  9631. v2.positionScreen.y
  9632. );
  9633. grad.addColorStop( 0, colorStyle1 );
  9634. grad.addColorStop( 1, colorStyle2 );
  9635. } catch ( exception ) {
  9636. grad = colorStyle1;
  9637. }
  9638. setStrokeStyle( grad );
  9639. }
  9640. }
  9641. _context.stroke();
  9642. _elemBox.expandByScalar( material.linewidth * 2 );
  9643. } else if ( material instanceof THREE.LineDashedMaterial ) {
  9644. setLineWidth( material.linewidth );
  9645. setLineCap( material.linecap );
  9646. setLineJoin( material.linejoin );
  9647. setStrokeStyle( material.color.getStyle() );
  9648. setDashAndGap( material.dashSize, material.gapSize );
  9649. _context.stroke();
  9650. _elemBox.expandByScalar( material.linewidth * 2 );
  9651. setDashAndGap( null, null );
  9652. }
  9653. }
  9654. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  9655. _this.info.render.vertices += 3;
  9656. _this.info.render.faces ++;
  9657. setOpacity( material.opacity );
  9658. setBlending( material.blending );
  9659. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9660. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9661. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9662. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  9663. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  9664. _diffuseColor.copy( material.color );
  9665. _emissiveColor.copy( material.emissive );
  9666. if ( material.vertexColors === THREE.FaceColors ) {
  9667. _diffuseColor.multiply( element.color );
  9668. }
  9669. if ( material.wireframe === false && material.shading === THREE.SmoothShading && element.vertexNormalsLength === 3 ) {
  9670. _color1.copy( _ambientLight );
  9671. _color2.copy( _ambientLight );
  9672. _color3.copy( _ambientLight );
  9673. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  9674. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  9675. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  9676. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  9677. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  9678. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  9679. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9680. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9681. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9682. } else {
  9683. _color.copy( _ambientLight );
  9684. calculateLight( element.centroidModel, element.normalModel, _color );
  9685. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9686. material.wireframe === true
  9687. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9688. : fillPath( _color );
  9689. }
  9690. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9691. if ( material.map !== null ) {
  9692. if ( material.map.mapping instanceof THREE.UVMapping ) {
  9693. _uvs = element.uvs[ 0 ];
  9694. 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 );
  9695. }
  9696. } else if ( material.envMap !== null ) {
  9697. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  9698. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  9699. _uv1x = 0.5 * _vector3.x + 0.5;
  9700. _uv1y = 0.5 * _vector3.y + 0.5;
  9701. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  9702. _uv2x = 0.5 * _vector3.x + 0.5;
  9703. _uv2y = 0.5 * _vector3.y + 0.5;
  9704. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  9705. _uv3x = 0.5 * _vector3.x + 0.5;
  9706. _uv3y = 0.5 * _vector3.y + 0.5;
  9707. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9708. }/* else if ( material.envMap.mapping === THREE.SphericalRefractionMapping ) {
  9709. }*/
  9710. } else {
  9711. _color.copy( material.color );
  9712. if ( material.vertexColors === THREE.FaceColors ) {
  9713. _color.multiply( element.color );
  9714. }
  9715. material.wireframe === true
  9716. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9717. : fillPath( _color );
  9718. }
  9719. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9720. _near = _camera.near;
  9721. _far = _camera.far;
  9722. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  9723. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  9724. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  9725. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9726. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9727. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9728. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9729. var normal;
  9730. if ( material.shading === THREE.FlatShading ) {
  9731. normal = element.normalModelView;
  9732. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9733. material.wireframe === true
  9734. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9735. : fillPath( _color );
  9736. } else if ( material.shading === THREE.SmoothShading ) {
  9737. normal = element.vertexNormalsModelView[ uv1 ];
  9738. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9739. normal = element.vertexNormalsModelView[ uv2 ];
  9740. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9741. normal = element.vertexNormalsModelView[ uv3 ];
  9742. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9743. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9744. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9745. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9746. }
  9747. }
  9748. }
  9749. //
  9750. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  9751. _context.beginPath();
  9752. _context.moveTo( x0, y0 );
  9753. _context.lineTo( x1, y1 );
  9754. _context.lineTo( x2, y2 );
  9755. _context.closePath();
  9756. }
  9757. function strokePath( color, linewidth, linecap, linejoin ) {
  9758. setLineWidth( linewidth );
  9759. setLineCap( linecap );
  9760. setLineJoin( linejoin );
  9761. setStrokeStyle( color.getStyle() );
  9762. _context.stroke();
  9763. _elemBox.expandByScalar( linewidth * 2 );
  9764. }
  9765. function fillPath( color ) {
  9766. setFillStyle( color.getStyle() );
  9767. _context.fill();
  9768. }
  9769. function onTextureUpdate ( event ) {
  9770. textureToPattern( event.target );
  9771. }
  9772. function textureToPattern( texture ) {
  9773. var repeatX = texture.wrapS === THREE.RepeatWrapping;
  9774. var repeatY = texture.wrapT === THREE.RepeatWrapping;
  9775. var image = texture.image;
  9776. var canvas = document.createElement( 'canvas' );
  9777. canvas.width = image.width;
  9778. canvas.height = image.height;
  9779. var context = canvas.getContext( '2d' );
  9780. context.setTransform( 1, 0, 0, - 1, 0, image.height );
  9781. context.drawImage( image, 0, 0 );
  9782. _patterns[ texture.id ] = _context.createPattern(
  9783. canvas, repeatX === true && repeatY === true
  9784. ? 'repeat'
  9785. : repeatX === true && repeatY === false
  9786. ? 'repeat-x'
  9787. : repeatX === false && repeatY === true
  9788. ? 'repeat-y'
  9789. : 'no-repeat'
  9790. );
  9791. }
  9792. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  9793. if ( texture instanceof THREE.DataTexture ) return;
  9794. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  9795. if ( texture.image !== undefined && texture.image.width > 0 ) {
  9796. textureToPattern( texture );
  9797. }
  9798. texture.addEventListener( 'update', onTextureUpdate );
  9799. }
  9800. var pattern = _patterns[ texture.id ];
  9801. if ( pattern !== undefined ) {
  9802. setFillStyle( pattern );
  9803. } else {
  9804. setFillStyle( 'rgba(0,0,0,1)' );
  9805. _context.fill();
  9806. return;
  9807. }
  9808. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9809. var a, b, c, d, e, f, det, idet,
  9810. offsetX = texture.offset.x / texture.repeat.x,
  9811. offsetY = texture.offset.y / texture.repeat.y,
  9812. width = texture.image.width * texture.repeat.x,
  9813. height = texture.image.height * texture.repeat.y;
  9814. u0 = ( u0 + offsetX ) * width;
  9815. v0 = ( v0 + offsetY ) * height;
  9816. u1 = ( u1 + offsetX ) * width;
  9817. v1 = ( v1 + offsetY ) * height;
  9818. u2 = ( u2 + offsetX ) * width;
  9819. v2 = ( v2 + offsetY ) * height;
  9820. x1 -= x0; y1 -= y0;
  9821. x2 -= x0; y2 -= y0;
  9822. u1 -= u0; v1 -= v0;
  9823. u2 -= u0; v2 -= v0;
  9824. det = u1 * v2 - u2 * v1;
  9825. if ( det === 0 ) return;
  9826. idet = 1 / det;
  9827. a = ( v2 * x1 - v1 * x2 ) * idet;
  9828. b = ( v2 * y1 - v1 * y2 ) * idet;
  9829. c = ( u1 * x2 - u2 * x1 ) * idet;
  9830. d = ( u1 * y2 - u2 * y1 ) * idet;
  9831. e = x0 - a * u0 - c * v0;
  9832. f = y0 - b * u0 - d * v0;
  9833. _context.save();
  9834. _context.transform( a, b, c, d, e, f );
  9835. _context.fill();
  9836. _context.restore();
  9837. }
  9838. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  9839. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9840. var a, b, c, d, e, f, det, idet,
  9841. width = image.width - 1,
  9842. height = image.height - 1;
  9843. u0 *= width; v0 *= height;
  9844. u1 *= width; v1 *= height;
  9845. u2 *= width; v2 *= height;
  9846. x1 -= x0; y1 -= y0;
  9847. x2 -= x0; y2 -= y0;
  9848. u1 -= u0; v1 -= v0;
  9849. u2 -= u0; v2 -= v0;
  9850. det = u1 * v2 - u2 * v1;
  9851. idet = 1 / det;
  9852. a = ( v2 * x1 - v1 * x2 ) * idet;
  9853. b = ( v2 * y1 - v1 * y2 ) * idet;
  9854. c = ( u1 * x2 - u2 * x1 ) * idet;
  9855. d = ( u1 * y2 - u2 * y1 ) * idet;
  9856. e = x0 - a * u0 - c * v0;
  9857. f = y0 - b * u0 - d * v0;
  9858. _context.save();
  9859. _context.transform( a, b, c, d, e, f );
  9860. _context.clip();
  9861. _context.drawImage( image, 0, 0 );
  9862. _context.restore();
  9863. }
  9864. function getGradientTexture( color1, color2, color3, color4 ) {
  9865. // http://mrdoob.com/blog/post/710
  9866. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  9867. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  9868. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  9869. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  9870. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  9871. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  9872. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  9873. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  9874. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  9875. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  9876. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  9877. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  9878. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  9879. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  9880. return _gradientMap;
  9881. }
  9882. // Hide anti-alias gaps
  9883. function expand( v1, v2, pixels ) {
  9884. var x = v2.x - v1.x, y = v2.y - v1.y,
  9885. det = x * x + y * y, idet;
  9886. if ( det === 0 ) return;
  9887. idet = pixels / Math.sqrt( det );
  9888. x *= idet; y *= idet;
  9889. v2.x += x; v2.y += y;
  9890. v1.x -= x; v1.y -= y;
  9891. }
  9892. // Context cached methods.
  9893. function setOpacity( value ) {
  9894. if ( _contextGlobalAlpha !== value ) {
  9895. _context.globalAlpha = value;
  9896. _contextGlobalAlpha = value;
  9897. }
  9898. }
  9899. function setBlending( value ) {
  9900. if ( _contextGlobalCompositeOperation !== value ) {
  9901. if ( value === THREE.NormalBlending ) {
  9902. _context.globalCompositeOperation = 'source-over';
  9903. } else if ( value === THREE.AdditiveBlending ) {
  9904. _context.globalCompositeOperation = 'lighter';
  9905. } else if ( value === THREE.SubtractiveBlending ) {
  9906. _context.globalCompositeOperation = 'darker';
  9907. }
  9908. _contextGlobalCompositeOperation = value;
  9909. }
  9910. }
  9911. function setLineWidth( value ) {
  9912. if ( _contextLineWidth !== value ) {
  9913. _context.lineWidth = value;
  9914. _contextLineWidth = value;
  9915. }
  9916. }
  9917. function setLineCap( value ) {
  9918. // "butt", "round", "square"
  9919. if ( _contextLineCap !== value ) {
  9920. _context.lineCap = value;
  9921. _contextLineCap = value;
  9922. }
  9923. }
  9924. function setLineJoin( value ) {
  9925. // "round", "bevel", "miter"
  9926. if ( _contextLineJoin !== value ) {
  9927. _context.lineJoin = value;
  9928. _contextLineJoin = value;
  9929. }
  9930. }
  9931. function setStrokeStyle( value ) {
  9932. if ( _contextStrokeStyle !== value ) {
  9933. _context.strokeStyle = value;
  9934. _contextStrokeStyle = value;
  9935. }
  9936. }
  9937. function setFillStyle( value ) {
  9938. if ( _contextFillStyle !== value ) {
  9939. _context.fillStyle = value;
  9940. _contextFillStyle = value;
  9941. }
  9942. }
  9943. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  9944. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  9945. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  9946. _contextDashSize = dashSizeValue;
  9947. _contextGapSize = gapSizeValue;
  9948. }
  9949. }
  9950. };
  9951. /**
  9952. * Shader chunks for WebLG Shader library
  9953. *
  9954. * @author alteredq / http://alteredqualia.com/
  9955. * @author mrdoob / http://mrdoob.com/
  9956. * @author mikael emtinger / http://gomo.se/
  9957. */
  9958. THREE.ShaderChunk = {
  9959. // FOG
  9960. fog_pars_fragment: [
  9961. "#ifdef USE_FOG",
  9962. "uniform vec3 fogColor;",
  9963. "#ifdef FOG_EXP2",
  9964. "uniform float fogDensity;",
  9965. "#else",
  9966. "uniform float fogNear;",
  9967. "uniform float fogFar;",
  9968. "#endif",
  9969. "#endif"
  9970. ].join("\n"),
  9971. fog_fragment: [
  9972. "#ifdef USE_FOG",
  9973. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9974. "#ifdef FOG_EXP2",
  9975. "const float LOG2 = 1.442695;",
  9976. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  9977. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  9978. "#else",
  9979. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  9980. "#endif",
  9981. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  9982. "#endif"
  9983. ].join("\n"),
  9984. // ENVIRONMENT MAP
  9985. envmap_pars_fragment: [
  9986. "#ifdef USE_ENVMAP",
  9987. "uniform float reflectivity;",
  9988. "uniform samplerCube envMap;",
  9989. "uniform float flipEnvMap;",
  9990. "uniform int combine;",
  9991. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9992. "uniform bool useRefract;",
  9993. "uniform float refractionRatio;",
  9994. "#else",
  9995. "varying vec3 vReflect;",
  9996. "#endif",
  9997. "#endif"
  9998. ].join("\n"),
  9999. envmap_fragment: [
  10000. "#ifdef USE_ENVMAP",
  10001. "vec3 reflectVec;",
  10002. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  10003. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  10004. "if ( useRefract ) {",
  10005. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  10006. "} else { ",
  10007. "reflectVec = reflect( cameraToVertex, normal );",
  10008. "}",
  10009. "#else",
  10010. "reflectVec = vReflect;",
  10011. "#endif",
  10012. "#ifdef DOUBLE_SIDED",
  10013. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10014. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  10015. "#else",
  10016. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  10017. "#endif",
  10018. "#ifdef GAMMA_INPUT",
  10019. "cubeColor.xyz *= cubeColor.xyz;",
  10020. "#endif",
  10021. "if ( combine == 1 ) {",
  10022. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  10023. "} else if ( combine == 2 ) {",
  10024. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  10025. "} else {",
  10026. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  10027. "}",
  10028. "#endif"
  10029. ].join("\n"),
  10030. envmap_pars_vertex: [
  10031. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  10032. "varying vec3 vReflect;",
  10033. "uniform float refractionRatio;",
  10034. "uniform bool useRefract;",
  10035. "#endif"
  10036. ].join("\n"),
  10037. worldpos_vertex : [
  10038. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  10039. "#ifdef USE_SKINNING",
  10040. "vec4 worldPosition = modelMatrix * skinned;",
  10041. "#endif",
  10042. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  10043. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  10044. "#endif",
  10045. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  10046. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  10047. "#endif",
  10048. "#endif"
  10049. ].join("\n"),
  10050. envmap_vertex : [
  10051. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  10052. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  10053. "worldNormal = normalize( worldNormal );",
  10054. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  10055. "if ( useRefract ) {",
  10056. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  10057. "} else {",
  10058. "vReflect = reflect( cameraToVertex, worldNormal );",
  10059. "}",
  10060. "#endif"
  10061. ].join("\n"),
  10062. // COLOR MAP (particles)
  10063. map_particle_pars_fragment: [
  10064. "#ifdef USE_MAP",
  10065. "uniform sampler2D map;",
  10066. "#endif"
  10067. ].join("\n"),
  10068. map_particle_fragment: [
  10069. "#ifdef USE_MAP",
  10070. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  10071. "#endif"
  10072. ].join("\n"),
  10073. // COLOR MAP (triangles)
  10074. map_pars_vertex: [
  10075. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10076. "varying vec2 vUv;",
  10077. "uniform vec4 offsetRepeat;",
  10078. "#endif"
  10079. ].join("\n"),
  10080. map_pars_fragment: [
  10081. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10082. "varying vec2 vUv;",
  10083. "#endif",
  10084. "#ifdef USE_MAP",
  10085. "uniform sampler2D map;",
  10086. "#endif"
  10087. ].join("\n"),
  10088. map_vertex: [
  10089. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10090. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  10091. "#endif"
  10092. ].join("\n"),
  10093. map_fragment: [
  10094. "#ifdef USE_MAP",
  10095. "vec4 texelColor = texture2D( map, vUv );",
  10096. "#ifdef GAMMA_INPUT",
  10097. "texelColor.xyz *= texelColor.xyz;",
  10098. "#endif",
  10099. "gl_FragColor = gl_FragColor * texelColor;",
  10100. "#endif"
  10101. ].join("\n"),
  10102. // LIGHT MAP
  10103. lightmap_pars_fragment: [
  10104. "#ifdef USE_LIGHTMAP",
  10105. "varying vec2 vUv2;",
  10106. "uniform sampler2D lightMap;",
  10107. "#endif"
  10108. ].join("\n"),
  10109. lightmap_pars_vertex: [
  10110. "#ifdef USE_LIGHTMAP",
  10111. "varying vec2 vUv2;",
  10112. "#endif"
  10113. ].join("\n"),
  10114. lightmap_fragment: [
  10115. "#ifdef USE_LIGHTMAP",
  10116. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  10117. "#endif"
  10118. ].join("\n"),
  10119. lightmap_vertex: [
  10120. "#ifdef USE_LIGHTMAP",
  10121. "vUv2 = uv2;",
  10122. "#endif"
  10123. ].join("\n"),
  10124. // BUMP MAP
  10125. bumpmap_pars_fragment: [
  10126. "#ifdef USE_BUMPMAP",
  10127. "uniform sampler2D bumpMap;",
  10128. "uniform float bumpScale;",
  10129. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  10130. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  10131. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10132. "vec2 dHdxy_fwd() {",
  10133. "vec2 dSTdx = dFdx( vUv );",
  10134. "vec2 dSTdy = dFdy( vUv );",
  10135. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  10136. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  10137. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  10138. "return vec2( dBx, dBy );",
  10139. "}",
  10140. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  10141. "vec3 vSigmaX = dFdx( surf_pos );",
  10142. "vec3 vSigmaY = dFdy( surf_pos );",
  10143. "vec3 vN = surf_norm;", // normalized
  10144. "vec3 R1 = cross( vSigmaY, vN );",
  10145. "vec3 R2 = cross( vN, vSigmaX );",
  10146. "float fDet = dot( vSigmaX, R1 );",
  10147. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  10148. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  10149. "}",
  10150. "#endif"
  10151. ].join("\n"),
  10152. // NORMAL MAP
  10153. normalmap_pars_fragment: [
  10154. "#ifdef USE_NORMALMAP",
  10155. "uniform sampler2D normalMap;",
  10156. "uniform vec2 normalScale;",
  10157. // Per-Pixel Tangent Space Normal Mapping
  10158. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  10159. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  10160. "vec3 q0 = dFdx( eye_pos.xyz );",
  10161. "vec3 q1 = dFdy( eye_pos.xyz );",
  10162. "vec2 st0 = dFdx( vUv.st );",
  10163. "vec2 st1 = dFdy( vUv.st );",
  10164. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  10165. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  10166. "vec3 N = normalize( surf_norm );",
  10167. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  10168. "mapN.xy = normalScale * mapN.xy;",
  10169. "mat3 tsn = mat3( S, T, N );",
  10170. "return normalize( tsn * mapN );",
  10171. "}",
  10172. "#endif"
  10173. ].join("\n"),
  10174. // SPECULAR MAP
  10175. specularmap_pars_fragment: [
  10176. "#ifdef USE_SPECULARMAP",
  10177. "uniform sampler2D specularMap;",
  10178. "#endif"
  10179. ].join("\n"),
  10180. specularmap_fragment: [
  10181. "float specularStrength;",
  10182. "#ifdef USE_SPECULARMAP",
  10183. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  10184. "specularStrength = texelSpecular.r;",
  10185. "#else",
  10186. "specularStrength = 1.0;",
  10187. "#endif"
  10188. ].join("\n"),
  10189. // LIGHTS LAMBERT
  10190. lights_lambert_pars_vertex: [
  10191. "uniform vec3 ambient;",
  10192. "uniform vec3 diffuse;",
  10193. "uniform vec3 emissive;",
  10194. "uniform vec3 ambientLightColor;",
  10195. "#if MAX_DIR_LIGHTS > 0",
  10196. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10197. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10198. "#endif",
  10199. "#if MAX_HEMI_LIGHTS > 0",
  10200. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10201. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10202. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10203. "#endif",
  10204. "#if MAX_POINT_LIGHTS > 0",
  10205. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10206. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10207. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10208. "#endif",
  10209. "#if MAX_SPOT_LIGHTS > 0",
  10210. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10211. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10212. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10213. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10214. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10215. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10216. "#endif",
  10217. "#ifdef WRAP_AROUND",
  10218. "uniform vec3 wrapRGB;",
  10219. "#endif"
  10220. ].join("\n"),
  10221. lights_lambert_vertex: [
  10222. "vLightFront = vec3( 0.0 );",
  10223. "#ifdef DOUBLE_SIDED",
  10224. "vLightBack = vec3( 0.0 );",
  10225. "#endif",
  10226. "transformedNormal = normalize( transformedNormal );",
  10227. "#if MAX_DIR_LIGHTS > 0",
  10228. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10229. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10230. "vec3 dirVector = normalize( lDirection.xyz );",
  10231. "float dotProduct = dot( transformedNormal, dirVector );",
  10232. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10233. "#ifdef DOUBLE_SIDED",
  10234. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10235. "#ifdef WRAP_AROUND",
  10236. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10237. "#endif",
  10238. "#endif",
  10239. "#ifdef WRAP_AROUND",
  10240. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10241. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  10242. "#ifdef DOUBLE_SIDED",
  10243. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  10244. "#endif",
  10245. "#endif",
  10246. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  10247. "#ifdef DOUBLE_SIDED",
  10248. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  10249. "#endif",
  10250. "}",
  10251. "#endif",
  10252. "#if MAX_POINT_LIGHTS > 0",
  10253. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10254. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10255. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10256. "float lDistance = 1.0;",
  10257. "if ( pointLightDistance[ i ] > 0.0 )",
  10258. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10259. "lVector = normalize( lVector );",
  10260. "float dotProduct = dot( transformedNormal, lVector );",
  10261. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10262. "#ifdef DOUBLE_SIDED",
  10263. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10264. "#ifdef WRAP_AROUND",
  10265. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10266. "#endif",
  10267. "#endif",
  10268. "#ifdef WRAP_AROUND",
  10269. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10270. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  10271. "#ifdef DOUBLE_SIDED",
  10272. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  10273. "#endif",
  10274. "#endif",
  10275. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  10276. "#ifdef DOUBLE_SIDED",
  10277. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  10278. "#endif",
  10279. "}",
  10280. "#endif",
  10281. "#if MAX_SPOT_LIGHTS > 0",
  10282. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10283. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10284. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10285. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  10286. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10287. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10288. "float lDistance = 1.0;",
  10289. "if ( spotLightDistance[ i ] > 0.0 )",
  10290. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10291. "lVector = normalize( lVector );",
  10292. "float dotProduct = dot( transformedNormal, lVector );",
  10293. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10294. "#ifdef DOUBLE_SIDED",
  10295. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10296. "#ifdef WRAP_AROUND",
  10297. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10298. "#endif",
  10299. "#endif",
  10300. "#ifdef WRAP_AROUND",
  10301. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10302. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  10303. "#ifdef DOUBLE_SIDED",
  10304. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  10305. "#endif",
  10306. "#endif",
  10307. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  10308. "#ifdef DOUBLE_SIDED",
  10309. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  10310. "#endif",
  10311. "}",
  10312. "}",
  10313. "#endif",
  10314. "#if MAX_HEMI_LIGHTS > 0",
  10315. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10316. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10317. "vec3 lVector = normalize( lDirection.xyz );",
  10318. "float dotProduct = dot( transformedNormal, lVector );",
  10319. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10320. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  10321. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10322. "#ifdef DOUBLE_SIDED",
  10323. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  10324. "#endif",
  10325. "}",
  10326. "#endif",
  10327. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  10328. "#ifdef DOUBLE_SIDED",
  10329. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  10330. "#endif"
  10331. ].join("\n"),
  10332. // LIGHTS PHONG
  10333. lights_phong_pars_vertex: [
  10334. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10335. "varying vec3 vWorldPosition;",
  10336. "#endif"
  10337. ].join("\n"),
  10338. lights_phong_vertex: [
  10339. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10340. "vWorldPosition = worldPosition.xyz;",
  10341. "#endif"
  10342. ].join("\n"),
  10343. lights_phong_pars_fragment: [
  10344. "uniform vec3 ambientLightColor;",
  10345. "#if MAX_DIR_LIGHTS > 0",
  10346. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10347. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10348. "#endif",
  10349. "#if MAX_HEMI_LIGHTS > 0",
  10350. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10351. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10352. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10353. "#endif",
  10354. "#if MAX_POINT_LIGHTS > 0",
  10355. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10356. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10357. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10358. "#endif",
  10359. "#if MAX_SPOT_LIGHTS > 0",
  10360. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10361. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10362. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10363. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10364. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10365. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10366. "#endif",
  10367. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10368. "varying vec3 vWorldPosition;",
  10369. "#endif",
  10370. "#ifdef WRAP_AROUND",
  10371. "uniform vec3 wrapRGB;",
  10372. "#endif",
  10373. "varying vec3 vViewPosition;",
  10374. "varying vec3 vNormal;"
  10375. ].join("\n"),
  10376. lights_phong_fragment: [
  10377. "vec3 normal = normalize( vNormal );",
  10378. "vec3 viewPosition = normalize( vViewPosition );",
  10379. "#ifdef DOUBLE_SIDED",
  10380. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10381. "#endif",
  10382. "#ifdef USE_NORMALMAP",
  10383. "normal = perturbNormal2Arb( -vViewPosition, normal );",
  10384. "#elif defined( USE_BUMPMAP )",
  10385. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  10386. "#endif",
  10387. "#if MAX_POINT_LIGHTS > 0",
  10388. "vec3 pointDiffuse = vec3( 0.0 );",
  10389. "vec3 pointSpecular = vec3( 0.0 );",
  10390. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10391. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10392. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10393. "float lDistance = 1.0;",
  10394. "if ( pointLightDistance[ i ] > 0.0 )",
  10395. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10396. "lVector = normalize( lVector );",
  10397. // diffuse
  10398. "float dotProduct = dot( normal, lVector );",
  10399. "#ifdef WRAP_AROUND",
  10400. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  10401. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10402. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10403. "#else",
  10404. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  10405. "#endif",
  10406. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  10407. // specular
  10408. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  10409. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10410. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  10411. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10412. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10413. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  10414. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  10415. "}",
  10416. "#endif",
  10417. "#if MAX_SPOT_LIGHTS > 0",
  10418. "vec3 spotDiffuse = vec3( 0.0 );",
  10419. "vec3 spotSpecular = vec3( 0.0 );",
  10420. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10421. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10422. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10423. "float lDistance = 1.0;",
  10424. "if ( spotLightDistance[ i ] > 0.0 )",
  10425. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10426. "lVector = normalize( lVector );",
  10427. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10428. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10429. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10430. // diffuse
  10431. "float dotProduct = dot( normal, lVector );",
  10432. "#ifdef WRAP_AROUND",
  10433. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  10434. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10435. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10436. "#else",
  10437. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  10438. "#endif",
  10439. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  10440. // specular
  10441. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  10442. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10443. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  10444. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10445. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10446. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  10447. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  10448. "}",
  10449. "}",
  10450. "#endif",
  10451. "#if MAX_DIR_LIGHTS > 0",
  10452. "vec3 dirDiffuse = vec3( 0.0 );",
  10453. "vec3 dirSpecular = vec3( 0.0 );" ,
  10454. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10455. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10456. "vec3 dirVector = normalize( lDirection.xyz );",
  10457. // diffuse
  10458. "float dotProduct = dot( normal, dirVector );",
  10459. "#ifdef WRAP_AROUND",
  10460. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  10461. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10462. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  10463. "#else",
  10464. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  10465. "#endif",
  10466. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  10467. // specular
  10468. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10469. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10470. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  10471. /*
  10472. // fresnel term from skin shader
  10473. "const float F0 = 0.128;",
  10474. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  10475. "float exponential = pow( base, 5.0 );",
  10476. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  10477. */
  10478. /*
  10479. // fresnel term from fresnel shader
  10480. "const float mFresnelBias = 0.08;",
  10481. "const float mFresnelScale = 0.3;",
  10482. "const float mFresnelPower = 5.0;",
  10483. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  10484. */
  10485. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10486. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10487. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  10488. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10489. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10490. "}",
  10491. "#endif",
  10492. "#if MAX_HEMI_LIGHTS > 0",
  10493. "vec3 hemiDiffuse = vec3( 0.0 );",
  10494. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10495. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10496. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10497. "vec3 lVector = normalize( lDirection.xyz );",
  10498. // diffuse
  10499. "float dotProduct = dot( normal, lVector );",
  10500. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10501. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10502. "hemiDiffuse += diffuse * hemiColor;",
  10503. // specular (sky light)
  10504. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10505. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10506. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  10507. // specular (ground light)
  10508. "vec3 lVectorGround = -lVector;",
  10509. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10510. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10511. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  10512. "float dotProductGround = dot( normal, lVectorGround );",
  10513. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10514. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10515. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10516. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10517. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10518. "}",
  10519. "#endif",
  10520. "vec3 totalDiffuse = vec3( 0.0 );",
  10521. "vec3 totalSpecular = vec3( 0.0 );",
  10522. "#if MAX_DIR_LIGHTS > 0",
  10523. "totalDiffuse += dirDiffuse;",
  10524. "totalSpecular += dirSpecular;",
  10525. "#endif",
  10526. "#if MAX_HEMI_LIGHTS > 0",
  10527. "totalDiffuse += hemiDiffuse;",
  10528. "totalSpecular += hemiSpecular;",
  10529. "#endif",
  10530. "#if MAX_POINT_LIGHTS > 0",
  10531. "totalDiffuse += pointDiffuse;",
  10532. "totalSpecular += pointSpecular;",
  10533. "#endif",
  10534. "#if MAX_SPOT_LIGHTS > 0",
  10535. "totalDiffuse += spotDiffuse;",
  10536. "totalSpecular += spotSpecular;",
  10537. "#endif",
  10538. "#ifdef METAL",
  10539. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  10540. "#else",
  10541. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  10542. "#endif"
  10543. ].join("\n"),
  10544. // VERTEX COLORS
  10545. color_pars_fragment: [
  10546. "#ifdef USE_COLOR",
  10547. "varying vec3 vColor;",
  10548. "#endif"
  10549. ].join("\n"),
  10550. color_fragment: [
  10551. "#ifdef USE_COLOR",
  10552. "gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );",
  10553. "#endif"
  10554. ].join("\n"),
  10555. color_pars_vertex: [
  10556. "#ifdef USE_COLOR",
  10557. "varying vec3 vColor;",
  10558. "#endif"
  10559. ].join("\n"),
  10560. color_vertex: [
  10561. "#ifdef USE_COLOR",
  10562. "#ifdef GAMMA_INPUT",
  10563. "vColor = color * color;",
  10564. "#else",
  10565. "vColor = color;",
  10566. "#endif",
  10567. "#endif"
  10568. ].join("\n"),
  10569. // SKINNING
  10570. skinning_pars_vertex: [
  10571. "#ifdef USE_SKINNING",
  10572. "#ifdef BONE_TEXTURE",
  10573. "uniform sampler2D boneTexture;",
  10574. "uniform int boneTextureWidth;",
  10575. "uniform int boneTextureHeight;",
  10576. "mat4 getBoneMatrix( const in float i ) {",
  10577. "float j = i * 4.0;",
  10578. "float x = mod( j, float( boneTextureWidth ) );",
  10579. "float y = floor( j / float( boneTextureWidth ) );",
  10580. "float dx = 1.0 / float( boneTextureWidth );",
  10581. "float dy = 1.0 / float( boneTextureHeight );",
  10582. "y = dy * ( y + 0.5 );",
  10583. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  10584. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  10585. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  10586. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  10587. "mat4 bone = mat4( v1, v2, v3, v4 );",
  10588. "return bone;",
  10589. "}",
  10590. "#else",
  10591. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  10592. "mat4 getBoneMatrix( const in float i ) {",
  10593. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  10594. "return bone;",
  10595. "}",
  10596. "#endif",
  10597. "#endif"
  10598. ].join("\n"),
  10599. skinbase_vertex: [
  10600. "#ifdef USE_SKINNING",
  10601. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  10602. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  10603. "mat4 boneMatZ = getBoneMatrix( skinIndex.z );",
  10604. "mat4 boneMatW = getBoneMatrix( skinIndex.w );",
  10605. "#endif"
  10606. ].join("\n"),
  10607. skinning_vertex: [
  10608. "#ifdef USE_SKINNING",
  10609. "#ifdef USE_MORPHTARGETS",
  10610. "vec4 skinVertex = vec4( morphed, 1.0 );",
  10611. "#else",
  10612. "vec4 skinVertex = vec4( position, 1.0 );",
  10613. "#endif",
  10614. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10615. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10616. "skinned += boneMatZ * skinVertex * skinWeight.z;",
  10617. "skinned += boneMatW * skinVertex * skinWeight.w;",
  10618. "#endif"
  10619. ].join("\n"),
  10620. // MORPHING
  10621. morphtarget_pars_vertex: [
  10622. "#ifdef USE_MORPHTARGETS",
  10623. "#ifndef USE_MORPHNORMALS",
  10624. "uniform float morphTargetInfluences[ 8 ];",
  10625. "#else",
  10626. "uniform float morphTargetInfluences[ 4 ];",
  10627. "#endif",
  10628. "#endif"
  10629. ].join("\n"),
  10630. morphtarget_vertex: [
  10631. "#ifdef USE_MORPHTARGETS",
  10632. "vec3 morphed = vec3( 0.0 );",
  10633. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  10634. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  10635. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  10636. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  10637. "#ifndef USE_MORPHNORMALS",
  10638. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  10639. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  10640. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  10641. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  10642. "#endif",
  10643. "morphed += position;",
  10644. "#endif"
  10645. ].join("\n"),
  10646. default_vertex : [
  10647. "vec4 mvPosition;",
  10648. "#ifdef USE_SKINNING",
  10649. "mvPosition = modelViewMatrix * skinned;",
  10650. "#endif",
  10651. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  10652. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  10653. "#endif",
  10654. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  10655. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10656. "#endif",
  10657. "gl_Position = projectionMatrix * mvPosition;"
  10658. ].join("\n"),
  10659. morphnormal_vertex: [
  10660. "#ifdef USE_MORPHNORMALS",
  10661. "vec3 morphedNormal = vec3( 0.0 );",
  10662. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  10663. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  10664. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  10665. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  10666. "morphedNormal += normal;",
  10667. "#endif"
  10668. ].join("\n"),
  10669. skinnormal_vertex: [
  10670. "#ifdef USE_SKINNING",
  10671. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  10672. "skinMatrix += skinWeight.y * boneMatY;",
  10673. "#ifdef USE_MORPHNORMALS",
  10674. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  10675. "#else",
  10676. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  10677. "#endif",
  10678. "#endif"
  10679. ].join("\n"),
  10680. defaultnormal_vertex: [
  10681. "vec3 objectNormal;",
  10682. "#ifdef USE_SKINNING",
  10683. "objectNormal = skinnedNormal.xyz;",
  10684. "#endif",
  10685. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  10686. "objectNormal = morphedNormal;",
  10687. "#endif",
  10688. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  10689. "objectNormal = normal;",
  10690. "#endif",
  10691. "#ifdef FLIP_SIDED",
  10692. "objectNormal = -objectNormal;",
  10693. "#endif",
  10694. "vec3 transformedNormal = normalMatrix * objectNormal;"
  10695. ].join("\n"),
  10696. // SHADOW MAP
  10697. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  10698. // http://spidergl.org/example.php?id=6
  10699. // http://fabiensanglard.net/shadowmapping
  10700. shadowmap_pars_fragment: [
  10701. "#ifdef USE_SHADOWMAP",
  10702. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  10703. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  10704. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  10705. "uniform float shadowBias[ MAX_SHADOWS ];",
  10706. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10707. "float unpackDepth( const in vec4 rgba_depth ) {",
  10708. "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 );",
  10709. "float depth = dot( rgba_depth, bit_shift );",
  10710. "return depth;",
  10711. "}",
  10712. "#endif"
  10713. ].join("\n"),
  10714. shadowmap_fragment: [
  10715. "#ifdef USE_SHADOWMAP",
  10716. "#ifdef SHADOWMAP_DEBUG",
  10717. "vec3 frustumColors[3];",
  10718. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  10719. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  10720. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  10721. "#endif",
  10722. "#ifdef SHADOWMAP_CASCADE",
  10723. "int inFrustumCount = 0;",
  10724. "#endif",
  10725. "float fDepth;",
  10726. "vec3 shadowColor = vec3( 1.0 );",
  10727. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10728. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  10729. // "if ( something && something )" breaks ATI OpenGL shader compiler
  10730. // "if ( all( something, something ) )" using this instead
  10731. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  10732. "bool inFrustum = all( inFrustumVec );",
  10733. // don't shadow pixels outside of light frustum
  10734. // use just first frustum (for cascades)
  10735. // don't shadow pixels behind far plane of light frustum
  10736. "#ifdef SHADOWMAP_CASCADE",
  10737. "inFrustumCount += int( inFrustum );",
  10738. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  10739. "#else",
  10740. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  10741. "#endif",
  10742. "bool frustumTest = all( frustumTestVec );",
  10743. "if ( frustumTest ) {",
  10744. "shadowCoord.z += shadowBias[ i ];",
  10745. "#if defined( SHADOWMAP_TYPE_PCF )",
  10746. // Percentage-close filtering
  10747. // (9 pixel kernel)
  10748. // http://fabiensanglard.net/shadowmappingPCF/
  10749. "float shadow = 0.0;",
  10750. /*
  10751. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  10752. // must enroll loop manually
  10753. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  10754. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  10755. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  10756. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  10757. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  10758. "float fDepth = unpackDepth( rgbaDepth );",
  10759. "if ( fDepth < shadowCoord.z )",
  10760. "shadow += 1.0;",
  10761. "}",
  10762. "shadow /= 9.0;",
  10763. */
  10764. "const float shadowDelta = 1.0 / 9.0;",
  10765. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10766. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10767. "float dx0 = -1.25 * xPixelOffset;",
  10768. "float dy0 = -1.25 * yPixelOffset;",
  10769. "float dx1 = 1.25 * xPixelOffset;",
  10770. "float dy1 = 1.25 * yPixelOffset;",
  10771. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10772. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10773. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10774. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10775. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10776. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10777. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10778. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10779. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10780. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10781. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10782. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10783. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10784. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10785. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10786. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10787. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10788. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10789. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10790. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  10791. // Percentage-close filtering
  10792. // (9 pixel kernel)
  10793. // http://fabiensanglard.net/shadowmappingPCF/
  10794. "float shadow = 0.0;",
  10795. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10796. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10797. "float dx0 = -1.0 * xPixelOffset;",
  10798. "float dy0 = -1.0 * yPixelOffset;",
  10799. "float dx1 = 1.0 * xPixelOffset;",
  10800. "float dy1 = 1.0 * yPixelOffset;",
  10801. "mat3 shadowKernel;",
  10802. "mat3 depthKernel;",
  10803. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10804. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10805. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10806. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10807. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10808. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10809. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10810. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10811. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10812. "vec3 shadowZ = vec3( shadowCoord.z );",
  10813. "shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  10814. "shadowKernel[0] *= vec3(0.25);",
  10815. "shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  10816. "shadowKernel[1] *= vec3(0.25);",
  10817. "shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  10818. "shadowKernel[2] *= vec3(0.25);",
  10819. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  10820. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  10821. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  10822. "vec4 shadowValues;",
  10823. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  10824. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  10825. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  10826. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  10827. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  10828. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10829. "#else",
  10830. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  10831. "float fDepth = unpackDepth( rgbaDepth );",
  10832. "if ( fDepth < shadowCoord.z )",
  10833. // spot with multiple shadows is darker
  10834. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  10835. // spot with multiple shadows has the same color as single shadow spot
  10836. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  10837. "#endif",
  10838. "}",
  10839. "#ifdef SHADOWMAP_DEBUG",
  10840. "#ifdef SHADOWMAP_CASCADE",
  10841. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  10842. "#else",
  10843. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  10844. "#endif",
  10845. "#endif",
  10846. "}",
  10847. "#ifdef GAMMA_OUTPUT",
  10848. "shadowColor *= shadowColor;",
  10849. "#endif",
  10850. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  10851. "#endif"
  10852. ].join("\n"),
  10853. shadowmap_pars_vertex: [
  10854. "#ifdef USE_SHADOWMAP",
  10855. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10856. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  10857. "#endif"
  10858. ].join("\n"),
  10859. shadowmap_vertex: [
  10860. "#ifdef USE_SHADOWMAP",
  10861. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10862. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10863. "}",
  10864. "#endif"
  10865. ].join("\n"),
  10866. // ALPHATEST
  10867. alphatest_fragment: [
  10868. "#ifdef ALPHATEST",
  10869. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  10870. "#endif"
  10871. ].join("\n"),
  10872. // LINEAR SPACE
  10873. linear_to_gamma_fragment: [
  10874. "#ifdef GAMMA_OUTPUT",
  10875. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  10876. "#endif"
  10877. ].join("\n")
  10878. };
  10879. /**
  10880. * Uniform Utilities
  10881. */
  10882. THREE.UniformsUtils = {
  10883. merge: function ( uniforms ) {
  10884. var u, p, tmp, merged = {};
  10885. for ( u = 0; u < uniforms.length; u ++ ) {
  10886. tmp = this.clone( uniforms[ u ] );
  10887. for ( p in tmp ) {
  10888. merged[ p ] = tmp[ p ];
  10889. }
  10890. }
  10891. return merged;
  10892. },
  10893. clone: function ( uniforms_src ) {
  10894. var u, p, parameter, parameter_src, uniforms_dst = {};
  10895. for ( u in uniforms_src ) {
  10896. uniforms_dst[ u ] = {};
  10897. for ( p in uniforms_src[ u ] ) {
  10898. parameter_src = uniforms_src[ u ][ p ];
  10899. if ( parameter_src instanceof THREE.Color ||
  10900. parameter_src instanceof THREE.Vector2 ||
  10901. parameter_src instanceof THREE.Vector3 ||
  10902. parameter_src instanceof THREE.Vector4 ||
  10903. parameter_src instanceof THREE.Matrix4 ||
  10904. parameter_src instanceof THREE.Texture ) {
  10905. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10906. } else if ( parameter_src instanceof Array ) {
  10907. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10908. } else {
  10909. uniforms_dst[ u ][ p ] = parameter_src;
  10910. }
  10911. }
  10912. }
  10913. return uniforms_dst;
  10914. }
  10915. };
  10916. /**
  10917. * Uniforms library for shared webgl shaders
  10918. */
  10919. THREE.UniformsLib = {
  10920. common: {
  10921. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10922. "opacity" : { type: "f", value: 1.0 },
  10923. "map" : { type: "t", value: null },
  10924. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10925. "lightMap" : { type: "t", value: null },
  10926. "specularMap" : { type: "t", value: null },
  10927. "envMap" : { type: "t", value: null },
  10928. "flipEnvMap" : { type: "f", value: -1 },
  10929. "useRefract" : { type: "i", value: 0 },
  10930. "reflectivity" : { type: "f", value: 1.0 },
  10931. "refractionRatio" : { type: "f", value: 0.98 },
  10932. "combine" : { type: "i", value: 0 },
  10933. "morphTargetInfluences" : { type: "f", value: 0 }
  10934. },
  10935. bump: {
  10936. "bumpMap" : { type: "t", value: null },
  10937. "bumpScale" : { type: "f", value: 1 }
  10938. },
  10939. normalmap: {
  10940. "normalMap" : { type: "t", value: null },
  10941. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10942. },
  10943. fog : {
  10944. "fogDensity" : { type: "f", value: 0.00025 },
  10945. "fogNear" : { type: "f", value: 1 },
  10946. "fogFar" : { type: "f", value: 2000 },
  10947. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10948. },
  10949. lights: {
  10950. "ambientLightColor" : { type: "fv", value: [] },
  10951. "directionalLightDirection" : { type: "fv", value: [] },
  10952. "directionalLightColor" : { type: "fv", value: [] },
  10953. "hemisphereLightDirection" : { type: "fv", value: [] },
  10954. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10955. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10956. "pointLightColor" : { type: "fv", value: [] },
  10957. "pointLightPosition" : { type: "fv", value: [] },
  10958. "pointLightDistance" : { type: "fv1", value: [] },
  10959. "spotLightColor" : { type: "fv", value: [] },
  10960. "spotLightPosition" : { type: "fv", value: [] },
  10961. "spotLightDirection" : { type: "fv", value: [] },
  10962. "spotLightDistance" : { type: "fv1", value: [] },
  10963. "spotLightAngleCos" : { type: "fv1", value: [] },
  10964. "spotLightExponent" : { type: "fv1", value: [] }
  10965. },
  10966. particle: {
  10967. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10968. "opacity" : { type: "f", value: 1.0 },
  10969. "size" : { type: "f", value: 1.0 },
  10970. "scale" : { type: "f", value: 1.0 },
  10971. "map" : { type: "t", value: null },
  10972. "fogDensity" : { type: "f", value: 0.00025 },
  10973. "fogNear" : { type: "f", value: 1 },
  10974. "fogFar" : { type: "f", value: 2000 },
  10975. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10976. },
  10977. shadowmap: {
  10978. "shadowMap": { type: "tv", value: [] },
  10979. "shadowMapSize": { type: "v2v", value: [] },
  10980. "shadowBias" : { type: "fv1", value: [] },
  10981. "shadowDarkness": { type: "fv1", value: [] },
  10982. "shadowMatrix" : { type: "m4v", value: [] }
  10983. }
  10984. };
  10985. /**
  10986. * Webgl Shader Library for three.js
  10987. *
  10988. * @author alteredq / http://alteredqualia.com/
  10989. * @author mrdoob / http://mrdoob.com/
  10990. * @author mikael emtinger / http://gomo.se/
  10991. */
  10992. THREE.ShaderLib = {
  10993. 'basic': {
  10994. uniforms: THREE.UniformsUtils.merge( [
  10995. THREE.UniformsLib[ "common" ],
  10996. THREE.UniformsLib[ "fog" ],
  10997. THREE.UniformsLib[ "shadowmap" ]
  10998. ] ),
  10999. vertexShader: [
  11000. THREE.ShaderChunk[ "map_pars_vertex" ],
  11001. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11002. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11003. THREE.ShaderChunk[ "color_pars_vertex" ],
  11004. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11005. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11006. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11007. "void main() {",
  11008. THREE.ShaderChunk[ "map_vertex" ],
  11009. THREE.ShaderChunk[ "lightmap_vertex" ],
  11010. THREE.ShaderChunk[ "color_vertex" ],
  11011. THREE.ShaderChunk[ "skinbase_vertex" ],
  11012. "#ifdef USE_ENVMAP",
  11013. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11014. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11015. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11016. "#endif",
  11017. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11018. THREE.ShaderChunk[ "skinning_vertex" ],
  11019. THREE.ShaderChunk[ "default_vertex" ],
  11020. THREE.ShaderChunk[ "worldpos_vertex" ],
  11021. THREE.ShaderChunk[ "envmap_vertex" ],
  11022. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11023. "}"
  11024. ].join("\n"),
  11025. fragmentShader: [
  11026. "uniform vec3 diffuse;",
  11027. "uniform float opacity;",
  11028. THREE.ShaderChunk[ "color_pars_fragment" ],
  11029. THREE.ShaderChunk[ "map_pars_fragment" ],
  11030. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11031. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11032. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11033. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11034. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11035. "void main() {",
  11036. "gl_FragColor = vec4( diffuse, opacity );",
  11037. THREE.ShaderChunk[ "map_fragment" ],
  11038. THREE.ShaderChunk[ "alphatest_fragment" ],
  11039. THREE.ShaderChunk[ "specularmap_fragment" ],
  11040. THREE.ShaderChunk[ "lightmap_fragment" ],
  11041. THREE.ShaderChunk[ "color_fragment" ],
  11042. THREE.ShaderChunk[ "envmap_fragment" ],
  11043. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11044. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11045. THREE.ShaderChunk[ "fog_fragment" ],
  11046. "}"
  11047. ].join("\n")
  11048. },
  11049. 'lambert': {
  11050. uniforms: THREE.UniformsUtils.merge( [
  11051. THREE.UniformsLib[ "common" ],
  11052. THREE.UniformsLib[ "fog" ],
  11053. THREE.UniformsLib[ "lights" ],
  11054. THREE.UniformsLib[ "shadowmap" ],
  11055. {
  11056. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11057. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11058. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11059. }
  11060. ] ),
  11061. vertexShader: [
  11062. "#define LAMBERT",
  11063. "varying vec3 vLightFront;",
  11064. "#ifdef DOUBLE_SIDED",
  11065. "varying vec3 vLightBack;",
  11066. "#endif",
  11067. THREE.ShaderChunk[ "map_pars_vertex" ],
  11068. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11069. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11070. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  11071. THREE.ShaderChunk[ "color_pars_vertex" ],
  11072. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11073. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11074. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11075. "void main() {",
  11076. THREE.ShaderChunk[ "map_vertex" ],
  11077. THREE.ShaderChunk[ "lightmap_vertex" ],
  11078. THREE.ShaderChunk[ "color_vertex" ],
  11079. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11080. THREE.ShaderChunk[ "skinbase_vertex" ],
  11081. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11082. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11083. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11084. THREE.ShaderChunk[ "skinning_vertex" ],
  11085. THREE.ShaderChunk[ "default_vertex" ],
  11086. THREE.ShaderChunk[ "worldpos_vertex" ],
  11087. THREE.ShaderChunk[ "envmap_vertex" ],
  11088. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  11089. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11090. "}"
  11091. ].join("\n"),
  11092. fragmentShader: [
  11093. "uniform float opacity;",
  11094. "varying vec3 vLightFront;",
  11095. "#ifdef DOUBLE_SIDED",
  11096. "varying vec3 vLightBack;",
  11097. "#endif",
  11098. THREE.ShaderChunk[ "color_pars_fragment" ],
  11099. THREE.ShaderChunk[ "map_pars_fragment" ],
  11100. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11101. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11102. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11103. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11104. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11105. "void main() {",
  11106. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  11107. THREE.ShaderChunk[ "map_fragment" ],
  11108. THREE.ShaderChunk[ "alphatest_fragment" ],
  11109. THREE.ShaderChunk[ "specularmap_fragment" ],
  11110. "#ifdef DOUBLE_SIDED",
  11111. //"float isFront = float( gl_FrontFacing );",
  11112. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  11113. "if ( gl_FrontFacing )",
  11114. "gl_FragColor.xyz *= vLightFront;",
  11115. "else",
  11116. "gl_FragColor.xyz *= vLightBack;",
  11117. "#else",
  11118. "gl_FragColor.xyz *= vLightFront;",
  11119. "#endif",
  11120. THREE.ShaderChunk[ "lightmap_fragment" ],
  11121. THREE.ShaderChunk[ "color_fragment" ],
  11122. THREE.ShaderChunk[ "envmap_fragment" ],
  11123. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11124. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11125. THREE.ShaderChunk[ "fog_fragment" ],
  11126. "}"
  11127. ].join("\n")
  11128. },
  11129. 'phong': {
  11130. uniforms: THREE.UniformsUtils.merge( [
  11131. THREE.UniformsLib[ "common" ],
  11132. THREE.UniformsLib[ "bump" ],
  11133. THREE.UniformsLib[ "normalmap" ],
  11134. THREE.UniformsLib[ "fog" ],
  11135. THREE.UniformsLib[ "lights" ],
  11136. THREE.UniformsLib[ "shadowmap" ],
  11137. {
  11138. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11139. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11140. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  11141. "shininess": { type: "f", value: 30 },
  11142. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11143. }
  11144. ] ),
  11145. vertexShader: [
  11146. "#define PHONG",
  11147. "varying vec3 vViewPosition;",
  11148. "varying vec3 vNormal;",
  11149. THREE.ShaderChunk[ "map_pars_vertex" ],
  11150. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11151. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11152. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  11153. THREE.ShaderChunk[ "color_pars_vertex" ],
  11154. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11155. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11156. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11157. "void main() {",
  11158. THREE.ShaderChunk[ "map_vertex" ],
  11159. THREE.ShaderChunk[ "lightmap_vertex" ],
  11160. THREE.ShaderChunk[ "color_vertex" ],
  11161. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11162. THREE.ShaderChunk[ "skinbase_vertex" ],
  11163. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11164. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11165. "vNormal = normalize( transformedNormal );",
  11166. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11167. THREE.ShaderChunk[ "skinning_vertex" ],
  11168. THREE.ShaderChunk[ "default_vertex" ],
  11169. "vViewPosition = -mvPosition.xyz;",
  11170. THREE.ShaderChunk[ "worldpos_vertex" ],
  11171. THREE.ShaderChunk[ "envmap_vertex" ],
  11172. THREE.ShaderChunk[ "lights_phong_vertex" ],
  11173. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11174. "}"
  11175. ].join("\n"),
  11176. fragmentShader: [
  11177. "uniform vec3 diffuse;",
  11178. "uniform float opacity;",
  11179. "uniform vec3 ambient;",
  11180. "uniform vec3 emissive;",
  11181. "uniform vec3 specular;",
  11182. "uniform float shininess;",
  11183. THREE.ShaderChunk[ "color_pars_fragment" ],
  11184. THREE.ShaderChunk[ "map_pars_fragment" ],
  11185. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11186. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11187. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11188. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  11189. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11190. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  11191. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  11192. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11193. "void main() {",
  11194. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  11195. THREE.ShaderChunk[ "map_fragment" ],
  11196. THREE.ShaderChunk[ "alphatest_fragment" ],
  11197. THREE.ShaderChunk[ "specularmap_fragment" ],
  11198. THREE.ShaderChunk[ "lights_phong_fragment" ],
  11199. THREE.ShaderChunk[ "lightmap_fragment" ],
  11200. THREE.ShaderChunk[ "color_fragment" ],
  11201. THREE.ShaderChunk[ "envmap_fragment" ],
  11202. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11203. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11204. THREE.ShaderChunk[ "fog_fragment" ],
  11205. "}"
  11206. ].join("\n")
  11207. },
  11208. 'particle_basic': {
  11209. uniforms: THREE.UniformsUtils.merge( [
  11210. THREE.UniformsLib[ "particle" ],
  11211. THREE.UniformsLib[ "shadowmap" ]
  11212. ] ),
  11213. vertexShader: [
  11214. "uniform float size;",
  11215. "uniform float scale;",
  11216. THREE.ShaderChunk[ "color_pars_vertex" ],
  11217. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11218. "void main() {",
  11219. THREE.ShaderChunk[ "color_vertex" ],
  11220. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11221. "#ifdef USE_SIZEATTENUATION",
  11222. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  11223. "#else",
  11224. "gl_PointSize = size;",
  11225. "#endif",
  11226. "gl_Position = projectionMatrix * mvPosition;",
  11227. THREE.ShaderChunk[ "worldpos_vertex" ],
  11228. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11229. "}"
  11230. ].join("\n"),
  11231. fragmentShader: [
  11232. "uniform vec3 psColor;",
  11233. "uniform float opacity;",
  11234. THREE.ShaderChunk[ "color_pars_fragment" ],
  11235. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  11236. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11237. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11238. "void main() {",
  11239. "gl_FragColor = vec4( psColor, opacity );",
  11240. THREE.ShaderChunk[ "map_particle_fragment" ],
  11241. THREE.ShaderChunk[ "alphatest_fragment" ],
  11242. THREE.ShaderChunk[ "color_fragment" ],
  11243. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11244. THREE.ShaderChunk[ "fog_fragment" ],
  11245. "}"
  11246. ].join("\n")
  11247. },
  11248. 'dashed': {
  11249. uniforms: THREE.UniformsUtils.merge( [
  11250. THREE.UniformsLib[ "common" ],
  11251. THREE.UniformsLib[ "fog" ],
  11252. {
  11253. "scale": { type: "f", value: 1 },
  11254. "dashSize": { type: "f", value: 1 },
  11255. "totalSize": { type: "f", value: 2 }
  11256. }
  11257. ] ),
  11258. vertexShader: [
  11259. "uniform float scale;",
  11260. "attribute float lineDistance;",
  11261. "varying float vLineDistance;",
  11262. THREE.ShaderChunk[ "color_pars_vertex" ],
  11263. "void main() {",
  11264. THREE.ShaderChunk[ "color_vertex" ],
  11265. "vLineDistance = scale * lineDistance;",
  11266. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11267. "gl_Position = projectionMatrix * mvPosition;",
  11268. "}"
  11269. ].join("\n"),
  11270. fragmentShader: [
  11271. "uniform vec3 diffuse;",
  11272. "uniform float opacity;",
  11273. "uniform float dashSize;",
  11274. "uniform float totalSize;",
  11275. "varying float vLineDistance;",
  11276. THREE.ShaderChunk[ "color_pars_fragment" ],
  11277. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11278. "void main() {",
  11279. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  11280. "discard;",
  11281. "}",
  11282. "gl_FragColor = vec4( diffuse, opacity );",
  11283. THREE.ShaderChunk[ "color_fragment" ],
  11284. THREE.ShaderChunk[ "fog_fragment" ],
  11285. "}"
  11286. ].join("\n")
  11287. },
  11288. 'depth': {
  11289. uniforms: {
  11290. "mNear": { type: "f", value: 1.0 },
  11291. "mFar" : { type: "f", value: 2000.0 },
  11292. "opacity" : { type: "f", value: 1.0 }
  11293. },
  11294. vertexShader: [
  11295. "void main() {",
  11296. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11297. "}"
  11298. ].join("\n"),
  11299. fragmentShader: [
  11300. "uniform float mNear;",
  11301. "uniform float mFar;",
  11302. "uniform float opacity;",
  11303. "void main() {",
  11304. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  11305. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  11306. "gl_FragColor = vec4( vec3( color ), opacity );",
  11307. "}"
  11308. ].join("\n")
  11309. },
  11310. 'normal': {
  11311. uniforms: {
  11312. "opacity" : { type: "f", value: 1.0 }
  11313. },
  11314. vertexShader: [
  11315. "varying vec3 vNormal;",
  11316. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11317. "void main() {",
  11318. "vNormal = normalize( normalMatrix * normal );",
  11319. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11320. THREE.ShaderChunk[ "default_vertex" ],
  11321. "}"
  11322. ].join("\n"),
  11323. fragmentShader: [
  11324. "uniform float opacity;",
  11325. "varying vec3 vNormal;",
  11326. "void main() {",
  11327. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  11328. "}"
  11329. ].join("\n")
  11330. },
  11331. /* -------------------------------------------------------------------------
  11332. // Normal map shader
  11333. // - Blinn-Phong
  11334. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  11335. // - point and directional lights (use with "lights: true" material option)
  11336. ------------------------------------------------------------------------- */
  11337. 'normalmap' : {
  11338. uniforms: THREE.UniformsUtils.merge( [
  11339. THREE.UniformsLib[ "fog" ],
  11340. THREE.UniformsLib[ "lights" ],
  11341. THREE.UniformsLib[ "shadowmap" ],
  11342. {
  11343. "enableAO" : { type: "i", value: 0 },
  11344. "enableDiffuse" : { type: "i", value: 0 },
  11345. "enableSpecular" : { type: "i", value: 0 },
  11346. "enableReflection": { type: "i", value: 0 },
  11347. "enableDisplacement": { type: "i", value: 0 },
  11348. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  11349. "tDiffuse" : { type: "t", value: null },
  11350. "tCube" : { type: "t", value: null },
  11351. "tNormal" : { type: "t", value: null },
  11352. "tSpecular" : { type: "t", value: null },
  11353. "tAO" : { type: "t", value: null },
  11354. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11355. "uDisplacementBias": { type: "f", value: 0.0 },
  11356. "uDisplacementScale": { type: "f", value: 1.0 },
  11357. "diffuse": { type: "c", value: new THREE.Color( 0xffffff ) },
  11358. "specular": { type: "c", value: new THREE.Color( 0x111111 ) },
  11359. "ambient": { type: "c", value: new THREE.Color( 0xffffff ) },
  11360. "shininess": { type: "f", value: 30 },
  11361. "opacity": { type: "f", value: 1 },
  11362. "useRefract": { type: "i", value: 0 },
  11363. "refractionRatio": { type: "f", value: 0.98 },
  11364. "reflectivity": { type: "f", value: 0.5 },
  11365. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11366. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11367. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11368. }
  11369. ] ),
  11370. fragmentShader: [
  11371. "uniform vec3 ambient;",
  11372. "uniform vec3 diffuse;",
  11373. "uniform vec3 specular;",
  11374. "uniform float shininess;",
  11375. "uniform float opacity;",
  11376. "uniform bool enableDiffuse;",
  11377. "uniform bool enableSpecular;",
  11378. "uniform bool enableAO;",
  11379. "uniform bool enableReflection;",
  11380. "uniform sampler2D tDiffuse;",
  11381. "uniform sampler2D tNormal;",
  11382. "uniform sampler2D tSpecular;",
  11383. "uniform sampler2D tAO;",
  11384. "uniform samplerCube tCube;",
  11385. "uniform vec2 uNormalScale;",
  11386. "uniform bool useRefract;",
  11387. "uniform float refractionRatio;",
  11388. "uniform float reflectivity;",
  11389. "varying vec3 vTangent;",
  11390. "varying vec3 vBinormal;",
  11391. "varying vec3 vNormal;",
  11392. "varying vec2 vUv;",
  11393. "uniform vec3 ambientLightColor;",
  11394. "#if MAX_DIR_LIGHTS > 0",
  11395. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11396. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11397. "#endif",
  11398. "#if MAX_HEMI_LIGHTS > 0",
  11399. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11400. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11401. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11402. "#endif",
  11403. "#if MAX_POINT_LIGHTS > 0",
  11404. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11405. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11406. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11407. "#endif",
  11408. "#if MAX_SPOT_LIGHTS > 0",
  11409. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11410. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11411. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11412. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11413. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11414. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11415. "#endif",
  11416. "#ifdef WRAP_AROUND",
  11417. "uniform vec3 wrapRGB;",
  11418. "#endif",
  11419. "varying vec3 vWorldPosition;",
  11420. "varying vec3 vViewPosition;",
  11421. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11422. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11423. "void main() {",
  11424. "gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11425. "vec3 specularTex = vec3( 1.0 );",
  11426. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11427. "normalTex.xy *= uNormalScale;",
  11428. "normalTex = normalize( normalTex );",
  11429. "if( enableDiffuse ) {",
  11430. "#ifdef GAMMA_INPUT",
  11431. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  11432. "texelColor.xyz *= texelColor.xyz;",
  11433. "gl_FragColor = gl_FragColor * texelColor;",
  11434. "#else",
  11435. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11436. "#endif",
  11437. "}",
  11438. "if( enableAO ) {",
  11439. "#ifdef GAMMA_INPUT",
  11440. "vec4 aoColor = texture2D( tAO, vUv );",
  11441. "aoColor.xyz *= aoColor.xyz;",
  11442. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11443. "#else",
  11444. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11445. "#endif",
  11446. "}",
  11447. "if( enableSpecular )",
  11448. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  11449. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11450. "vec3 finalNormal = tsb * normalTex;",
  11451. "#ifdef FLIP_SIDED",
  11452. "finalNormal = -finalNormal;",
  11453. "#endif",
  11454. "vec3 normal = normalize( finalNormal );",
  11455. "vec3 viewPosition = normalize( vViewPosition );",
  11456. // point lights
  11457. "#if MAX_POINT_LIGHTS > 0",
  11458. "vec3 pointDiffuse = vec3( 0.0 );",
  11459. "vec3 pointSpecular = vec3( 0.0 );",
  11460. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11461. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11462. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  11463. "float pointDistance = 1.0;",
  11464. "if ( pointLightDistance[ i ] > 0.0 )",
  11465. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  11466. "pointVector = normalize( pointVector );",
  11467. // diffuse
  11468. "#ifdef WRAP_AROUND",
  11469. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11470. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11471. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11472. "#else",
  11473. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11474. "#endif",
  11475. "pointDiffuse += pointDistance * pointLightColor[ i ] * diffuse * pointDiffuseWeight;",
  11476. // specular
  11477. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11478. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11479. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  11480. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11481. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11482. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11483. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11484. "}",
  11485. "#endif",
  11486. // spot lights
  11487. "#if MAX_SPOT_LIGHTS > 0",
  11488. "vec3 spotDiffuse = vec3( 0.0 );",
  11489. "vec3 spotSpecular = vec3( 0.0 );",
  11490. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11491. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11492. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  11493. "float spotDistance = 1.0;",
  11494. "if ( spotLightDistance[ i ] > 0.0 )",
  11495. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  11496. "spotVector = normalize( spotVector );",
  11497. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11498. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11499. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11500. // diffuse
  11501. "#ifdef WRAP_AROUND",
  11502. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  11503. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  11504. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11505. "#else",
  11506. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  11507. "#endif",
  11508. "spotDiffuse += spotDistance * spotLightColor[ i ] * diffuse * spotDiffuseWeight * spotEffect;",
  11509. // specular
  11510. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  11511. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11512. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  11513. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11514. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11515. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  11516. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  11517. "}",
  11518. "}",
  11519. "#endif",
  11520. // directional lights
  11521. "#if MAX_DIR_LIGHTS > 0",
  11522. "vec3 dirDiffuse = vec3( 0.0 );",
  11523. "vec3 dirSpecular = vec3( 0.0 );",
  11524. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11525. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11526. "vec3 dirVector = normalize( lDirection.xyz );",
  11527. // diffuse
  11528. "#ifdef WRAP_AROUND",
  11529. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11530. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11531. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11532. "#else",
  11533. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11534. "#endif",
  11535. "dirDiffuse += directionalLightColor[ i ] * diffuse * dirDiffuseWeight;",
  11536. // specular
  11537. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11538. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11539. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  11540. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11541. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11542. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11543. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11544. "}",
  11545. "#endif",
  11546. // hemisphere lights
  11547. "#if MAX_HEMI_LIGHTS > 0",
  11548. "vec3 hemiDiffuse = vec3( 0.0 );",
  11549. "vec3 hemiSpecular = vec3( 0.0 );" ,
  11550. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11551. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11552. "vec3 lVector = normalize( lDirection.xyz );",
  11553. // diffuse
  11554. "float dotProduct = dot( normal, lVector );",
  11555. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11556. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11557. "hemiDiffuse += diffuse * hemiColor;",
  11558. // specular (sky light)
  11559. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11560. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11561. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  11562. // specular (ground light)
  11563. "vec3 lVectorGround = -lVector;",
  11564. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11565. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11566. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  11567. "float dotProductGround = dot( normal, lVectorGround );",
  11568. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11569. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11570. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  11571. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  11572. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11573. "}",
  11574. "#endif",
  11575. // all lights contribution summation
  11576. "vec3 totalDiffuse = vec3( 0.0 );",
  11577. "vec3 totalSpecular = vec3( 0.0 );",
  11578. "#if MAX_DIR_LIGHTS > 0",
  11579. "totalDiffuse += dirDiffuse;",
  11580. "totalSpecular += dirSpecular;",
  11581. "#endif",
  11582. "#if MAX_HEMI_LIGHTS > 0",
  11583. "totalDiffuse += hemiDiffuse;",
  11584. "totalSpecular += hemiSpecular;",
  11585. "#endif",
  11586. "#if MAX_POINT_LIGHTS > 0",
  11587. "totalDiffuse += pointDiffuse;",
  11588. "totalSpecular += pointSpecular;",
  11589. "#endif",
  11590. "#if MAX_SPOT_LIGHTS > 0",
  11591. "totalDiffuse += spotDiffuse;",
  11592. "totalSpecular += spotSpecular;",
  11593. "#endif",
  11594. "#ifdef METAL",
  11595. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  11596. "#else",
  11597. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  11598. "#endif",
  11599. "if ( enableReflection ) {",
  11600. "vec3 vReflect;",
  11601. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  11602. "if ( useRefract ) {",
  11603. "vReflect = refract( cameraToVertex, normal, refractionRatio );",
  11604. "} else {",
  11605. "vReflect = reflect( cameraToVertex, normal );",
  11606. "}",
  11607. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11608. "#ifdef GAMMA_INPUT",
  11609. "cubeColor.xyz *= cubeColor.xyz;",
  11610. "#endif",
  11611. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * reflectivity );",
  11612. "}",
  11613. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11614. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11615. THREE.ShaderChunk[ "fog_fragment" ],
  11616. "}"
  11617. ].join("\n"),
  11618. vertexShader: [
  11619. "attribute vec4 tangent;",
  11620. "uniform vec2 uOffset;",
  11621. "uniform vec2 uRepeat;",
  11622. "uniform bool enableDisplacement;",
  11623. "#ifdef VERTEX_TEXTURES",
  11624. "uniform sampler2D tDisplacement;",
  11625. "uniform float uDisplacementScale;",
  11626. "uniform float uDisplacementBias;",
  11627. "#endif",
  11628. "varying vec3 vTangent;",
  11629. "varying vec3 vBinormal;",
  11630. "varying vec3 vNormal;",
  11631. "varying vec2 vUv;",
  11632. "varying vec3 vWorldPosition;",
  11633. "varying vec3 vViewPosition;",
  11634. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11635. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11636. "void main() {",
  11637. THREE.ShaderChunk[ "skinbase_vertex" ],
  11638. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11639. // normal, tangent and binormal vectors
  11640. "#ifdef USE_SKINNING",
  11641. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  11642. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  11643. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  11644. "#else",
  11645. "vNormal = normalize( normalMatrix * normal );",
  11646. "vTangent = normalize( normalMatrix * tangent.xyz );",
  11647. "#endif",
  11648. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  11649. "vUv = uv * uRepeat + uOffset;",
  11650. // displacement mapping
  11651. "vec3 displacedPosition;",
  11652. "#ifdef VERTEX_TEXTURES",
  11653. "if ( enableDisplacement ) {",
  11654. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11655. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11656. "displacedPosition = position + normalize( normal ) * df;",
  11657. "} else {",
  11658. "#ifdef USE_SKINNING",
  11659. "vec4 skinVertex = vec4( position, 1.0 );",
  11660. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11661. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11662. "displacedPosition = skinned.xyz;",
  11663. "#else",
  11664. "displacedPosition = position;",
  11665. "#endif",
  11666. "}",
  11667. "#else",
  11668. "#ifdef USE_SKINNING",
  11669. "vec4 skinVertex = vec4( position, 1.0 );",
  11670. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11671. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11672. "displacedPosition = skinned.xyz;",
  11673. "#else",
  11674. "displacedPosition = position;",
  11675. "#endif",
  11676. "#endif",
  11677. //
  11678. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  11679. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  11680. "gl_Position = projectionMatrix * mvPosition;",
  11681. //
  11682. "vWorldPosition = worldPosition.xyz;",
  11683. "vViewPosition = -mvPosition.xyz;",
  11684. // shadows
  11685. "#ifdef USE_SHADOWMAP",
  11686. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11687. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11688. "}",
  11689. "#endif",
  11690. "}"
  11691. ].join("\n")
  11692. },
  11693. /* -------------------------------------------------------------------------
  11694. // Cube map shader
  11695. ------------------------------------------------------------------------- */
  11696. 'cube': {
  11697. uniforms: { "tCube": { type: "t", value: null },
  11698. "tFlip": { type: "f", value: -1 } },
  11699. vertexShader: [
  11700. "varying vec3 vWorldPosition;",
  11701. "void main() {",
  11702. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  11703. "vWorldPosition = worldPosition.xyz;",
  11704. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11705. "}"
  11706. ].join("\n"),
  11707. fragmentShader: [
  11708. "uniform samplerCube tCube;",
  11709. "uniform float tFlip;",
  11710. "varying vec3 vWorldPosition;",
  11711. "void main() {",
  11712. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11713. "}"
  11714. ].join("\n")
  11715. },
  11716. // Depth encoding into RGBA texture
  11717. // based on SpiderGL shadow map example
  11718. // http://spidergl.org/example.php?id=6
  11719. // originally from
  11720. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11721. // see also here:
  11722. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11723. 'depthRGBA': {
  11724. uniforms: {},
  11725. vertexShader: [
  11726. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11727. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11728. "void main() {",
  11729. THREE.ShaderChunk[ "skinbase_vertex" ],
  11730. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11731. THREE.ShaderChunk[ "skinning_vertex" ],
  11732. THREE.ShaderChunk[ "default_vertex" ],
  11733. "}"
  11734. ].join("\n"),
  11735. fragmentShader: [
  11736. "vec4 pack_depth( const in float depth ) {",
  11737. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11738. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11739. "vec4 res = fract( depth * bit_shift );",
  11740. "res -= res.xxyz * bit_mask;",
  11741. "return res;",
  11742. "}",
  11743. "void main() {",
  11744. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  11745. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  11746. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  11747. //"gl_FragData[ 0 ] = pack_depth( z );",
  11748. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  11749. "}"
  11750. ].join("\n")
  11751. }
  11752. };
  11753. /**
  11754. * @author supereggbert / http://www.paulbrunt.co.uk/
  11755. * @author mrdoob / http://mrdoob.com/
  11756. * @author alteredq / http://alteredqualia.com/
  11757. * @author szimek / https://github.com/szimek/
  11758. */
  11759. THREE.WebGLRenderer = function ( parameters ) {
  11760. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  11761. parameters = parameters || {};
  11762. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11763. _context = parameters.context !== undefined ? parameters.context : null,
  11764. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  11765. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11766. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11767. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11768. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11769. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  11770. _clearColor = new THREE.Color( 0x000000 ),
  11771. _clearAlpha = 0;
  11772. // public properties
  11773. this.domElement = _canvas;
  11774. this.context = null;
  11775. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  11776. ? parameters.devicePixelRatio
  11777. : self.devicePixelRatio !== undefined
  11778. ? self.devicePixelRatio
  11779. : 1;
  11780. // clearing
  11781. this.autoClear = true;
  11782. this.autoClearColor = true;
  11783. this.autoClearDepth = true;
  11784. this.autoClearStencil = true;
  11785. // scene graph
  11786. this.sortObjects = true;
  11787. this.autoUpdateObjects = true;
  11788. // physically based shading
  11789. this.gammaInput = false;
  11790. this.gammaOutput = false;
  11791. // shadow map
  11792. this.shadowMapEnabled = false;
  11793. this.shadowMapAutoUpdate = true;
  11794. this.shadowMapType = THREE.PCFShadowMap;
  11795. this.shadowMapCullFace = THREE.CullFaceFront;
  11796. this.shadowMapDebug = false;
  11797. this.shadowMapCascade = false;
  11798. // morphs
  11799. this.maxMorphTargets = 8;
  11800. this.maxMorphNormals = 4;
  11801. // flags
  11802. this.autoScaleCubemaps = true;
  11803. // custom render plugins
  11804. this.renderPluginsPre = [];
  11805. this.renderPluginsPost = [];
  11806. // info
  11807. this.info = {
  11808. memory: {
  11809. programs: 0,
  11810. geometries: 0,
  11811. textures: 0
  11812. },
  11813. render: {
  11814. calls: 0,
  11815. vertices: 0,
  11816. faces: 0,
  11817. points: 0
  11818. }
  11819. };
  11820. // internal properties
  11821. var _this = this,
  11822. _programs = [],
  11823. _programs_counter = 0,
  11824. // internal state cache
  11825. _currentProgram = null,
  11826. _currentFramebuffer = null,
  11827. _currentMaterialId = -1,
  11828. _currentGeometryGroupHash = null,
  11829. _currentCamera = null,
  11830. _geometryGroupCounter = 0,
  11831. _usedTextureUnits = 0,
  11832. // GL state cache
  11833. _oldDoubleSided = -1,
  11834. _oldFlipSided = -1,
  11835. _oldBlending = -1,
  11836. _oldBlendEquation = -1,
  11837. _oldBlendSrc = -1,
  11838. _oldBlendDst = -1,
  11839. _oldDepthTest = -1,
  11840. _oldDepthWrite = -1,
  11841. _oldPolygonOffset = null,
  11842. _oldPolygonOffsetFactor = null,
  11843. _oldPolygonOffsetUnits = null,
  11844. _oldLineWidth = null,
  11845. _viewportX = 0,
  11846. _viewportY = 0,
  11847. _viewportWidth = _canvas.width,
  11848. _viewportHeight = _canvas.height,
  11849. _currentWidth = 0,
  11850. _currentHeight = 0,
  11851. _enabledAttributes = {},
  11852. // frustum
  11853. _frustum = new THREE.Frustum(),
  11854. // camera matrices cache
  11855. _projScreenMatrix = new THREE.Matrix4(),
  11856. _projScreenMatrixPS = new THREE.Matrix4(),
  11857. _vector3 = new THREE.Vector3(),
  11858. // light arrays cache
  11859. _direction = new THREE.Vector3(),
  11860. _lightsNeedUpdate = true,
  11861. _lights = {
  11862. ambient: [ 0, 0, 0 ],
  11863. directional: { length: 0, colors: new Array(), positions: new Array() },
  11864. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  11865. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  11866. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  11867. };
  11868. // initialize
  11869. var _gl;
  11870. var _glExtensionTextureFloat;
  11871. var _glExtensionTextureFloatLinear;
  11872. var _glExtensionStandardDerivatives;
  11873. var _glExtensionTextureFilterAnisotropic;
  11874. var _glExtensionCompressedTextureS3TC;
  11875. initGL();
  11876. setDefaultGLState();
  11877. this.context = _gl;
  11878. // GPU capabilities
  11879. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  11880. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11881. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  11882. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11883. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  11884. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  11885. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  11886. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  11887. //
  11888. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  11889. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  11890. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  11891. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  11892. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  11893. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  11894. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  11895. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  11896. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  11897. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  11898. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  11899. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  11900. // clamp precision to maximum available
  11901. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  11902. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  11903. if ( _precision === "highp" && ! highpAvailable ) {
  11904. if ( mediumpAvailable ) {
  11905. _precision = "mediump";
  11906. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  11907. } else {
  11908. _precision = "lowp";
  11909. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  11910. }
  11911. }
  11912. if ( _precision === "mediump" && ! mediumpAvailable ) {
  11913. _precision = "lowp";
  11914. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  11915. }
  11916. // API
  11917. this.getContext = function () {
  11918. return _gl;
  11919. };
  11920. this.supportsVertexTextures = function () {
  11921. return _supportsVertexTextures;
  11922. };
  11923. this.supportsFloatTextures = function () {
  11924. return _glExtensionTextureFloat;
  11925. };
  11926. this.supportsStandardDerivatives = function () {
  11927. return _glExtensionStandardDerivatives;
  11928. };
  11929. this.supportsCompressedTextureS3TC = function () {
  11930. return _glExtensionCompressedTextureS3TC;
  11931. };
  11932. this.getMaxAnisotropy = function () {
  11933. return _maxAnisotropy;
  11934. };
  11935. this.getPrecision = function () {
  11936. return _precision;
  11937. };
  11938. this.setSize = function ( width, height, updateStyle ) {
  11939. _canvas.width = width * this.devicePixelRatio;
  11940. _canvas.height = height * this.devicePixelRatio;
  11941. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  11942. _canvas.style.width = width + 'px';
  11943. _canvas.style.height = height + 'px';
  11944. }
  11945. this.setViewport( 0, 0, width, height );
  11946. };
  11947. this.setViewport = function ( x, y, width, height ) {
  11948. _viewportX = x * this.devicePixelRatio;
  11949. _viewportY = y * this.devicePixelRatio;
  11950. _viewportWidth = width * this.devicePixelRatio;
  11951. _viewportHeight = height * this.devicePixelRatio;
  11952. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11953. };
  11954. this.setScissor = function ( x, y, width, height ) {
  11955. _gl.scissor(
  11956. x * this.devicePixelRatio,
  11957. y * this.devicePixelRatio,
  11958. width * this.devicePixelRatio,
  11959. height * this.devicePixelRatio
  11960. );
  11961. };
  11962. this.enableScissorTest = function ( enable ) {
  11963. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  11964. };
  11965. // Clearing
  11966. this.setClearColor = function ( color, alpha ) {
  11967. _clearColor.set( color );
  11968. _clearAlpha = alpha !== undefined ? alpha : 1;
  11969. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11970. };
  11971. this.setClearColorHex = function ( hex, alpha ) {
  11972. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  11973. this.setClearColor( hex, alpha );
  11974. };
  11975. this.getClearColor = function () {
  11976. return _clearColor;
  11977. };
  11978. this.getClearAlpha = function () {
  11979. return _clearAlpha;
  11980. };
  11981. this.clear = function ( color, depth, stencil ) {
  11982. var bits = 0;
  11983. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11984. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11985. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11986. _gl.clear( bits );
  11987. };
  11988. this.clearColor = function () {
  11989. _gl.clear( _gl.COLOR_BUFFER_BIT );
  11990. };
  11991. this.clearDepth = function () {
  11992. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  11993. };
  11994. this.clearStencil = function () {
  11995. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  11996. };
  11997. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11998. this.setRenderTarget( renderTarget );
  11999. this.clear( color, depth, stencil );
  12000. };
  12001. // Plugins
  12002. this.addPostPlugin = function ( plugin ) {
  12003. plugin.init( this );
  12004. this.renderPluginsPost.push( plugin );
  12005. };
  12006. this.addPrePlugin = function ( plugin ) {
  12007. plugin.init( this );
  12008. this.renderPluginsPre.push( plugin );
  12009. };
  12010. // Rendering
  12011. this.updateShadowMap = function ( scene, camera ) {
  12012. _currentProgram = null;
  12013. _oldBlending = -1;
  12014. _oldDepthTest = -1;
  12015. _oldDepthWrite = -1;
  12016. _currentGeometryGroupHash = -1;
  12017. _currentMaterialId = -1;
  12018. _lightsNeedUpdate = true;
  12019. _oldDoubleSided = -1;
  12020. _oldFlipSided = -1;
  12021. this.shadowMapPlugin.update( scene, camera );
  12022. };
  12023. // Internal functions
  12024. // Buffer allocation
  12025. function createParticleBuffers ( geometry ) {
  12026. geometry.__webglVertexBuffer = _gl.createBuffer();
  12027. geometry.__webglColorBuffer = _gl.createBuffer();
  12028. _this.info.memory.geometries ++;
  12029. };
  12030. function createLineBuffers ( geometry ) {
  12031. geometry.__webglVertexBuffer = _gl.createBuffer();
  12032. geometry.__webglColorBuffer = _gl.createBuffer();
  12033. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  12034. _this.info.memory.geometries ++;
  12035. };
  12036. function createMeshBuffers ( geometryGroup ) {
  12037. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  12038. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  12039. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  12040. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  12041. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  12042. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  12043. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  12044. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  12045. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  12046. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  12047. var m, ml;
  12048. if ( geometryGroup.numMorphTargets ) {
  12049. geometryGroup.__webglMorphTargetsBuffers = [];
  12050. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12051. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  12052. }
  12053. }
  12054. if ( geometryGroup.numMorphNormals ) {
  12055. geometryGroup.__webglMorphNormalsBuffers = [];
  12056. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12057. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  12058. }
  12059. }
  12060. _this.info.memory.geometries ++;
  12061. };
  12062. // Events
  12063. var onGeometryDispose = function ( event ) {
  12064. var geometry = event.target;
  12065. geometry.removeEventListener( 'dispose', onGeometryDispose );
  12066. deallocateGeometry( geometry );
  12067. };
  12068. var onTextureDispose = function ( event ) {
  12069. var texture = event.target;
  12070. texture.removeEventListener( 'dispose', onTextureDispose );
  12071. deallocateTexture( texture );
  12072. _this.info.memory.textures --;
  12073. };
  12074. var onRenderTargetDispose = function ( event ) {
  12075. var renderTarget = event.target;
  12076. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  12077. deallocateRenderTarget( renderTarget );
  12078. _this.info.memory.textures --;
  12079. };
  12080. var onMaterialDispose = function ( event ) {
  12081. var material = event.target;
  12082. material.removeEventListener( 'dispose', onMaterialDispose );
  12083. deallocateMaterial( material );
  12084. };
  12085. // Buffer deallocation
  12086. var deleteBuffers = function ( geometry ) {
  12087. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  12088. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  12089. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  12090. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  12091. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  12092. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  12093. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  12094. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  12095. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  12096. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  12097. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  12098. // custom attributes
  12099. if ( geometry.__webglCustomAttributesList !== undefined ) {
  12100. for ( var id in geometry.__webglCustomAttributesList ) {
  12101. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  12102. }
  12103. }
  12104. _this.info.memory.geometries --;
  12105. };
  12106. var deallocateGeometry = function ( geometry ) {
  12107. geometry.__webglInit = undefined;
  12108. if ( geometry instanceof THREE.BufferGeometry ) {
  12109. var attributes = geometry.attributes;
  12110. for ( var key in attributes ) {
  12111. if ( attributes[ key ].buffer !== undefined ) {
  12112. _gl.deleteBuffer( attributes[ key ].buffer );
  12113. }
  12114. }
  12115. _this.info.memory.geometries --;
  12116. } else {
  12117. if ( geometry.geometryGroups !== undefined ) {
  12118. for ( var g in geometry.geometryGroups ) {
  12119. var geometryGroup = geometry.geometryGroups[ g ];
  12120. if ( geometryGroup.numMorphTargets !== undefined ) {
  12121. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12122. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  12123. }
  12124. }
  12125. if ( geometryGroup.numMorphNormals !== undefined ) {
  12126. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12127. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  12128. }
  12129. }
  12130. deleteBuffers( geometryGroup );
  12131. }
  12132. } else {
  12133. deleteBuffers( geometry );
  12134. }
  12135. }
  12136. };
  12137. var deallocateTexture = function ( texture ) {
  12138. if ( texture.image && texture.image.__webglTextureCube ) {
  12139. // cube texture
  12140. _gl.deleteTexture( texture.image.__webglTextureCube );
  12141. } else {
  12142. // 2D texture
  12143. if ( ! texture.__webglInit ) return;
  12144. texture.__webglInit = false;
  12145. _gl.deleteTexture( texture.__webglTexture );
  12146. }
  12147. };
  12148. var deallocateRenderTarget = function ( renderTarget ) {
  12149. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  12150. _gl.deleteTexture( renderTarget.__webglTexture );
  12151. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  12152. for ( var i = 0; i < 6; i ++ ) {
  12153. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  12154. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  12155. }
  12156. } else {
  12157. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  12158. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  12159. }
  12160. };
  12161. var deallocateMaterial = function ( material ) {
  12162. var program = material.program;
  12163. if ( program === undefined ) return;
  12164. material.program = undefined;
  12165. // only deallocate GL program if this was the last use of shared program
  12166. // assumed there is only single copy of any program in the _programs list
  12167. // (that's how it's constructed)
  12168. var i, il, programInfo;
  12169. var deleteProgram = false;
  12170. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12171. programInfo = _programs[ i ];
  12172. if ( programInfo.program === program ) {
  12173. programInfo.usedTimes --;
  12174. if ( programInfo.usedTimes === 0 ) {
  12175. deleteProgram = true;
  12176. }
  12177. break;
  12178. }
  12179. }
  12180. if ( deleteProgram === true ) {
  12181. // avoid using array.splice, this is costlier than creating new array from scratch
  12182. var newPrograms = [];
  12183. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12184. programInfo = _programs[ i ];
  12185. if ( programInfo.program !== program ) {
  12186. newPrograms.push( programInfo );
  12187. }
  12188. }
  12189. _programs = newPrograms;
  12190. _gl.deleteProgram( program );
  12191. _this.info.memory.programs --;
  12192. }
  12193. };
  12194. // Buffer initialization
  12195. function initCustomAttributes ( geometry, object ) {
  12196. var nvertices = geometry.vertices.length;
  12197. var material = object.material;
  12198. if ( material.attributes ) {
  12199. if ( geometry.__webglCustomAttributesList === undefined ) {
  12200. geometry.__webglCustomAttributesList = [];
  12201. }
  12202. for ( var a in material.attributes ) {
  12203. var attribute = material.attributes[ a ];
  12204. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12205. attribute.__webglInitialized = true;
  12206. var size = 1; // "f" and "i"
  12207. if ( attribute.type === "v2" ) size = 2;
  12208. else if ( attribute.type === "v3" ) size = 3;
  12209. else if ( attribute.type === "v4" ) size = 4;
  12210. else if ( attribute.type === "c" ) size = 3;
  12211. attribute.size = size;
  12212. attribute.array = new Float32Array( nvertices * size );
  12213. attribute.buffer = _gl.createBuffer();
  12214. attribute.buffer.belongsToAttribute = a;
  12215. attribute.needsUpdate = true;
  12216. }
  12217. geometry.__webglCustomAttributesList.push( attribute );
  12218. }
  12219. }
  12220. };
  12221. function initParticleBuffers ( geometry, object ) {
  12222. var nvertices = geometry.vertices.length;
  12223. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12224. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12225. geometry.__sortArray = [];
  12226. geometry.__webglParticleCount = nvertices;
  12227. initCustomAttributes ( geometry, object );
  12228. };
  12229. function initLineBuffers ( geometry, object ) {
  12230. var nvertices = geometry.vertices.length;
  12231. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12232. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12233. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  12234. geometry.__webglLineCount = nvertices;
  12235. initCustomAttributes ( geometry, object );
  12236. };
  12237. function initMeshBuffers ( geometryGroup, object ) {
  12238. var geometry = object.geometry,
  12239. faces3 = geometryGroup.faces3,
  12240. nvertices = faces3.length * 3,
  12241. ntris = faces3.length * 1,
  12242. nlines = faces3.length * 3,
  12243. material = getBufferMaterial( object, geometryGroup ),
  12244. uvType = bufferGuessUVType( material ),
  12245. normalType = bufferGuessNormalType( material ),
  12246. vertexColorType = bufferGuessVertexColorType( material );
  12247. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  12248. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  12249. if ( normalType ) {
  12250. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  12251. }
  12252. if ( geometry.hasTangents ) {
  12253. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  12254. }
  12255. if ( vertexColorType ) {
  12256. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  12257. }
  12258. if ( uvType ) {
  12259. if ( geometry.faceVertexUvs.length > 0 ) {
  12260. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  12261. }
  12262. if ( geometry.faceVertexUvs.length > 1 ) {
  12263. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  12264. }
  12265. }
  12266. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  12267. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  12268. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  12269. }
  12270. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  12271. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  12272. var m, ml;
  12273. if ( geometryGroup.numMorphTargets ) {
  12274. geometryGroup.__morphTargetsArrays = [];
  12275. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12276. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  12277. }
  12278. }
  12279. if ( geometryGroup.numMorphNormals ) {
  12280. geometryGroup.__morphNormalsArrays = [];
  12281. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12282. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  12283. }
  12284. }
  12285. geometryGroup.__webglFaceCount = ntris * 3;
  12286. geometryGroup.__webglLineCount = nlines * 2;
  12287. // custom attributes
  12288. if ( material.attributes ) {
  12289. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  12290. geometryGroup.__webglCustomAttributesList = [];
  12291. }
  12292. for ( var a in material.attributes ) {
  12293. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  12294. // attribute buffers which are correctly indexed in the setMeshBuffers function
  12295. var originalAttribute = material.attributes[ a ];
  12296. var attribute = {};
  12297. for ( var property in originalAttribute ) {
  12298. attribute[ property ] = originalAttribute[ property ];
  12299. }
  12300. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12301. attribute.__webglInitialized = true;
  12302. var size = 1; // "f" and "i"
  12303. if( attribute.type === "v2" ) size = 2;
  12304. else if( attribute.type === "v3" ) size = 3;
  12305. else if( attribute.type === "v4" ) size = 4;
  12306. else if( attribute.type === "c" ) size = 3;
  12307. attribute.size = size;
  12308. attribute.array = new Float32Array( nvertices * size );
  12309. attribute.buffer = _gl.createBuffer();
  12310. attribute.buffer.belongsToAttribute = a;
  12311. originalAttribute.needsUpdate = true;
  12312. attribute.__original = originalAttribute;
  12313. }
  12314. geometryGroup.__webglCustomAttributesList.push( attribute );
  12315. }
  12316. }
  12317. geometryGroup.__inittedArrays = true;
  12318. };
  12319. function getBufferMaterial( object, geometryGroup ) {
  12320. return object.material instanceof THREE.MeshFaceMaterial
  12321. ? object.material.materials[ geometryGroup.materialIndex ]
  12322. : object.material;
  12323. };
  12324. function materialNeedsSmoothNormals ( material ) {
  12325. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  12326. };
  12327. function bufferGuessNormalType ( material ) {
  12328. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  12329. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  12330. return false;
  12331. }
  12332. if ( materialNeedsSmoothNormals( material ) ) {
  12333. return THREE.SmoothShading;
  12334. } else {
  12335. return THREE.FlatShading;
  12336. }
  12337. };
  12338. function bufferGuessVertexColorType( material ) {
  12339. if ( material.vertexColors ) {
  12340. return material.vertexColors;
  12341. }
  12342. return false;
  12343. };
  12344. function bufferGuessUVType( material ) {
  12345. // material must use some texture to require uvs
  12346. if ( material.map ||
  12347. material.lightMap ||
  12348. material.bumpMap ||
  12349. material.normalMap ||
  12350. material.specularMap ||
  12351. material instanceof THREE.ShaderMaterial ) {
  12352. return true;
  12353. }
  12354. return false;
  12355. };
  12356. //
  12357. function initDirectBuffers( geometry ) {
  12358. var a, attribute, type;
  12359. for ( a in geometry.attributes ) {
  12360. if ( a === "index" ) {
  12361. type = _gl.ELEMENT_ARRAY_BUFFER;
  12362. } else {
  12363. type = _gl.ARRAY_BUFFER;
  12364. }
  12365. attribute = geometry.attributes[ a ];
  12366. attribute.buffer = _gl.createBuffer();
  12367. _gl.bindBuffer( type, attribute.buffer );
  12368. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  12369. }
  12370. };
  12371. // Buffer setting
  12372. function setParticleBuffers ( geometry, hint, object ) {
  12373. var v, c, vertex, offset, index, color,
  12374. vertices = geometry.vertices,
  12375. vl = vertices.length,
  12376. colors = geometry.colors,
  12377. cl = colors.length,
  12378. vertexArray = geometry.__vertexArray,
  12379. colorArray = geometry.__colorArray,
  12380. sortArray = geometry.__sortArray,
  12381. dirtyVertices = geometry.verticesNeedUpdate,
  12382. dirtyElements = geometry.elementsNeedUpdate,
  12383. dirtyColors = geometry.colorsNeedUpdate,
  12384. customAttributes = geometry.__webglCustomAttributesList,
  12385. i, il,
  12386. a, ca, cal, value,
  12387. customAttribute;
  12388. if ( object.sortParticles ) {
  12389. _projScreenMatrixPS.copy( _projScreenMatrix );
  12390. _projScreenMatrixPS.multiply( object.matrixWorld );
  12391. for ( v = 0; v < vl; v ++ ) {
  12392. vertex = vertices[ v ];
  12393. _vector3.copy( vertex );
  12394. _vector3.applyProjection( _projScreenMatrixPS );
  12395. sortArray[ v ] = [ _vector3.z, v ];
  12396. }
  12397. sortArray.sort( numericalSort );
  12398. for ( v = 0; v < vl; v ++ ) {
  12399. vertex = vertices[ sortArray[v][1] ];
  12400. offset = v * 3;
  12401. vertexArray[ offset ] = vertex.x;
  12402. vertexArray[ offset + 1 ] = vertex.y;
  12403. vertexArray[ offset + 2 ] = vertex.z;
  12404. }
  12405. for ( c = 0; c < cl; c ++ ) {
  12406. offset = c * 3;
  12407. color = colors[ sortArray[c][1] ];
  12408. colorArray[ offset ] = color.r;
  12409. colorArray[ offset + 1 ] = color.g;
  12410. colorArray[ offset + 2 ] = color.b;
  12411. }
  12412. if ( customAttributes ) {
  12413. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12414. customAttribute = customAttributes[ i ];
  12415. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  12416. offset = 0;
  12417. cal = customAttribute.value.length;
  12418. if ( customAttribute.size === 1 ) {
  12419. for ( ca = 0; ca < cal; ca ++ ) {
  12420. index = sortArray[ ca ][ 1 ];
  12421. customAttribute.array[ ca ] = customAttribute.value[ index ];
  12422. }
  12423. } else if ( customAttribute.size === 2 ) {
  12424. for ( ca = 0; ca < cal; ca ++ ) {
  12425. index = sortArray[ ca ][ 1 ];
  12426. value = customAttribute.value[ index ];
  12427. customAttribute.array[ offset ] = value.x;
  12428. customAttribute.array[ offset + 1 ] = value.y;
  12429. offset += 2;
  12430. }
  12431. } else if ( customAttribute.size === 3 ) {
  12432. if ( customAttribute.type === "c" ) {
  12433. for ( ca = 0; ca < cal; ca ++ ) {
  12434. index = sortArray[ ca ][ 1 ];
  12435. value = customAttribute.value[ index ];
  12436. customAttribute.array[ offset ] = value.r;
  12437. customAttribute.array[ offset + 1 ] = value.g;
  12438. customAttribute.array[ offset + 2 ] = value.b;
  12439. offset += 3;
  12440. }
  12441. } else {
  12442. for ( ca = 0; ca < cal; ca ++ ) {
  12443. index = sortArray[ ca ][ 1 ];
  12444. value = customAttribute.value[ index ];
  12445. customAttribute.array[ offset ] = value.x;
  12446. customAttribute.array[ offset + 1 ] = value.y;
  12447. customAttribute.array[ offset + 2 ] = value.z;
  12448. offset += 3;
  12449. }
  12450. }
  12451. } else if ( customAttribute.size === 4 ) {
  12452. for ( ca = 0; ca < cal; ca ++ ) {
  12453. index = sortArray[ ca ][ 1 ];
  12454. value = customAttribute.value[ index ];
  12455. customAttribute.array[ offset ] = value.x;
  12456. customAttribute.array[ offset + 1 ] = value.y;
  12457. customAttribute.array[ offset + 2 ] = value.z;
  12458. customAttribute.array[ offset + 3 ] = value.w;
  12459. offset += 4;
  12460. }
  12461. }
  12462. }
  12463. }
  12464. } else {
  12465. if ( dirtyVertices ) {
  12466. for ( v = 0; v < vl; v ++ ) {
  12467. vertex = vertices[ v ];
  12468. offset = v * 3;
  12469. vertexArray[ offset ] = vertex.x;
  12470. vertexArray[ offset + 1 ] = vertex.y;
  12471. vertexArray[ offset + 2 ] = vertex.z;
  12472. }
  12473. }
  12474. if ( dirtyColors ) {
  12475. for ( c = 0; c < cl; c ++ ) {
  12476. color = colors[ c ];
  12477. offset = c * 3;
  12478. colorArray[ offset ] = color.r;
  12479. colorArray[ offset + 1 ] = color.g;
  12480. colorArray[ offset + 2 ] = color.b;
  12481. }
  12482. }
  12483. if ( customAttributes ) {
  12484. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12485. customAttribute = customAttributes[ i ];
  12486. if ( customAttribute.needsUpdate &&
  12487. ( customAttribute.boundTo === undefined ||
  12488. customAttribute.boundTo === "vertices") ) {
  12489. cal = customAttribute.value.length;
  12490. offset = 0;
  12491. if ( customAttribute.size === 1 ) {
  12492. for ( ca = 0; ca < cal; ca ++ ) {
  12493. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12494. }
  12495. } else if ( customAttribute.size === 2 ) {
  12496. for ( ca = 0; ca < cal; ca ++ ) {
  12497. value = customAttribute.value[ ca ];
  12498. customAttribute.array[ offset ] = value.x;
  12499. customAttribute.array[ offset + 1 ] = value.y;
  12500. offset += 2;
  12501. }
  12502. } else if ( customAttribute.size === 3 ) {
  12503. if ( customAttribute.type === "c" ) {
  12504. for ( ca = 0; ca < cal; ca ++ ) {
  12505. value = customAttribute.value[ ca ];
  12506. customAttribute.array[ offset ] = value.r;
  12507. customAttribute.array[ offset + 1 ] = value.g;
  12508. customAttribute.array[ offset + 2 ] = value.b;
  12509. offset += 3;
  12510. }
  12511. } else {
  12512. for ( ca = 0; ca < cal; ca ++ ) {
  12513. value = customAttribute.value[ ca ];
  12514. customAttribute.array[ offset ] = value.x;
  12515. customAttribute.array[ offset + 1 ] = value.y;
  12516. customAttribute.array[ offset + 2 ] = value.z;
  12517. offset += 3;
  12518. }
  12519. }
  12520. } else if ( customAttribute.size === 4 ) {
  12521. for ( ca = 0; ca < cal; ca ++ ) {
  12522. value = customAttribute.value[ ca ];
  12523. customAttribute.array[ offset ] = value.x;
  12524. customAttribute.array[ offset + 1 ] = value.y;
  12525. customAttribute.array[ offset + 2 ] = value.z;
  12526. customAttribute.array[ offset + 3 ] = value.w;
  12527. offset += 4;
  12528. }
  12529. }
  12530. }
  12531. }
  12532. }
  12533. }
  12534. if ( dirtyVertices || object.sortParticles ) {
  12535. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12536. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12537. }
  12538. if ( dirtyColors || object.sortParticles ) {
  12539. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12540. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12541. }
  12542. if ( customAttributes ) {
  12543. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12544. customAttribute = customAttributes[ i ];
  12545. if ( customAttribute.needsUpdate || object.sortParticles ) {
  12546. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12547. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12548. }
  12549. }
  12550. }
  12551. };
  12552. function setLineBuffers ( geometry, hint ) {
  12553. var v, c, d, vertex, offset, color,
  12554. vertices = geometry.vertices,
  12555. colors = geometry.colors,
  12556. lineDistances = geometry.lineDistances,
  12557. vl = vertices.length,
  12558. cl = colors.length,
  12559. dl = lineDistances.length,
  12560. vertexArray = geometry.__vertexArray,
  12561. colorArray = geometry.__colorArray,
  12562. lineDistanceArray = geometry.__lineDistanceArray,
  12563. dirtyVertices = geometry.verticesNeedUpdate,
  12564. dirtyColors = geometry.colorsNeedUpdate,
  12565. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  12566. customAttributes = geometry.__webglCustomAttributesList,
  12567. i, il,
  12568. a, ca, cal, value,
  12569. customAttribute;
  12570. if ( dirtyVertices ) {
  12571. for ( v = 0; v < vl; v ++ ) {
  12572. vertex = vertices[ v ];
  12573. offset = v * 3;
  12574. vertexArray[ offset ] = vertex.x;
  12575. vertexArray[ offset + 1 ] = vertex.y;
  12576. vertexArray[ offset + 2 ] = vertex.z;
  12577. }
  12578. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12579. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12580. }
  12581. if ( dirtyColors ) {
  12582. for ( c = 0; c < cl; c ++ ) {
  12583. color = colors[ c ];
  12584. offset = c * 3;
  12585. colorArray[ offset ] = color.r;
  12586. colorArray[ offset + 1 ] = color.g;
  12587. colorArray[ offset + 2 ] = color.b;
  12588. }
  12589. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12590. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12591. }
  12592. if ( dirtyLineDistances ) {
  12593. for ( d = 0; d < dl; d ++ ) {
  12594. lineDistanceArray[ d ] = lineDistances[ d ];
  12595. }
  12596. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  12597. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  12598. }
  12599. if ( customAttributes ) {
  12600. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12601. customAttribute = customAttributes[ i ];
  12602. if ( customAttribute.needsUpdate &&
  12603. ( customAttribute.boundTo === undefined ||
  12604. customAttribute.boundTo === "vertices" ) ) {
  12605. offset = 0;
  12606. cal = customAttribute.value.length;
  12607. if ( customAttribute.size === 1 ) {
  12608. for ( ca = 0; ca < cal; ca ++ ) {
  12609. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12610. }
  12611. } else if ( customAttribute.size === 2 ) {
  12612. for ( ca = 0; ca < cal; ca ++ ) {
  12613. value = customAttribute.value[ ca ];
  12614. customAttribute.array[ offset ] = value.x;
  12615. customAttribute.array[ offset + 1 ] = value.y;
  12616. offset += 2;
  12617. }
  12618. } else if ( customAttribute.size === 3 ) {
  12619. if ( customAttribute.type === "c" ) {
  12620. for ( ca = 0; ca < cal; ca ++ ) {
  12621. value = customAttribute.value[ ca ];
  12622. customAttribute.array[ offset ] = value.r;
  12623. customAttribute.array[ offset + 1 ] = value.g;
  12624. customAttribute.array[ offset + 2 ] = value.b;
  12625. offset += 3;
  12626. }
  12627. } else {
  12628. for ( ca = 0; ca < cal; ca ++ ) {
  12629. value = customAttribute.value[ ca ];
  12630. customAttribute.array[ offset ] = value.x;
  12631. customAttribute.array[ offset + 1 ] = value.y;
  12632. customAttribute.array[ offset + 2 ] = value.z;
  12633. offset += 3;
  12634. }
  12635. }
  12636. } else if ( customAttribute.size === 4 ) {
  12637. for ( ca = 0; ca < cal; ca ++ ) {
  12638. value = customAttribute.value[ ca ];
  12639. customAttribute.array[ offset ] = value.x;
  12640. customAttribute.array[ offset + 1 ] = value.y;
  12641. customAttribute.array[ offset + 2 ] = value.z;
  12642. customAttribute.array[ offset + 3 ] = value.w;
  12643. offset += 4;
  12644. }
  12645. }
  12646. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12647. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12648. }
  12649. }
  12650. }
  12651. };
  12652. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12653. if ( ! geometryGroup.__inittedArrays ) {
  12654. return;
  12655. }
  12656. var normalType = bufferGuessNormalType( material ),
  12657. vertexColorType = bufferGuessVertexColorType( material ),
  12658. uvType = bufferGuessUVType( material ),
  12659. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12660. var f, fl, fi, face,
  12661. vertexNormals, faceNormal, normal,
  12662. vertexColors, faceColor,
  12663. vertexTangents,
  12664. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12665. c1, c2, c3, c4,
  12666. sw1, sw2, sw3, sw4,
  12667. si1, si2, si3, si4,
  12668. sa1, sa2, sa3, sa4,
  12669. sb1, sb2, sb3, sb4,
  12670. m, ml, i, il,
  12671. vn, uvi, uv2i,
  12672. vk, vkl, vka,
  12673. nka, chf, faceVertexNormals,
  12674. a,
  12675. vertexIndex = 0,
  12676. offset = 0,
  12677. offset_uv = 0,
  12678. offset_uv2 = 0,
  12679. offset_face = 0,
  12680. offset_normal = 0,
  12681. offset_tangent = 0,
  12682. offset_line = 0,
  12683. offset_color = 0,
  12684. offset_skin = 0,
  12685. offset_morphTarget = 0,
  12686. offset_custom = 0,
  12687. offset_customSrc = 0,
  12688. value,
  12689. vertexArray = geometryGroup.__vertexArray,
  12690. uvArray = geometryGroup.__uvArray,
  12691. uv2Array = geometryGroup.__uv2Array,
  12692. normalArray = geometryGroup.__normalArray,
  12693. tangentArray = geometryGroup.__tangentArray,
  12694. colorArray = geometryGroup.__colorArray,
  12695. skinIndexArray = geometryGroup.__skinIndexArray,
  12696. skinWeightArray = geometryGroup.__skinWeightArray,
  12697. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12698. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12699. customAttributes = geometryGroup.__webglCustomAttributesList,
  12700. customAttribute,
  12701. faceArray = geometryGroup.__faceArray,
  12702. lineArray = geometryGroup.__lineArray,
  12703. geometry = object.geometry, // this is shared for all chunks
  12704. dirtyVertices = geometry.verticesNeedUpdate,
  12705. dirtyElements = geometry.elementsNeedUpdate,
  12706. dirtyUvs = geometry.uvsNeedUpdate,
  12707. dirtyNormals = geometry.normalsNeedUpdate,
  12708. dirtyTangents = geometry.tangentsNeedUpdate,
  12709. dirtyColors = geometry.colorsNeedUpdate,
  12710. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12711. vertices = geometry.vertices,
  12712. chunk_faces3 = geometryGroup.faces3,
  12713. obj_faces = geometry.faces,
  12714. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12715. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12716. obj_colors = geometry.colors,
  12717. obj_skinIndices = geometry.skinIndices,
  12718. obj_skinWeights = geometry.skinWeights,
  12719. morphTargets = geometry.morphTargets,
  12720. morphNormals = geometry.morphNormals;
  12721. if ( dirtyVertices ) {
  12722. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12723. face = obj_faces[ chunk_faces3[ f ] ];
  12724. v1 = vertices[ face.a ];
  12725. v2 = vertices[ face.b ];
  12726. v3 = vertices[ face.c ];
  12727. vertexArray[ offset ] = v1.x;
  12728. vertexArray[ offset + 1 ] = v1.y;
  12729. vertexArray[ offset + 2 ] = v1.z;
  12730. vertexArray[ offset + 3 ] = v2.x;
  12731. vertexArray[ offset + 4 ] = v2.y;
  12732. vertexArray[ offset + 5 ] = v2.z;
  12733. vertexArray[ offset + 6 ] = v3.x;
  12734. vertexArray[ offset + 7 ] = v3.y;
  12735. vertexArray[ offset + 8 ] = v3.z;
  12736. offset += 9;
  12737. }
  12738. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12739. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12740. }
  12741. if ( dirtyMorphTargets ) {
  12742. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  12743. offset_morphTarget = 0;
  12744. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12745. chf = chunk_faces3[ f ];
  12746. face = obj_faces[ chf ];
  12747. // morph positions
  12748. v1 = morphTargets[ vk ].vertices[ face.a ];
  12749. v2 = morphTargets[ vk ].vertices[ face.b ];
  12750. v3 = morphTargets[ vk ].vertices[ face.c ];
  12751. vka = morphTargetsArrays[ vk ];
  12752. vka[ offset_morphTarget ] = v1.x;
  12753. vka[ offset_morphTarget + 1 ] = v1.y;
  12754. vka[ offset_morphTarget + 2 ] = v1.z;
  12755. vka[ offset_morphTarget + 3 ] = v2.x;
  12756. vka[ offset_morphTarget + 4 ] = v2.y;
  12757. vka[ offset_morphTarget + 5 ] = v2.z;
  12758. vka[ offset_morphTarget + 6 ] = v3.x;
  12759. vka[ offset_morphTarget + 7 ] = v3.y;
  12760. vka[ offset_morphTarget + 8 ] = v3.z;
  12761. // morph normals
  12762. if ( material.morphNormals ) {
  12763. if ( needsSmoothNormals ) {
  12764. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12765. n1 = faceVertexNormals.a;
  12766. n2 = faceVertexNormals.b;
  12767. n3 = faceVertexNormals.c;
  12768. } else {
  12769. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12770. n2 = n1;
  12771. n3 = n1;
  12772. }
  12773. nka = morphNormalsArrays[ vk ];
  12774. nka[ offset_morphTarget ] = n1.x;
  12775. nka[ offset_morphTarget + 1 ] = n1.y;
  12776. nka[ offset_morphTarget + 2 ] = n1.z;
  12777. nka[ offset_morphTarget + 3 ] = n2.x;
  12778. nka[ offset_morphTarget + 4 ] = n2.y;
  12779. nka[ offset_morphTarget + 5 ] = n2.z;
  12780. nka[ offset_morphTarget + 6 ] = n3.x;
  12781. nka[ offset_morphTarget + 7 ] = n3.y;
  12782. nka[ offset_morphTarget + 8 ] = n3.z;
  12783. }
  12784. //
  12785. offset_morphTarget += 9;
  12786. }
  12787. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  12788. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  12789. if ( material.morphNormals ) {
  12790. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  12791. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  12792. }
  12793. }
  12794. }
  12795. if ( obj_skinWeights.length ) {
  12796. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12797. face = obj_faces[ chunk_faces3[ f ] ];
  12798. // weights
  12799. sw1 = obj_skinWeights[ face.a ];
  12800. sw2 = obj_skinWeights[ face.b ];
  12801. sw3 = obj_skinWeights[ face.c ];
  12802. skinWeightArray[ offset_skin ] = sw1.x;
  12803. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12804. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12805. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12806. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12807. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12808. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12809. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12810. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12811. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12812. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12813. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12814. // indices
  12815. si1 = obj_skinIndices[ face.a ];
  12816. si2 = obj_skinIndices[ face.b ];
  12817. si3 = obj_skinIndices[ face.c ];
  12818. skinIndexArray[ offset_skin ] = si1.x;
  12819. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12820. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12821. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12822. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12823. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12824. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12825. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12826. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12827. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12828. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12829. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12830. offset_skin += 12;
  12831. }
  12832. if ( offset_skin > 0 ) {
  12833. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12834. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  12835. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12836. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  12837. }
  12838. }
  12839. if ( dirtyColors && vertexColorType ) {
  12840. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12841. face = obj_faces[ chunk_faces3[ f ] ];
  12842. vertexColors = face.vertexColors;
  12843. faceColor = face.color;
  12844. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  12845. c1 = vertexColors[ 0 ];
  12846. c2 = vertexColors[ 1 ];
  12847. c3 = vertexColors[ 2 ];
  12848. } else {
  12849. c1 = faceColor;
  12850. c2 = faceColor;
  12851. c3 = faceColor;
  12852. }
  12853. colorArray[ offset_color ] = c1.r;
  12854. colorArray[ offset_color + 1 ] = c1.g;
  12855. colorArray[ offset_color + 2 ] = c1.b;
  12856. colorArray[ offset_color + 3 ] = c2.r;
  12857. colorArray[ offset_color + 4 ] = c2.g;
  12858. colorArray[ offset_color + 5 ] = c2.b;
  12859. colorArray[ offset_color + 6 ] = c3.r;
  12860. colorArray[ offset_color + 7 ] = c3.g;
  12861. colorArray[ offset_color + 8 ] = c3.b;
  12862. offset_color += 9;
  12863. }
  12864. if ( offset_color > 0 ) {
  12865. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12866. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12867. }
  12868. }
  12869. if ( dirtyTangents && geometry.hasTangents ) {
  12870. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12871. face = obj_faces[ chunk_faces3[ f ] ];
  12872. vertexTangents = face.vertexTangents;
  12873. t1 = vertexTangents[ 0 ];
  12874. t2 = vertexTangents[ 1 ];
  12875. t3 = vertexTangents[ 2 ];
  12876. tangentArray[ offset_tangent ] = t1.x;
  12877. tangentArray[ offset_tangent + 1 ] = t1.y;
  12878. tangentArray[ offset_tangent + 2 ] = t1.z;
  12879. tangentArray[ offset_tangent + 3 ] = t1.w;
  12880. tangentArray[ offset_tangent + 4 ] = t2.x;
  12881. tangentArray[ offset_tangent + 5 ] = t2.y;
  12882. tangentArray[ offset_tangent + 6 ] = t2.z;
  12883. tangentArray[ offset_tangent + 7 ] = t2.w;
  12884. tangentArray[ offset_tangent + 8 ] = t3.x;
  12885. tangentArray[ offset_tangent + 9 ] = t3.y;
  12886. tangentArray[ offset_tangent + 10 ] = t3.z;
  12887. tangentArray[ offset_tangent + 11 ] = t3.w;
  12888. offset_tangent += 12;
  12889. }
  12890. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12891. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  12892. }
  12893. if ( dirtyNormals && normalType ) {
  12894. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12895. face = obj_faces[ chunk_faces3[ f ] ];
  12896. vertexNormals = face.vertexNormals;
  12897. faceNormal = face.normal;
  12898. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  12899. for ( i = 0; i < 3; i ++ ) {
  12900. vn = vertexNormals[ i ];
  12901. normalArray[ offset_normal ] = vn.x;
  12902. normalArray[ offset_normal + 1 ] = vn.y;
  12903. normalArray[ offset_normal + 2 ] = vn.z;
  12904. offset_normal += 3;
  12905. }
  12906. } else {
  12907. for ( i = 0; i < 3; i ++ ) {
  12908. normalArray[ offset_normal ] = faceNormal.x;
  12909. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12910. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12911. offset_normal += 3;
  12912. }
  12913. }
  12914. }
  12915. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12916. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12917. }
  12918. if ( dirtyUvs && obj_uvs && uvType ) {
  12919. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12920. fi = chunk_faces3[ f ];
  12921. uv = obj_uvs[ fi ];
  12922. if ( uv === undefined ) continue;
  12923. for ( i = 0; i < 3; i ++ ) {
  12924. uvi = uv[ i ];
  12925. uvArray[ offset_uv ] = uvi.x;
  12926. uvArray[ offset_uv + 1 ] = uvi.y;
  12927. offset_uv += 2;
  12928. }
  12929. }
  12930. if ( offset_uv > 0 ) {
  12931. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12932. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  12933. }
  12934. }
  12935. if ( dirtyUvs && obj_uvs2 && uvType ) {
  12936. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12937. fi = chunk_faces3[ f ];
  12938. uv2 = obj_uvs2[ fi ];
  12939. if ( uv2 === undefined ) continue;
  12940. for ( i = 0; i < 3; i ++ ) {
  12941. uv2i = uv2[ i ];
  12942. uv2Array[ offset_uv2 ] = uv2i.x;
  12943. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12944. offset_uv2 += 2;
  12945. }
  12946. }
  12947. if ( offset_uv2 > 0 ) {
  12948. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12949. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  12950. }
  12951. }
  12952. if ( dirtyElements ) {
  12953. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12954. faceArray[ offset_face ] = vertexIndex;
  12955. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12956. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  12957. offset_face += 3;
  12958. lineArray[ offset_line ] = vertexIndex;
  12959. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12960. lineArray[ offset_line + 2 ] = vertexIndex;
  12961. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  12962. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12963. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12964. offset_line += 6;
  12965. vertexIndex += 3;
  12966. }
  12967. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12968. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  12969. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12970. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  12971. }
  12972. if ( customAttributes ) {
  12973. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12974. customAttribute = customAttributes[ i ];
  12975. if ( ! customAttribute.__original.needsUpdate ) continue;
  12976. offset_custom = 0;
  12977. offset_customSrc = 0;
  12978. if ( customAttribute.size === 1 ) {
  12979. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12980. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12981. face = obj_faces[ chunk_faces3[ f ] ];
  12982. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12983. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12984. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12985. offset_custom += 3;
  12986. }
  12987. } else if ( customAttribute.boundTo === "faces" ) {
  12988. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12989. value = customAttribute.value[ chunk_faces3[ f ] ];
  12990. customAttribute.array[ offset_custom ] = value;
  12991. customAttribute.array[ offset_custom + 1 ] = value;
  12992. customAttribute.array[ offset_custom + 2 ] = value;
  12993. offset_custom += 3;
  12994. }
  12995. }
  12996. } else if ( customAttribute.size === 2 ) {
  12997. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12998. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12999. face = obj_faces[ chunk_faces3[ f ] ];
  13000. v1 = customAttribute.value[ face.a ];
  13001. v2 = customAttribute.value[ face.b ];
  13002. v3 = customAttribute.value[ face.c ];
  13003. customAttribute.array[ offset_custom ] = v1.x;
  13004. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13005. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13006. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13007. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13008. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13009. offset_custom += 6;
  13010. }
  13011. } else if ( customAttribute.boundTo === "faces" ) {
  13012. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13013. value = customAttribute.value[ chunk_faces3[ f ] ];
  13014. v1 = value;
  13015. v2 = value;
  13016. v3 = value;
  13017. customAttribute.array[ offset_custom ] = v1.x;
  13018. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13019. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13020. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13021. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13022. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13023. offset_custom += 6;
  13024. }
  13025. }
  13026. } else if ( customAttribute.size === 3 ) {
  13027. var pp;
  13028. if ( customAttribute.type === "c" ) {
  13029. pp = [ "r", "g", "b" ];
  13030. } else {
  13031. pp = [ "x", "y", "z" ];
  13032. }
  13033. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13034. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13035. face = obj_faces[ chunk_faces3[ f ] ];
  13036. v1 = customAttribute.value[ face.a ];
  13037. v2 = customAttribute.value[ face.b ];
  13038. v3 = customAttribute.value[ face.c ];
  13039. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13040. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13041. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13042. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13043. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13044. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13045. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13046. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13047. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13048. offset_custom += 9;
  13049. }
  13050. } else if ( customAttribute.boundTo === "faces" ) {
  13051. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13052. value = customAttribute.value[ chunk_faces3[ f ] ];
  13053. v1 = value;
  13054. v2 = value;
  13055. v3 = value;
  13056. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13057. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13058. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13059. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13060. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13061. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13062. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13063. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13064. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13065. offset_custom += 9;
  13066. }
  13067. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13068. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13069. value = customAttribute.value[ chunk_faces3[ f ] ];
  13070. v1 = value[ 0 ];
  13071. v2 = value[ 1 ];
  13072. v3 = value[ 2 ];
  13073. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13074. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13075. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13076. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13077. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13078. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13079. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13080. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13081. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13082. offset_custom += 9;
  13083. }
  13084. }
  13085. } else if ( customAttribute.size === 4 ) {
  13086. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13087. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13088. face = obj_faces[ chunk_faces3[ f ] ];
  13089. v1 = customAttribute.value[ face.a ];
  13090. v2 = customAttribute.value[ face.b ];
  13091. v3 = customAttribute.value[ face.c ];
  13092. customAttribute.array[ offset_custom ] = v1.x;
  13093. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13094. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13095. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13096. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13097. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13098. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13099. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13100. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13101. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13102. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13103. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13104. offset_custom += 12;
  13105. }
  13106. } else if ( customAttribute.boundTo === "faces" ) {
  13107. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13108. value = customAttribute.value[ chunk_faces3[ f ] ];
  13109. v1 = value;
  13110. v2 = value;
  13111. v3 = value;
  13112. customAttribute.array[ offset_custom ] = v1.x;
  13113. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13114. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13115. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13116. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13117. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13118. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13119. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13120. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13121. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13122. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13123. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13124. offset_custom += 12;
  13125. }
  13126. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13127. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13128. value = customAttribute.value[ chunk_faces3[ f ] ];
  13129. v1 = value[ 0 ];
  13130. v2 = value[ 1 ];
  13131. v3 = value[ 2 ];
  13132. customAttribute.array[ offset_custom ] = v1.x;
  13133. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13134. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13135. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13136. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13137. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13138. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13139. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13140. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13141. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13142. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13143. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13144. offset_custom += 12;
  13145. }
  13146. }
  13147. }
  13148. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13149. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13150. }
  13151. }
  13152. if ( dispose ) {
  13153. delete geometryGroup.__inittedArrays;
  13154. delete geometryGroup.__colorArray;
  13155. delete geometryGroup.__normalArray;
  13156. delete geometryGroup.__tangentArray;
  13157. delete geometryGroup.__uvArray;
  13158. delete geometryGroup.__uv2Array;
  13159. delete geometryGroup.__faceArray;
  13160. delete geometryGroup.__vertexArray;
  13161. delete geometryGroup.__lineArray;
  13162. delete geometryGroup.__skinIndexArray;
  13163. delete geometryGroup.__skinWeightArray;
  13164. }
  13165. };
  13166. // used by renderBufferDirect for THREE.Line
  13167. function setupLinesVertexAttributes( material, programAttributes, geometryAttributes, startIndex ) {
  13168. var attributeItem, attributeName, attributePointer, attributeSize;
  13169. for ( attributeName in programAttributes ) {
  13170. attributePointer = programAttributes[ attributeName ];
  13171. attributeItem = geometryAttributes[ attributeName ];
  13172. if ( attributePointer >= 0 ) {
  13173. if ( attributeItem ) {
  13174. attributeSize = attributeItem.itemSize;
  13175. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13176. enableAttribute( attributePointer );
  13177. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13178. } else if ( material.defaultAttributeValues ) {
  13179. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13180. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13181. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13182. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13183. }
  13184. }
  13185. }
  13186. }
  13187. }
  13188. function setDirectBuffers ( geometry, hint, dispose ) {
  13189. var attributes = geometry.attributes;
  13190. var attributeName, attributeItem;
  13191. for ( attributeName in attributes ) {
  13192. attributeItem = attributes[ attributeName ];
  13193. if ( attributeItem.needsUpdate ) {
  13194. if ( attributeName === 'index' ) {
  13195. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  13196. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  13197. } else {
  13198. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13199. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  13200. }
  13201. attributeItem.needsUpdate = false;
  13202. }
  13203. if ( dispose && ! attributeItem.dynamic ) {
  13204. attributeItem.array = null;
  13205. }
  13206. }
  13207. };
  13208. // Buffer rendering
  13209. this.renderBufferImmediate = function ( object, program, material ) {
  13210. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  13211. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  13212. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  13213. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  13214. if ( object.hasPositions ) {
  13215. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  13216. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  13217. _gl.enableVertexAttribArray( program.attributes.position );
  13218. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13219. }
  13220. if ( object.hasNormals ) {
  13221. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  13222. if ( material.shading === THREE.FlatShading ) {
  13223. var nx, ny, nz,
  13224. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  13225. normalArray,
  13226. i, il = object.count * 3;
  13227. for( i = 0; i < il; i += 9 ) {
  13228. normalArray = object.normalArray;
  13229. nax = normalArray[ i ];
  13230. nay = normalArray[ i + 1 ];
  13231. naz = normalArray[ i + 2 ];
  13232. nbx = normalArray[ i + 3 ];
  13233. nby = normalArray[ i + 4 ];
  13234. nbz = normalArray[ i + 5 ];
  13235. ncx = normalArray[ i + 6 ];
  13236. ncy = normalArray[ i + 7 ];
  13237. ncz = normalArray[ i + 8 ];
  13238. nx = ( nax + nbx + ncx ) / 3;
  13239. ny = ( nay + nby + ncy ) / 3;
  13240. nz = ( naz + nbz + ncz ) / 3;
  13241. normalArray[ i ] = nx;
  13242. normalArray[ i + 1 ] = ny;
  13243. normalArray[ i + 2 ] = nz;
  13244. normalArray[ i + 3 ] = nx;
  13245. normalArray[ i + 4 ] = ny;
  13246. normalArray[ i + 5 ] = nz;
  13247. normalArray[ i + 6 ] = nx;
  13248. normalArray[ i + 7 ] = ny;
  13249. normalArray[ i + 8 ] = nz;
  13250. }
  13251. }
  13252. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13253. _gl.enableVertexAttribArray( program.attributes.normal );
  13254. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13255. }
  13256. if ( object.hasUvs && material.map ) {
  13257. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13258. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13259. _gl.enableVertexAttribArray( program.attributes.uv );
  13260. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13261. }
  13262. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13263. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13264. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13265. _gl.enableVertexAttribArray( program.attributes.color );
  13266. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13267. }
  13268. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13269. object.count = 0;
  13270. };
  13271. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13272. if ( material.visible === false ) return;
  13273. var linewidth, a, attribute;
  13274. var attributeItem, attributeName, attributePointer, attributeSize;
  13275. var program = setProgram( camera, lights, fog, material, object );
  13276. var programAttributes = program.attributes;
  13277. var geometryAttributes = geometry.attributes;
  13278. var updateBuffers = false,
  13279. wireframeBit = material.wireframe ? 1 : 0,
  13280. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13281. if ( geometryHash !== _currentGeometryGroupHash ) {
  13282. _currentGeometryGroupHash = geometryHash;
  13283. updateBuffers = true;
  13284. }
  13285. if ( updateBuffers ) {
  13286. disableAttributes();
  13287. }
  13288. // render mesh
  13289. if ( object instanceof THREE.Mesh ) {
  13290. var index = geometryAttributes[ "index" ];
  13291. // indexed triangles
  13292. if ( index ) {
  13293. var offsets = geometry.offsets;
  13294. // if there is more than 1 chunk
  13295. // must set attribute pointers to use new offsets for each chunk
  13296. // even if geometry and materials didn't change
  13297. if ( offsets.length > 1 ) updateBuffers = true;
  13298. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13299. var startIndex = offsets[ i ].index;
  13300. if ( updateBuffers ) {
  13301. for ( attributeName in programAttributes ) {
  13302. attributePointer = programAttributes[ attributeName ];
  13303. attributeItem = geometryAttributes[ attributeName ];
  13304. if ( attributePointer >= 0 ) {
  13305. if ( attributeItem ) {
  13306. attributeSize = attributeItem.itemSize;
  13307. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13308. enableAttribute( attributePointer );
  13309. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13310. } else if ( material.defaultAttributeValues ) {
  13311. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13312. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13313. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13314. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13315. }
  13316. }
  13317. }
  13318. }
  13319. // indices
  13320. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13321. }
  13322. // render indexed triangles
  13323. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  13324. _this.info.render.calls ++;
  13325. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13326. _this.info.render.faces += offsets[ i ].count / 3;
  13327. }
  13328. // non-indexed triangles
  13329. } else {
  13330. if ( updateBuffers ) {
  13331. for ( attributeName in programAttributes ) {
  13332. if ( attributeName === 'index') continue;
  13333. attributePointer = programAttributes[ attributeName ];
  13334. attributeItem = geometryAttributes[ attributeName ];
  13335. if ( attributePointer >= 0 ) {
  13336. if ( attributeItem ) {
  13337. attributeSize = attributeItem.itemSize;
  13338. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13339. enableAttribute( attributePointer );
  13340. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13341. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13342. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13343. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13344. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13345. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13346. }
  13347. }
  13348. }
  13349. }
  13350. }
  13351. var position = geometry.attributes[ "position" ];
  13352. // render non-indexed triangles
  13353. _gl.drawArrays( _gl.TRIANGLES, 0, position.array.length / 3 );
  13354. _this.info.render.calls ++;
  13355. _this.info.render.vertices += position.array.length / 3;
  13356. _this.info.render.faces += position.array.length / 3 / 3;
  13357. }
  13358. // render particles
  13359. } else if ( object instanceof THREE.ParticleSystem ) {
  13360. if ( updateBuffers ) {
  13361. for ( attributeName in programAttributes ) {
  13362. attributePointer = programAttributes[ attributeName ];
  13363. attributeItem = geometryAttributes[ attributeName ];
  13364. if ( attributePointer >= 0 ) {
  13365. if ( attributeItem ) {
  13366. attributeSize = attributeItem.itemSize;
  13367. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13368. enableAttribute( attributePointer );
  13369. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13370. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13371. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13372. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13373. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13374. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13375. }
  13376. }
  13377. }
  13378. }
  13379. }
  13380. var position = geometryAttributes[ "position" ];
  13381. // render particles
  13382. _gl.drawArrays( _gl.POINTS, 0, position.array.length / 3 );
  13383. _this.info.render.calls ++;
  13384. _this.info.render.points += position.array.length / 3;
  13385. } else if ( object instanceof THREE.Line ) {
  13386. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13387. setLineWidth( material.linewidth );
  13388. var index = geometryAttributes[ "index" ];
  13389. // indexed lines
  13390. if ( index ) {
  13391. var offsets = geometry.offsets;
  13392. // if there is more than 1 chunk
  13393. // must set attribute pointers to use new offsets for each chunk
  13394. // even if geometry and materials didn't change
  13395. if ( offsets.length > 1 ) updateBuffers = true;
  13396. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13397. var startIndex = offsets[ i ].index;
  13398. if ( updateBuffers ) {
  13399. setupLinesVertexAttributes(material, programAttributes, geometryAttributes, startIndex);
  13400. // indices
  13401. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13402. }
  13403. // render indexed lines
  13404. _gl.drawElements( _gl.LINES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16Array
  13405. _this.info.render.calls ++;
  13406. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13407. }
  13408. }
  13409. // non-indexed lines
  13410. else {
  13411. if ( updateBuffers ) {
  13412. setupLinesVertexAttributes(material, programAttributes, geometryAttributes, 0);
  13413. }
  13414. var position = geometryAttributes[ "position" ];
  13415. _gl.drawArrays( primitives, 0, position.array.length / 3 );
  13416. _this.info.render.calls ++;
  13417. _this.info.render.points += position.array.length;
  13418. }
  13419. }
  13420. };
  13421. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13422. if ( material.visible === false ) return;
  13423. var linewidth, a, attribute, i, il;
  13424. var program = setProgram( camera, lights, fog, material, object );
  13425. var attributes = program.attributes;
  13426. var updateBuffers = false,
  13427. wireframeBit = material.wireframe ? 1 : 0,
  13428. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13429. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13430. _currentGeometryGroupHash = geometryGroupHash;
  13431. updateBuffers = true;
  13432. }
  13433. if ( updateBuffers ) {
  13434. disableAttributes();
  13435. }
  13436. // vertices
  13437. if ( !material.morphTargets && attributes.position >= 0 ) {
  13438. if ( updateBuffers ) {
  13439. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13440. enableAttribute( attributes.position );
  13441. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13442. }
  13443. } else {
  13444. if ( object.morphTargetBase ) {
  13445. setupMorphTargets( material, geometryGroup, object );
  13446. }
  13447. }
  13448. if ( updateBuffers ) {
  13449. // custom attributes
  13450. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13451. if ( geometryGroup.__webglCustomAttributesList ) {
  13452. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13453. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13454. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13455. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13456. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13457. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13458. }
  13459. }
  13460. }
  13461. // colors
  13462. if ( attributes.color >= 0 ) {
  13463. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  13464. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13465. enableAttribute( attributes.color );
  13466. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13467. } else if ( material.defaultAttributeValues ) {
  13468. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  13469. }
  13470. }
  13471. // normals
  13472. if ( attributes.normal >= 0 ) {
  13473. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13474. enableAttribute( attributes.normal );
  13475. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13476. }
  13477. // tangents
  13478. if ( attributes.tangent >= 0 ) {
  13479. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13480. enableAttribute( attributes.tangent );
  13481. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13482. }
  13483. // uvs
  13484. if ( attributes.uv >= 0 ) {
  13485. if ( object.geometry.faceVertexUvs[0] ) {
  13486. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13487. enableAttribute( attributes.uv );
  13488. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13489. } else if ( material.defaultAttributeValues ) {
  13490. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  13491. }
  13492. }
  13493. if ( attributes.uv2 >= 0 ) {
  13494. if ( object.geometry.faceVertexUvs[1] ) {
  13495. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13496. enableAttribute( attributes.uv2 );
  13497. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13498. } else if ( material.defaultAttributeValues ) {
  13499. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  13500. }
  13501. }
  13502. if ( material.skinning &&
  13503. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13504. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13505. enableAttribute( attributes.skinIndex );
  13506. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13507. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13508. enableAttribute( attributes.skinWeight );
  13509. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13510. }
  13511. // line distances
  13512. if ( attributes.lineDistance >= 0 ) {
  13513. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13514. enableAttribute( attributes.lineDistance );
  13515. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13516. }
  13517. }
  13518. // render mesh
  13519. if ( object instanceof THREE.Mesh ) {
  13520. // wireframe
  13521. if ( material.wireframe ) {
  13522. setLineWidth( material.wireframeLinewidth );
  13523. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13524. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  13525. // triangles
  13526. } else {
  13527. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13528. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  13529. }
  13530. _this.info.render.calls ++;
  13531. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13532. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13533. // render lines
  13534. } else if ( object instanceof THREE.Line ) {
  13535. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13536. setLineWidth( material.linewidth );
  13537. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  13538. _this.info.render.calls ++;
  13539. // render particles
  13540. } else if ( object instanceof THREE.ParticleSystem ) {
  13541. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13542. _this.info.render.calls ++;
  13543. _this.info.render.points += geometryGroup.__webglParticleCount;
  13544. }
  13545. };
  13546. function enableAttribute( attribute ) {
  13547. if ( ! _enabledAttributes[ attribute ] ) {
  13548. _gl.enableVertexAttribArray( attribute );
  13549. _enabledAttributes[ attribute ] = true;
  13550. }
  13551. };
  13552. function disableAttributes() {
  13553. for ( var attribute in _enabledAttributes ) {
  13554. if ( _enabledAttributes[ attribute ] ) {
  13555. _gl.disableVertexAttribArray( attribute );
  13556. _enabledAttributes[ attribute ] = false;
  13557. }
  13558. }
  13559. };
  13560. function setupMorphTargets ( material, geometryGroup, object ) {
  13561. // set base
  13562. var attributes = material.program.attributes;
  13563. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13564. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13565. enableAttribute( attributes.position );
  13566. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13567. } else if ( attributes.position >= 0 ) {
  13568. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13569. enableAttribute( attributes.position );
  13570. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13571. }
  13572. if ( object.morphTargetForcedOrder.length ) {
  13573. // set forced order
  13574. var m = 0;
  13575. var order = object.morphTargetForcedOrder;
  13576. var influences = object.morphTargetInfluences;
  13577. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13578. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13579. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13580. enableAttribute( attributes[ "morphTarget" + m ] );
  13581. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13582. }
  13583. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13584. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13585. enableAttribute( attributes[ "morphNormal" + m ] );
  13586. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13587. }
  13588. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13589. m ++;
  13590. }
  13591. } else {
  13592. // find the most influencing
  13593. var influence, activeInfluenceIndices = [];
  13594. var influences = object.morphTargetInfluences;
  13595. var i, il = influences.length;
  13596. for ( i = 0; i < il; i ++ ) {
  13597. influence = influences[ i ];
  13598. if ( influence > 0 ) {
  13599. activeInfluenceIndices.push( [ influence, i ] );
  13600. }
  13601. }
  13602. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13603. activeInfluenceIndices.sort( numericalSort );
  13604. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13605. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13606. activeInfluenceIndices.sort( numericalSort );
  13607. } else if ( activeInfluenceIndices.length === 0 ) {
  13608. activeInfluenceIndices.push( [ 0, 0 ] );
  13609. };
  13610. var influenceIndex, m = 0;
  13611. while ( m < material.numSupportedMorphTargets ) {
  13612. if ( activeInfluenceIndices[ m ] ) {
  13613. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13614. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13615. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13616. enableAttribute( attributes[ "morphTarget" + m ] );
  13617. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13618. }
  13619. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13620. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13621. enableAttribute( attributes[ "morphNormal" + m ] );
  13622. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13623. }
  13624. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13625. } else {
  13626. /*
  13627. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13628. if ( material.morphNormals ) {
  13629. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13630. }
  13631. */
  13632. object.__webglMorphTargetInfluences[ m ] = 0;
  13633. }
  13634. m ++;
  13635. }
  13636. }
  13637. // load updated influences uniform
  13638. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13639. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13640. }
  13641. };
  13642. // Sorting
  13643. function painterSortStable ( a, b ) {
  13644. if ( a.z !== b.z ) {
  13645. return b.z - a.z;
  13646. } else {
  13647. return a.id - b.id;
  13648. }
  13649. };
  13650. function numericalSort ( a, b ) {
  13651. return b[ 0 ] - a[ 0 ];
  13652. };
  13653. // Rendering
  13654. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13655. if ( camera instanceof THREE.Camera === false ) {
  13656. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13657. return;
  13658. }
  13659. var i, il,
  13660. webglObject, object,
  13661. renderList,
  13662. lights = scene.__lights,
  13663. fog = scene.fog;
  13664. // reset caching for this frame
  13665. _currentMaterialId = -1;
  13666. _lightsNeedUpdate = true;
  13667. // update scene graph
  13668. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13669. // update camera matrices and frustum
  13670. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13671. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13672. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13673. _frustum.setFromMatrix( _projScreenMatrix );
  13674. // update WebGL objects
  13675. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13676. // custom render plugins (pre pass)
  13677. renderPlugins( this.renderPluginsPre, scene, camera );
  13678. //
  13679. _this.info.render.calls = 0;
  13680. _this.info.render.vertices = 0;
  13681. _this.info.render.faces = 0;
  13682. _this.info.render.points = 0;
  13683. this.setRenderTarget( renderTarget );
  13684. if ( this.autoClear || forceClear ) {
  13685. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13686. }
  13687. // set matrices for regular objects (frustum culled)
  13688. renderList = scene.__webglObjects;
  13689. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13690. webglObject = renderList[ i ];
  13691. object = webglObject.object;
  13692. webglObject.id = i;
  13693. webglObject.render = false;
  13694. if ( object.visible ) {
  13695. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  13696. setupMatrices( object, camera );
  13697. unrollBufferMaterial( webglObject );
  13698. webglObject.render = true;
  13699. if ( this.sortObjects === true ) {
  13700. if ( object.renderDepth !== null ) {
  13701. webglObject.z = object.renderDepth;
  13702. } else {
  13703. _vector3.setFromMatrixPosition( object.matrixWorld );
  13704. _vector3.applyProjection( _projScreenMatrix );
  13705. webglObject.z = _vector3.z;
  13706. }
  13707. }
  13708. }
  13709. }
  13710. }
  13711. if ( this.sortObjects ) {
  13712. renderList.sort( painterSortStable );
  13713. }
  13714. // set matrices for immediate objects
  13715. renderList = scene.__webglObjectsImmediate;
  13716. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13717. webglObject = renderList[ i ];
  13718. object = webglObject.object;
  13719. if ( object.visible ) {
  13720. setupMatrices( object, camera );
  13721. unrollImmediateBufferMaterial( webglObject );
  13722. }
  13723. }
  13724. if ( scene.overrideMaterial ) {
  13725. var material = scene.overrideMaterial;
  13726. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13727. this.setDepthTest( material.depthTest );
  13728. this.setDepthWrite( material.depthWrite );
  13729. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13730. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13731. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13732. } else {
  13733. var material = null;
  13734. // opaque pass (front-to-back order)
  13735. this.setBlending( THREE.NoBlending );
  13736. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13737. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13738. // transparent pass (back-to-front order)
  13739. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13740. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13741. }
  13742. // custom render plugins (post pass)
  13743. renderPlugins( this.renderPluginsPost, scene, camera );
  13744. // Generate mipmap if we're using any kind of mipmap filtering
  13745. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13746. updateRenderTargetMipmap( renderTarget );
  13747. }
  13748. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13749. this.setDepthTest( true );
  13750. this.setDepthWrite( true );
  13751. // _gl.finish();
  13752. };
  13753. function renderPlugins( plugins, scene, camera ) {
  13754. if ( ! plugins.length ) return;
  13755. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13756. // reset state for plugin (to start from clean slate)
  13757. _currentProgram = null;
  13758. _currentCamera = null;
  13759. _oldBlending = -1;
  13760. _oldDepthTest = -1;
  13761. _oldDepthWrite = -1;
  13762. _oldDoubleSided = -1;
  13763. _oldFlipSided = -1;
  13764. _currentGeometryGroupHash = -1;
  13765. _currentMaterialId = -1;
  13766. _lightsNeedUpdate = true;
  13767. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13768. // reset state after plugin (anything could have changed)
  13769. _currentProgram = null;
  13770. _currentCamera = null;
  13771. _oldBlending = -1;
  13772. _oldDepthTest = -1;
  13773. _oldDepthWrite = -1;
  13774. _oldDoubleSided = -1;
  13775. _oldFlipSided = -1;
  13776. _currentGeometryGroupHash = -1;
  13777. _currentMaterialId = -1;
  13778. _lightsNeedUpdate = true;
  13779. }
  13780. };
  13781. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13782. var webglObject, object, buffer, material, start, end, delta;
  13783. if ( reverse ) {
  13784. start = renderList.length - 1;
  13785. end = -1;
  13786. delta = -1;
  13787. } else {
  13788. start = 0;
  13789. end = renderList.length;
  13790. delta = 1;
  13791. }
  13792. for ( var i = start; i !== end; i += delta ) {
  13793. webglObject = renderList[ i ];
  13794. if ( webglObject.render ) {
  13795. object = webglObject.object;
  13796. buffer = webglObject.buffer;
  13797. if ( overrideMaterial ) {
  13798. material = overrideMaterial;
  13799. } else {
  13800. material = webglObject[ materialType ];
  13801. if ( ! material ) continue;
  13802. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13803. _this.setDepthTest( material.depthTest );
  13804. _this.setDepthWrite( material.depthWrite );
  13805. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13806. }
  13807. _this.setMaterialFaces( material );
  13808. if ( buffer instanceof THREE.BufferGeometry ) {
  13809. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  13810. } else {
  13811. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  13812. }
  13813. }
  13814. }
  13815. };
  13816. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13817. var webglObject, object, material, program;
  13818. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13819. webglObject = renderList[ i ];
  13820. object = webglObject.object;
  13821. if ( object.visible ) {
  13822. if ( overrideMaterial ) {
  13823. material = overrideMaterial;
  13824. } else {
  13825. material = webglObject[ materialType ];
  13826. if ( ! material ) continue;
  13827. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13828. _this.setDepthTest( material.depthTest );
  13829. _this.setDepthWrite( material.depthWrite );
  13830. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13831. }
  13832. _this.renderImmediateObject( camera, lights, fog, material, object );
  13833. }
  13834. }
  13835. };
  13836. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13837. var program = setProgram( camera, lights, fog, material, object );
  13838. _currentGeometryGroupHash = -1;
  13839. _this.setMaterialFaces( material );
  13840. if ( object.immediateRenderCallback ) {
  13841. object.immediateRenderCallback( program, _gl, _frustum );
  13842. } else {
  13843. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13844. }
  13845. };
  13846. function unrollImmediateBufferMaterial ( globject ) {
  13847. var object = globject.object,
  13848. material = object.material;
  13849. if ( material.transparent ) {
  13850. globject.transparent = material;
  13851. globject.opaque = null;
  13852. } else {
  13853. globject.opaque = material;
  13854. globject.transparent = null;
  13855. }
  13856. };
  13857. function unrollBufferMaterial ( globject ) {
  13858. var object = globject.object,
  13859. buffer = globject.buffer,
  13860. material, materialIndex, meshMaterial;
  13861. meshMaterial = object.material;
  13862. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  13863. materialIndex = buffer.materialIndex;
  13864. material = meshMaterial.materials[ materialIndex ];
  13865. if ( material.transparent ) {
  13866. globject.transparent = material;
  13867. globject.opaque = null;
  13868. } else {
  13869. globject.opaque = material;
  13870. globject.transparent = null;
  13871. }
  13872. } else {
  13873. material = meshMaterial;
  13874. if ( material ) {
  13875. if ( material.transparent ) {
  13876. globject.transparent = material;
  13877. globject.opaque = null;
  13878. } else {
  13879. globject.opaque = material;
  13880. globject.transparent = null;
  13881. }
  13882. }
  13883. }
  13884. };
  13885. // Geometry splitting
  13886. function sortFacesByMaterial ( geometry, material ) {
  13887. var f, fl, face, materialIndex, vertices,
  13888. groupHash, hash_map = {};
  13889. var numMorphTargets = geometry.morphTargets.length;
  13890. var numMorphNormals = geometry.morphNormals.length;
  13891. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  13892. geometry.geometryGroups = {};
  13893. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  13894. face = geometry.faces[ f ];
  13895. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  13896. if ( hash_map[ materialIndex ] === undefined ) {
  13897. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  13898. }
  13899. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13900. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13901. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13902. }
  13903. vertices = 3;
  13904. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  13905. hash_map[ materialIndex ].counter += 1;
  13906. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13907. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13908. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13909. }
  13910. }
  13911. geometry.geometryGroups[ groupHash ].faces3.push( f );
  13912. geometry.geometryGroups[ groupHash ].vertices += vertices;
  13913. }
  13914. geometry.geometryGroupsList = [];
  13915. for ( var g in geometry.geometryGroups ) {
  13916. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  13917. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  13918. }
  13919. };
  13920. // Objects refresh
  13921. this.initWebGLObjects = function ( scene ) {
  13922. if ( !scene.__webglObjects ) {
  13923. scene.__webglObjects = [];
  13924. scene.__webglObjectsImmediate = [];
  13925. scene.__webglSprites = [];
  13926. scene.__webglFlares = [];
  13927. }
  13928. while ( scene.__objectsAdded.length ) {
  13929. addObject( scene.__objectsAdded[ 0 ], scene );
  13930. scene.__objectsAdded.splice( 0, 1 );
  13931. }
  13932. while ( scene.__objectsRemoved.length ) {
  13933. removeObject( scene.__objectsRemoved[ 0 ], scene );
  13934. scene.__objectsRemoved.splice( 0, 1 );
  13935. }
  13936. // update must be called after objects adding / removal
  13937. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  13938. var object = scene.__webglObjects[ o ].object;
  13939. // TODO: Remove this hack (WebGLRenderer refactoring)
  13940. if ( object.__webglInit === undefined ) {
  13941. if ( object.__webglActive !== undefined ) {
  13942. removeObject( object, scene );
  13943. }
  13944. addObject( object, scene );
  13945. }
  13946. updateObject( object );
  13947. }
  13948. };
  13949. // Objects adding
  13950. function addObject( object, scene ) {
  13951. var g, geometry, material, geometryGroup;
  13952. if ( object.__webglInit === undefined ) {
  13953. object.__webglInit = true;
  13954. object._modelViewMatrix = new THREE.Matrix4();
  13955. object._normalMatrix = new THREE.Matrix3();
  13956. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  13957. object.geometry.__webglInit = true;
  13958. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  13959. }
  13960. geometry = object.geometry;
  13961. if ( geometry === undefined ) {
  13962. // fail silently for now
  13963. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13964. initDirectBuffers( geometry );
  13965. } else if ( object instanceof THREE.Mesh ) {
  13966. material = object.material;
  13967. if ( geometry.geometryGroups === undefined ) {
  13968. sortFacesByMaterial( geometry, material );
  13969. }
  13970. // create separate VBOs per geometry chunk
  13971. for ( g in geometry.geometryGroups ) {
  13972. geometryGroup = geometry.geometryGroups[ g ];
  13973. // initialise VBO on the first access
  13974. if ( ! geometryGroup.__webglVertexBuffer ) {
  13975. createMeshBuffers( geometryGroup );
  13976. initMeshBuffers( geometryGroup, object );
  13977. geometry.verticesNeedUpdate = true;
  13978. geometry.morphTargetsNeedUpdate = true;
  13979. geometry.elementsNeedUpdate = true;
  13980. geometry.uvsNeedUpdate = true;
  13981. geometry.normalsNeedUpdate = true;
  13982. geometry.tangentsNeedUpdate = true;
  13983. geometry.colorsNeedUpdate = true;
  13984. }
  13985. }
  13986. } else if ( object instanceof THREE.Line ) {
  13987. if ( ! geometry.__webglVertexBuffer ) {
  13988. createLineBuffers( geometry );
  13989. initLineBuffers( geometry, object );
  13990. geometry.verticesNeedUpdate = true;
  13991. geometry.colorsNeedUpdate = true;
  13992. geometry.lineDistancesNeedUpdate = true;
  13993. }
  13994. } else if ( object instanceof THREE.ParticleSystem ) {
  13995. if ( ! geometry.__webglVertexBuffer ) {
  13996. createParticleBuffers( geometry );
  13997. initParticleBuffers( geometry, object );
  13998. geometry.verticesNeedUpdate = true;
  13999. geometry.colorsNeedUpdate = true;
  14000. }
  14001. }
  14002. }
  14003. if ( object.__webglActive === undefined ) {
  14004. if ( object instanceof THREE.Mesh ) {
  14005. geometry = object.geometry;
  14006. if ( geometry instanceof THREE.BufferGeometry ) {
  14007. addBuffer( scene.__webglObjects, geometry, object );
  14008. } else if ( geometry instanceof THREE.Geometry ) {
  14009. for ( g in geometry.geometryGroups ) {
  14010. geometryGroup = geometry.geometryGroups[ g ];
  14011. addBuffer( scene.__webglObjects, geometryGroup, object );
  14012. }
  14013. }
  14014. } else if ( object instanceof THREE.Line ||
  14015. object instanceof THREE.ParticleSystem ) {
  14016. geometry = object.geometry;
  14017. addBuffer( scene.__webglObjects, geometry, object );
  14018. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14019. addBufferImmediate( scene.__webglObjectsImmediate, object );
  14020. } else if ( object instanceof THREE.Sprite ) {
  14021. scene.__webglSprites.push( object );
  14022. } else if ( object instanceof THREE.LensFlare ) {
  14023. scene.__webglFlares.push( object );
  14024. }
  14025. object.__webglActive = true;
  14026. }
  14027. };
  14028. function addBuffer( objlist, buffer, object ) {
  14029. objlist.push(
  14030. {
  14031. id: null,
  14032. buffer: buffer,
  14033. object: object,
  14034. opaque: null,
  14035. transparent: null,
  14036. z: 0
  14037. }
  14038. );
  14039. };
  14040. function addBufferImmediate( objlist, object ) {
  14041. objlist.push(
  14042. {
  14043. id: null,
  14044. object: object,
  14045. opaque: null,
  14046. transparent: null,
  14047. z: 0
  14048. }
  14049. );
  14050. };
  14051. // Objects updates
  14052. function updateObject( object ) {
  14053. var geometry = object.geometry,
  14054. geometryGroup, customAttributesDirty, material;
  14055. if ( geometry instanceof THREE.BufferGeometry ) {
  14056. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  14057. } else if ( object instanceof THREE.Mesh ) {
  14058. // check all geometry groups
  14059. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  14060. geometryGroup = geometry.geometryGroupsList[ i ];
  14061. material = getBufferMaterial( object, geometryGroup );
  14062. if ( geometry.buffersNeedUpdate ) {
  14063. initMeshBuffers( geometryGroup, object );
  14064. }
  14065. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14066. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  14067. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  14068. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  14069. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  14070. }
  14071. }
  14072. geometry.verticesNeedUpdate = false;
  14073. geometry.morphTargetsNeedUpdate = false;
  14074. geometry.elementsNeedUpdate = false;
  14075. geometry.uvsNeedUpdate = false;
  14076. geometry.normalsNeedUpdate = false;
  14077. geometry.colorsNeedUpdate = false;
  14078. geometry.tangentsNeedUpdate = false;
  14079. geometry.buffersNeedUpdate = false;
  14080. material.attributes && clearCustomAttributes( material );
  14081. } else if ( object instanceof THREE.Line ) {
  14082. material = getBufferMaterial( object, geometry );
  14083. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14084. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  14085. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  14086. }
  14087. geometry.verticesNeedUpdate = false;
  14088. geometry.colorsNeedUpdate = false;
  14089. geometry.lineDistancesNeedUpdate = false;
  14090. material.attributes && clearCustomAttributes( material );
  14091. } else if ( object instanceof THREE.ParticleSystem ) {
  14092. material = getBufferMaterial( object, geometry );
  14093. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14094. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  14095. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  14096. }
  14097. geometry.verticesNeedUpdate = false;
  14098. geometry.colorsNeedUpdate = false;
  14099. material.attributes && clearCustomAttributes( material );
  14100. }
  14101. };
  14102. // Objects updates - custom attributes check
  14103. function areCustomAttributesDirty( material ) {
  14104. for ( var a in material.attributes ) {
  14105. if ( material.attributes[ a ].needsUpdate ) return true;
  14106. }
  14107. return false;
  14108. };
  14109. function clearCustomAttributes( material ) {
  14110. for ( var a in material.attributes ) {
  14111. material.attributes[ a ].needsUpdate = false;
  14112. }
  14113. };
  14114. // Objects removal
  14115. function removeObject( object, scene ) {
  14116. if ( object instanceof THREE.Mesh ||
  14117. object instanceof THREE.ParticleSystem ||
  14118. object instanceof THREE.Line ) {
  14119. removeInstances( scene.__webglObjects, object );
  14120. } else if ( object instanceof THREE.Sprite ) {
  14121. removeInstancesDirect( scene.__webglSprites, object );
  14122. } else if ( object instanceof THREE.LensFlare ) {
  14123. removeInstancesDirect( scene.__webglFlares, object );
  14124. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14125. removeInstances( scene.__webglObjectsImmediate, object );
  14126. }
  14127. delete object.__webglActive;
  14128. };
  14129. function removeInstances( objlist, object ) {
  14130. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14131. if ( objlist[ o ].object === object ) {
  14132. objlist.splice( o, 1 );
  14133. }
  14134. }
  14135. };
  14136. function removeInstancesDirect( objlist, object ) {
  14137. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14138. if ( objlist[ o ] === object ) {
  14139. objlist.splice( o, 1 );
  14140. }
  14141. }
  14142. };
  14143. // Materials
  14144. this.initMaterial = function ( material, lights, fog, object ) {
  14145. material.addEventListener( 'dispose', onMaterialDispose );
  14146. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  14147. if ( material instanceof THREE.MeshDepthMaterial ) {
  14148. shaderID = 'depth';
  14149. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14150. shaderID = 'normal';
  14151. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  14152. shaderID = 'basic';
  14153. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14154. shaderID = 'lambert';
  14155. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14156. shaderID = 'phong';
  14157. } else if ( material instanceof THREE.LineBasicMaterial ) {
  14158. shaderID = 'basic';
  14159. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14160. shaderID = 'dashed';
  14161. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  14162. shaderID = 'particle_basic';
  14163. }
  14164. if ( shaderID ) {
  14165. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  14166. }
  14167. // heuristics to create shader parameters according to lights in the scene
  14168. // (not to blow over maxLights budget)
  14169. maxLightCount = allocateLights( lights );
  14170. maxShadows = allocateShadows( lights );
  14171. maxBones = allocateBones( object );
  14172. parameters = {
  14173. map: !!material.map,
  14174. envMap: !!material.envMap,
  14175. lightMap: !!material.lightMap,
  14176. bumpMap: !!material.bumpMap,
  14177. normalMap: !!material.normalMap,
  14178. specularMap: !!material.specularMap,
  14179. vertexColors: material.vertexColors,
  14180. fog: fog,
  14181. useFog: material.fog,
  14182. fogExp: fog instanceof THREE.FogExp2,
  14183. sizeAttenuation: material.sizeAttenuation,
  14184. skinning: material.skinning,
  14185. maxBones: maxBones,
  14186. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  14187. morphTargets: material.morphTargets,
  14188. morphNormals: material.morphNormals,
  14189. maxMorphTargets: this.maxMorphTargets,
  14190. maxMorphNormals: this.maxMorphNormals,
  14191. maxDirLights: maxLightCount.directional,
  14192. maxPointLights: maxLightCount.point,
  14193. maxSpotLights: maxLightCount.spot,
  14194. maxHemiLights: maxLightCount.hemi,
  14195. maxShadows: maxShadows,
  14196. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  14197. shadowMapType: this.shadowMapType,
  14198. shadowMapDebug: this.shadowMapDebug,
  14199. shadowMapCascade: this.shadowMapCascade,
  14200. alphaTest: material.alphaTest,
  14201. metal: material.metal,
  14202. wrapAround: material.wrapAround,
  14203. doubleSided: material.side === THREE.DoubleSide,
  14204. flipSided: material.side === THREE.BackSide
  14205. };
  14206. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters, material.index0AttributeName );
  14207. var attributes = material.program.attributes;
  14208. if ( material.morphTargets ) {
  14209. material.numSupportedMorphTargets = 0;
  14210. var id, base = "morphTarget";
  14211. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  14212. id = base + i;
  14213. if ( attributes[ id ] >= 0 ) {
  14214. material.numSupportedMorphTargets ++;
  14215. }
  14216. }
  14217. }
  14218. if ( material.morphNormals ) {
  14219. material.numSupportedMorphNormals = 0;
  14220. var id, base = "morphNormal";
  14221. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  14222. id = base + i;
  14223. if ( attributes[ id ] >= 0 ) {
  14224. material.numSupportedMorphNormals ++;
  14225. }
  14226. }
  14227. }
  14228. material.uniformsList = [];
  14229. for ( u in material.uniforms ) {
  14230. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14231. }
  14232. };
  14233. function setMaterialShaders( material, shaders ) {
  14234. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14235. material.vertexShader = shaders.vertexShader;
  14236. material.fragmentShader = shaders.fragmentShader;
  14237. };
  14238. function setProgram( camera, lights, fog, material, object ) {
  14239. _usedTextureUnits = 0;
  14240. if ( material.needsUpdate ) {
  14241. if ( material.program ) deallocateMaterial( material );
  14242. _this.initMaterial( material, lights, fog, object );
  14243. material.needsUpdate = false;
  14244. }
  14245. if ( material.morphTargets ) {
  14246. if ( ! object.__webglMorphTargetInfluences ) {
  14247. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14248. }
  14249. }
  14250. var refreshMaterial = false;
  14251. var program = material.program,
  14252. p_uniforms = program.uniforms,
  14253. m_uniforms = material.uniforms;
  14254. if ( program !== _currentProgram ) {
  14255. _gl.useProgram( program );
  14256. _currentProgram = program;
  14257. refreshMaterial = true;
  14258. }
  14259. if ( material.id !== _currentMaterialId ) {
  14260. _currentMaterialId = material.id;
  14261. refreshMaterial = true;
  14262. }
  14263. if ( refreshMaterial || camera !== _currentCamera ) {
  14264. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14265. if ( camera !== _currentCamera ) _currentCamera = camera;
  14266. }
  14267. // skinning uniforms must be set even if material didn't change
  14268. // auto-setting of texture unit for bone texture must go before other textures
  14269. // not sure why, but otherwise weird things happen
  14270. if ( material.skinning ) {
  14271. if ( _supportsBoneTextures && object.useVertexTexture ) {
  14272. if ( p_uniforms.boneTexture !== null ) {
  14273. var textureUnit = getTextureUnit();
  14274. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14275. _this.setTexture( object.boneTexture, textureUnit );
  14276. }
  14277. if ( p_uniforms.boneTextureWidth !== null ) {
  14278. _gl.uniform1i( p_uniforms.boneTextureWidth, object.boneTextureWidth );
  14279. }
  14280. if ( p_uniforms.boneTextureHeight !== null ) {
  14281. _gl.uniform1i( p_uniforms.boneTextureHeight, object.boneTextureHeight );
  14282. }
  14283. } else {
  14284. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14285. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  14286. }
  14287. }
  14288. }
  14289. if ( refreshMaterial ) {
  14290. // refresh uniforms common to several materials
  14291. if ( fog && material.fog ) {
  14292. refreshUniformsFog( m_uniforms, fog );
  14293. }
  14294. if ( material instanceof THREE.MeshPhongMaterial ||
  14295. material instanceof THREE.MeshLambertMaterial ||
  14296. material.lights ) {
  14297. if ( _lightsNeedUpdate ) {
  14298. setupLights( program, lights );
  14299. _lightsNeedUpdate = false;
  14300. }
  14301. refreshUniformsLights( m_uniforms, _lights );
  14302. }
  14303. if ( material instanceof THREE.MeshBasicMaterial ||
  14304. material instanceof THREE.MeshLambertMaterial ||
  14305. material instanceof THREE.MeshPhongMaterial ) {
  14306. refreshUniformsCommon( m_uniforms, material );
  14307. }
  14308. // refresh single material specific uniforms
  14309. if ( material instanceof THREE.LineBasicMaterial ) {
  14310. refreshUniformsLine( m_uniforms, material );
  14311. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14312. refreshUniformsLine( m_uniforms, material );
  14313. refreshUniformsDash( m_uniforms, material );
  14314. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  14315. refreshUniformsParticle( m_uniforms, material );
  14316. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14317. refreshUniformsPhong( m_uniforms, material );
  14318. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14319. refreshUniformsLambert( m_uniforms, material );
  14320. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14321. m_uniforms.mNear.value = camera.near;
  14322. m_uniforms.mFar.value = camera.far;
  14323. m_uniforms.opacity.value = material.opacity;
  14324. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14325. m_uniforms.opacity.value = material.opacity;
  14326. }
  14327. if ( object.receiveShadow && ! material._shadowPass ) {
  14328. refreshUniformsShadow( m_uniforms, lights );
  14329. }
  14330. // load common uniforms
  14331. loadUniformsGeneric( program, material.uniformsList );
  14332. // load material specific uniforms
  14333. // (shader material also gets them for the sake of genericity)
  14334. if ( material instanceof THREE.ShaderMaterial ||
  14335. material instanceof THREE.MeshPhongMaterial ||
  14336. material.envMap ) {
  14337. if ( p_uniforms.cameraPosition !== null ) {
  14338. _vector3.setFromMatrixPosition( camera.matrixWorld );
  14339. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14340. }
  14341. }
  14342. if ( material instanceof THREE.MeshPhongMaterial ||
  14343. material instanceof THREE.MeshLambertMaterial ||
  14344. material instanceof THREE.ShaderMaterial ||
  14345. material.skinning ) {
  14346. if ( p_uniforms.viewMatrix !== null ) {
  14347. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14348. }
  14349. }
  14350. }
  14351. loadUniformsMatrices( p_uniforms, object );
  14352. if ( p_uniforms.modelMatrix !== null ) {
  14353. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14354. }
  14355. return program;
  14356. };
  14357. // Uniforms (refresh uniforms objects)
  14358. function refreshUniformsCommon ( uniforms, material ) {
  14359. uniforms.opacity.value = material.opacity;
  14360. if ( _this.gammaInput ) {
  14361. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14362. } else {
  14363. uniforms.diffuse.value = material.color;
  14364. }
  14365. uniforms.map.value = material.map;
  14366. uniforms.lightMap.value = material.lightMap;
  14367. uniforms.specularMap.value = material.specularMap;
  14368. if ( material.bumpMap ) {
  14369. uniforms.bumpMap.value = material.bumpMap;
  14370. uniforms.bumpScale.value = material.bumpScale;
  14371. }
  14372. if ( material.normalMap ) {
  14373. uniforms.normalMap.value = material.normalMap;
  14374. uniforms.normalScale.value.copy( material.normalScale );
  14375. }
  14376. // uv repeat and offset setting priorities
  14377. // 1. color map
  14378. // 2. specular map
  14379. // 3. normal map
  14380. // 4. bump map
  14381. var uvScaleMap;
  14382. if ( material.map ) {
  14383. uvScaleMap = material.map;
  14384. } else if ( material.specularMap ) {
  14385. uvScaleMap = material.specularMap;
  14386. } else if ( material.normalMap ) {
  14387. uvScaleMap = material.normalMap;
  14388. } else if ( material.bumpMap ) {
  14389. uvScaleMap = material.bumpMap;
  14390. }
  14391. if ( uvScaleMap !== undefined ) {
  14392. var offset = uvScaleMap.offset;
  14393. var repeat = uvScaleMap.repeat;
  14394. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14395. }
  14396. uniforms.envMap.value = material.envMap;
  14397. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14398. if ( _this.gammaInput ) {
  14399. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14400. uniforms.reflectivity.value = material.reflectivity;
  14401. } else {
  14402. uniforms.reflectivity.value = material.reflectivity;
  14403. }
  14404. uniforms.refractionRatio.value = material.refractionRatio;
  14405. uniforms.combine.value = material.combine;
  14406. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14407. };
  14408. function refreshUniformsLine ( uniforms, material ) {
  14409. uniforms.diffuse.value = material.color;
  14410. uniforms.opacity.value = material.opacity;
  14411. };
  14412. function refreshUniformsDash ( uniforms, material ) {
  14413. uniforms.dashSize.value = material.dashSize;
  14414. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14415. uniforms.scale.value = material.scale;
  14416. };
  14417. function refreshUniformsParticle ( uniforms, material ) {
  14418. uniforms.psColor.value = material.color;
  14419. uniforms.opacity.value = material.opacity;
  14420. uniforms.size.value = material.size;
  14421. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14422. uniforms.map.value = material.map;
  14423. };
  14424. function refreshUniformsFog ( uniforms, fog ) {
  14425. uniforms.fogColor.value = fog.color;
  14426. if ( fog instanceof THREE.Fog ) {
  14427. uniforms.fogNear.value = fog.near;
  14428. uniforms.fogFar.value = fog.far;
  14429. } else if ( fog instanceof THREE.FogExp2 ) {
  14430. uniforms.fogDensity.value = fog.density;
  14431. }
  14432. };
  14433. function refreshUniformsPhong ( uniforms, material ) {
  14434. uniforms.shininess.value = material.shininess;
  14435. if ( _this.gammaInput ) {
  14436. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14437. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14438. uniforms.specular.value.copyGammaToLinear( material.specular );
  14439. } else {
  14440. uniforms.ambient.value = material.ambient;
  14441. uniforms.emissive.value = material.emissive;
  14442. uniforms.specular.value = material.specular;
  14443. }
  14444. if ( material.wrapAround ) {
  14445. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14446. }
  14447. };
  14448. function refreshUniformsLambert ( uniforms, material ) {
  14449. if ( _this.gammaInput ) {
  14450. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14451. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14452. } else {
  14453. uniforms.ambient.value = material.ambient;
  14454. uniforms.emissive.value = material.emissive;
  14455. }
  14456. if ( material.wrapAround ) {
  14457. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14458. }
  14459. };
  14460. function refreshUniformsLights ( uniforms, lights ) {
  14461. uniforms.ambientLightColor.value = lights.ambient;
  14462. uniforms.directionalLightColor.value = lights.directional.colors;
  14463. uniforms.directionalLightDirection.value = lights.directional.positions;
  14464. uniforms.pointLightColor.value = lights.point.colors;
  14465. uniforms.pointLightPosition.value = lights.point.positions;
  14466. uniforms.pointLightDistance.value = lights.point.distances;
  14467. uniforms.spotLightColor.value = lights.spot.colors;
  14468. uniforms.spotLightPosition.value = lights.spot.positions;
  14469. uniforms.spotLightDistance.value = lights.spot.distances;
  14470. uniforms.spotLightDirection.value = lights.spot.directions;
  14471. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14472. uniforms.spotLightExponent.value = lights.spot.exponents;
  14473. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14474. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14475. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14476. };
  14477. function refreshUniformsShadow ( uniforms, lights ) {
  14478. if ( uniforms.shadowMatrix ) {
  14479. var j = 0;
  14480. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14481. var light = lights[ i ];
  14482. if ( ! light.castShadow ) continue;
  14483. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14484. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14485. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14486. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14487. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14488. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14489. j ++;
  14490. }
  14491. }
  14492. }
  14493. };
  14494. // Uniforms (load to GPU)
  14495. function loadUniformsMatrices ( uniforms, object ) {
  14496. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14497. if ( uniforms.normalMatrix ) {
  14498. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14499. }
  14500. };
  14501. function getTextureUnit() {
  14502. var textureUnit = _usedTextureUnits;
  14503. if ( textureUnit >= _maxTextures ) {
  14504. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14505. }
  14506. _usedTextureUnits += 1;
  14507. return textureUnit;
  14508. };
  14509. function loadUniformsGeneric ( program, uniforms ) {
  14510. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14511. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14512. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14513. if ( !location ) continue;
  14514. uniform = uniforms[ j ][ 0 ];
  14515. type = uniform.type;
  14516. value = uniform.value;
  14517. if ( type === "i" ) { // single integer
  14518. _gl.uniform1i( location, value );
  14519. } else if ( type === "f" ) { // single float
  14520. _gl.uniform1f( location, value );
  14521. } else if ( type === "v2" ) { // single THREE.Vector2
  14522. _gl.uniform2f( location, value.x, value.y );
  14523. } else if ( type === "v3" ) { // single THREE.Vector3
  14524. _gl.uniform3f( location, value.x, value.y, value.z );
  14525. } else if ( type === "v4" ) { // single THREE.Vector4
  14526. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14527. } else if ( type === "c" ) { // single THREE.Color
  14528. _gl.uniform3f( location, value.r, value.g, value.b );
  14529. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14530. _gl.uniform1iv( location, value );
  14531. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14532. _gl.uniform3iv( location, value );
  14533. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14534. _gl.uniform1fv( location, value );
  14535. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14536. _gl.uniform3fv( location, value );
  14537. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14538. if ( uniform._array === undefined ) {
  14539. uniform._array = new Float32Array( 2 * value.length );
  14540. }
  14541. for ( i = 0, il = value.length; i < il; i ++ ) {
  14542. offset = i * 2;
  14543. uniform._array[ offset ] = value[ i ].x;
  14544. uniform._array[ offset + 1 ] = value[ i ].y;
  14545. }
  14546. _gl.uniform2fv( location, uniform._array );
  14547. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14548. if ( uniform._array === undefined ) {
  14549. uniform._array = new Float32Array( 3 * value.length );
  14550. }
  14551. for ( i = 0, il = value.length; i < il; i ++ ) {
  14552. offset = i * 3;
  14553. uniform._array[ offset ] = value[ i ].x;
  14554. uniform._array[ offset + 1 ] = value[ i ].y;
  14555. uniform._array[ offset + 2 ] = value[ i ].z;
  14556. }
  14557. _gl.uniform3fv( location, uniform._array );
  14558. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14559. if ( uniform._array === undefined ) {
  14560. uniform._array = new Float32Array( 4 * value.length );
  14561. }
  14562. for ( i = 0, il = value.length; i < il; i ++ ) {
  14563. offset = i * 4;
  14564. uniform._array[ offset ] = value[ i ].x;
  14565. uniform._array[ offset + 1 ] = value[ i ].y;
  14566. uniform._array[ offset + 2 ] = value[ i ].z;
  14567. uniform._array[ offset + 3 ] = value[ i ].w;
  14568. }
  14569. _gl.uniform4fv( location, uniform._array );
  14570. } else if ( type === "m4") { // single THREE.Matrix4
  14571. if ( uniform._array === undefined ) {
  14572. uniform._array = new Float32Array( 16 );
  14573. }
  14574. value.flattenToArray( uniform._array );
  14575. _gl.uniformMatrix4fv( location, false, uniform._array );
  14576. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14577. if ( uniform._array === undefined ) {
  14578. uniform._array = new Float32Array( 16 * value.length );
  14579. }
  14580. for ( i = 0, il = value.length; i < il; i ++ ) {
  14581. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14582. }
  14583. _gl.uniformMatrix4fv( location, false, uniform._array );
  14584. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14585. texture = value;
  14586. textureUnit = getTextureUnit();
  14587. _gl.uniform1i( location, textureUnit );
  14588. if ( !texture ) continue;
  14589. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14590. setCubeTexture( texture, textureUnit );
  14591. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14592. setCubeTextureDynamic( texture, textureUnit );
  14593. } else {
  14594. _this.setTexture( texture, textureUnit );
  14595. }
  14596. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14597. if ( uniform._array === undefined ) {
  14598. uniform._array = [];
  14599. }
  14600. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14601. uniform._array[ i ] = getTextureUnit();
  14602. }
  14603. _gl.uniform1iv( location, uniform._array );
  14604. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14605. texture = uniform.value[ i ];
  14606. textureUnit = uniform._array[ i ];
  14607. if ( !texture ) continue;
  14608. _this.setTexture( texture, textureUnit );
  14609. }
  14610. } else {
  14611. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  14612. }
  14613. }
  14614. };
  14615. function setupMatrices ( object, camera ) {
  14616. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14617. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14618. };
  14619. //
  14620. function setColorGamma( array, offset, color, intensitySq ) {
  14621. array[ offset ] = color.r * color.r * intensitySq;
  14622. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14623. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14624. };
  14625. function setColorLinear( array, offset, color, intensity ) {
  14626. array[ offset ] = color.r * intensity;
  14627. array[ offset + 1 ] = color.g * intensity;
  14628. array[ offset + 2 ] = color.b * intensity;
  14629. };
  14630. function setupLights ( program, lights ) {
  14631. var l, ll, light, n,
  14632. r = 0, g = 0, b = 0,
  14633. color, skyColor, groundColor,
  14634. intensity, intensitySq,
  14635. position,
  14636. distance,
  14637. zlights = _lights,
  14638. dirColors = zlights.directional.colors,
  14639. dirPositions = zlights.directional.positions,
  14640. pointColors = zlights.point.colors,
  14641. pointPositions = zlights.point.positions,
  14642. pointDistances = zlights.point.distances,
  14643. spotColors = zlights.spot.colors,
  14644. spotPositions = zlights.spot.positions,
  14645. spotDistances = zlights.spot.distances,
  14646. spotDirections = zlights.spot.directions,
  14647. spotAnglesCos = zlights.spot.anglesCos,
  14648. spotExponents = zlights.spot.exponents,
  14649. hemiSkyColors = zlights.hemi.skyColors,
  14650. hemiGroundColors = zlights.hemi.groundColors,
  14651. hemiPositions = zlights.hemi.positions,
  14652. dirLength = 0,
  14653. pointLength = 0,
  14654. spotLength = 0,
  14655. hemiLength = 0,
  14656. dirCount = 0,
  14657. pointCount = 0,
  14658. spotCount = 0,
  14659. hemiCount = 0,
  14660. dirOffset = 0,
  14661. pointOffset = 0,
  14662. spotOffset = 0,
  14663. hemiOffset = 0;
  14664. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14665. light = lights[ l ];
  14666. if ( light.onlyShadow ) continue;
  14667. color = light.color;
  14668. intensity = light.intensity;
  14669. distance = light.distance;
  14670. if ( light instanceof THREE.AmbientLight ) {
  14671. if ( ! light.visible ) continue;
  14672. if ( _this.gammaInput ) {
  14673. r += color.r * color.r;
  14674. g += color.g * color.g;
  14675. b += color.b * color.b;
  14676. } else {
  14677. r += color.r;
  14678. g += color.g;
  14679. b += color.b;
  14680. }
  14681. } else if ( light instanceof THREE.DirectionalLight ) {
  14682. dirCount += 1;
  14683. if ( ! light.visible ) continue;
  14684. _direction.setFromMatrixPosition( light.matrixWorld );
  14685. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14686. _direction.sub( _vector3 );
  14687. _direction.normalize();
  14688. // skip lights with undefined direction
  14689. // these create troubles in OpenGL (making pixel black)
  14690. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14691. dirOffset = dirLength * 3;
  14692. dirPositions[ dirOffset ] = _direction.x;
  14693. dirPositions[ dirOffset + 1 ] = _direction.y;
  14694. dirPositions[ dirOffset + 2 ] = _direction.z;
  14695. if ( _this.gammaInput ) {
  14696. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14697. } else {
  14698. setColorLinear( dirColors, dirOffset, color, intensity );
  14699. }
  14700. dirLength += 1;
  14701. } else if ( light instanceof THREE.PointLight ) {
  14702. pointCount += 1;
  14703. if ( ! light.visible ) continue;
  14704. pointOffset = pointLength * 3;
  14705. if ( _this.gammaInput ) {
  14706. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14707. } else {
  14708. setColorLinear( pointColors, pointOffset, color, intensity );
  14709. }
  14710. _vector3.setFromMatrixPosition( light.matrixWorld );
  14711. pointPositions[ pointOffset ] = _vector3.x;
  14712. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14713. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14714. pointDistances[ pointLength ] = distance;
  14715. pointLength += 1;
  14716. } else if ( light instanceof THREE.SpotLight ) {
  14717. spotCount += 1;
  14718. if ( ! light.visible ) continue;
  14719. spotOffset = spotLength * 3;
  14720. if ( _this.gammaInput ) {
  14721. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14722. } else {
  14723. setColorLinear( spotColors, spotOffset, color, intensity );
  14724. }
  14725. _vector3.setFromMatrixPosition( light.matrixWorld );
  14726. spotPositions[ spotOffset ] = _vector3.x;
  14727. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14728. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14729. spotDistances[ spotLength ] = distance;
  14730. _direction.copy( _vector3 );
  14731. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14732. _direction.sub( _vector3 );
  14733. _direction.normalize();
  14734. spotDirections[ spotOffset ] = _direction.x;
  14735. spotDirections[ spotOffset + 1 ] = _direction.y;
  14736. spotDirections[ spotOffset + 2 ] = _direction.z;
  14737. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14738. spotExponents[ spotLength ] = light.exponent;
  14739. spotLength += 1;
  14740. } else if ( light instanceof THREE.HemisphereLight ) {
  14741. hemiCount += 1;
  14742. if ( ! light.visible ) continue;
  14743. _direction.setFromMatrixPosition( light.matrixWorld );
  14744. _direction.normalize();
  14745. // skip lights with undefined direction
  14746. // these create troubles in OpenGL (making pixel black)
  14747. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14748. hemiOffset = hemiLength * 3;
  14749. hemiPositions[ hemiOffset ] = _direction.x;
  14750. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14751. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14752. skyColor = light.color;
  14753. groundColor = light.groundColor;
  14754. if ( _this.gammaInput ) {
  14755. intensitySq = intensity * intensity;
  14756. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14757. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14758. } else {
  14759. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14760. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14761. }
  14762. hemiLength += 1;
  14763. }
  14764. }
  14765. // null eventual remains from removed lights
  14766. // (this is to avoid if in shader)
  14767. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14768. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14769. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14770. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14771. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14772. zlights.directional.length = dirLength;
  14773. zlights.point.length = pointLength;
  14774. zlights.spot.length = spotLength;
  14775. zlights.hemi.length = hemiLength;
  14776. zlights.ambient[ 0 ] = r;
  14777. zlights.ambient[ 1 ] = g;
  14778. zlights.ambient[ 2 ] = b;
  14779. };
  14780. // GL state setting
  14781. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14782. if ( cullFace === THREE.CullFaceNone ) {
  14783. _gl.disable( _gl.CULL_FACE );
  14784. } else {
  14785. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14786. _gl.frontFace( _gl.CW );
  14787. } else {
  14788. _gl.frontFace( _gl.CCW );
  14789. }
  14790. if ( cullFace === THREE.CullFaceBack ) {
  14791. _gl.cullFace( _gl.BACK );
  14792. } else if ( cullFace === THREE.CullFaceFront ) {
  14793. _gl.cullFace( _gl.FRONT );
  14794. } else {
  14795. _gl.cullFace( _gl.FRONT_AND_BACK );
  14796. }
  14797. _gl.enable( _gl.CULL_FACE );
  14798. }
  14799. };
  14800. this.setMaterialFaces = function ( material ) {
  14801. var doubleSided = material.side === THREE.DoubleSide;
  14802. var flipSided = material.side === THREE.BackSide;
  14803. if ( _oldDoubleSided !== doubleSided ) {
  14804. if ( doubleSided ) {
  14805. _gl.disable( _gl.CULL_FACE );
  14806. } else {
  14807. _gl.enable( _gl.CULL_FACE );
  14808. }
  14809. _oldDoubleSided = doubleSided;
  14810. }
  14811. if ( _oldFlipSided !== flipSided ) {
  14812. if ( flipSided ) {
  14813. _gl.frontFace( _gl.CW );
  14814. } else {
  14815. _gl.frontFace( _gl.CCW );
  14816. }
  14817. _oldFlipSided = flipSided;
  14818. }
  14819. };
  14820. this.setDepthTest = function ( depthTest ) {
  14821. if ( _oldDepthTest !== depthTest ) {
  14822. if ( depthTest ) {
  14823. _gl.enable( _gl.DEPTH_TEST );
  14824. } else {
  14825. _gl.disable( _gl.DEPTH_TEST );
  14826. }
  14827. _oldDepthTest = depthTest;
  14828. }
  14829. };
  14830. this.setDepthWrite = function ( depthWrite ) {
  14831. if ( _oldDepthWrite !== depthWrite ) {
  14832. _gl.depthMask( depthWrite );
  14833. _oldDepthWrite = depthWrite;
  14834. }
  14835. };
  14836. function setLineWidth ( width ) {
  14837. if ( width !== _oldLineWidth ) {
  14838. _gl.lineWidth( width );
  14839. _oldLineWidth = width;
  14840. }
  14841. };
  14842. function setPolygonOffset ( polygonoffset, factor, units ) {
  14843. if ( _oldPolygonOffset !== polygonoffset ) {
  14844. if ( polygonoffset ) {
  14845. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  14846. } else {
  14847. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  14848. }
  14849. _oldPolygonOffset = polygonoffset;
  14850. }
  14851. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  14852. _gl.polygonOffset( factor, units );
  14853. _oldPolygonOffsetFactor = factor;
  14854. _oldPolygonOffsetUnits = units;
  14855. }
  14856. };
  14857. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  14858. if ( blending !== _oldBlending ) {
  14859. if ( blending === THREE.NoBlending ) {
  14860. _gl.disable( _gl.BLEND );
  14861. } else if ( blending === THREE.AdditiveBlending ) {
  14862. _gl.enable( _gl.BLEND );
  14863. _gl.blendEquation( _gl.FUNC_ADD );
  14864. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  14865. } else if ( blending === THREE.SubtractiveBlending ) {
  14866. // TODO: Find blendFuncSeparate() combination
  14867. _gl.enable( _gl.BLEND );
  14868. _gl.blendEquation( _gl.FUNC_ADD );
  14869. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  14870. } else if ( blending === THREE.MultiplyBlending ) {
  14871. // TODO: Find blendFuncSeparate() combination
  14872. _gl.enable( _gl.BLEND );
  14873. _gl.blendEquation( _gl.FUNC_ADD );
  14874. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  14875. } else if ( blending === THREE.CustomBlending ) {
  14876. _gl.enable( _gl.BLEND );
  14877. } else {
  14878. _gl.enable( _gl.BLEND );
  14879. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  14880. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  14881. }
  14882. _oldBlending = blending;
  14883. }
  14884. if ( blending === THREE.CustomBlending ) {
  14885. if ( blendEquation !== _oldBlendEquation ) {
  14886. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  14887. _oldBlendEquation = blendEquation;
  14888. }
  14889. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  14890. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  14891. _oldBlendSrc = blendSrc;
  14892. _oldBlendDst = blendDst;
  14893. }
  14894. } else {
  14895. _oldBlendEquation = null;
  14896. _oldBlendSrc = null;
  14897. _oldBlendDst = null;
  14898. }
  14899. };
  14900. // Defines
  14901. function generateDefines ( defines ) {
  14902. var value, chunk, chunks = [];
  14903. for ( var d in defines ) {
  14904. value = defines[ d ];
  14905. if ( value === false ) continue;
  14906. chunk = "#define " + d + " " + value;
  14907. chunks.push( chunk );
  14908. }
  14909. return chunks.join( "\n" );
  14910. };
  14911. // Shaders
  14912. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters, index0AttributeName ) {
  14913. var p, pl, d, program, code;
  14914. var chunks = [];
  14915. // Generate code
  14916. if ( shaderID ) {
  14917. chunks.push( shaderID );
  14918. } else {
  14919. chunks.push( fragmentShader );
  14920. chunks.push( vertexShader );
  14921. }
  14922. for ( d in defines ) {
  14923. chunks.push( d );
  14924. chunks.push( defines[ d ] );
  14925. }
  14926. for ( p in parameters ) {
  14927. chunks.push( p );
  14928. chunks.push( parameters[ p ] );
  14929. }
  14930. code = chunks.join();
  14931. // Check if code has been already compiled
  14932. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  14933. var programInfo = _programs[ p ];
  14934. if ( programInfo.code === code ) {
  14935. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  14936. programInfo.usedTimes ++;
  14937. return programInfo.program;
  14938. }
  14939. }
  14940. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  14941. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  14942. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  14943. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  14944. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  14945. }
  14946. // console.log( "building new program " );
  14947. //
  14948. var customDefines = generateDefines( defines );
  14949. //
  14950. program = _gl.createProgram();
  14951. var prefix_vertex = [
  14952. "precision " + _precision + " float;",
  14953. "precision " + _precision + " int;",
  14954. customDefines,
  14955. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  14956. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14957. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14958. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14959. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14960. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14961. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14962. "#define MAX_SHADOWS " + parameters.maxShadows,
  14963. "#define MAX_BONES " + parameters.maxBones,
  14964. parameters.map ? "#define USE_MAP" : "",
  14965. parameters.envMap ? "#define USE_ENVMAP" : "",
  14966. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14967. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14968. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14969. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14970. parameters.vertexColors ? "#define USE_COLOR" : "",
  14971. parameters.skinning ? "#define USE_SKINNING" : "",
  14972. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  14973. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  14974. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  14975. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14976. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14977. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14978. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14979. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14980. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14981. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14982. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  14983. "uniform mat4 modelMatrix;",
  14984. "uniform mat4 modelViewMatrix;",
  14985. "uniform mat4 projectionMatrix;",
  14986. "uniform mat4 viewMatrix;",
  14987. "uniform mat3 normalMatrix;",
  14988. "uniform vec3 cameraPosition;",
  14989. "attribute vec3 position;",
  14990. "attribute vec3 normal;",
  14991. "attribute vec2 uv;",
  14992. "attribute vec2 uv2;",
  14993. "#ifdef USE_COLOR",
  14994. "attribute vec3 color;",
  14995. "#endif",
  14996. "#ifdef USE_MORPHTARGETS",
  14997. "attribute vec3 morphTarget0;",
  14998. "attribute vec3 morphTarget1;",
  14999. "attribute vec3 morphTarget2;",
  15000. "attribute vec3 morphTarget3;",
  15001. "#ifdef USE_MORPHNORMALS",
  15002. "attribute vec3 morphNormal0;",
  15003. "attribute vec3 morphNormal1;",
  15004. "attribute vec3 morphNormal2;",
  15005. "attribute vec3 morphNormal3;",
  15006. "#else",
  15007. "attribute vec3 morphTarget4;",
  15008. "attribute vec3 morphTarget5;",
  15009. "attribute vec3 morphTarget6;",
  15010. "attribute vec3 morphTarget7;",
  15011. "#endif",
  15012. "#endif",
  15013. "#ifdef USE_SKINNING",
  15014. "attribute vec4 skinIndex;",
  15015. "attribute vec4 skinWeight;",
  15016. "#endif",
  15017. ""
  15018. ].join("\n");
  15019. var prefix_fragment = [
  15020. "precision " + _precision + " float;",
  15021. "precision " + _precision + " int;",
  15022. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  15023. customDefines,
  15024. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15025. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15026. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15027. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15028. "#define MAX_SHADOWS " + parameters.maxShadows,
  15029. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  15030. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15031. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15032. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  15033. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  15034. parameters.map ? "#define USE_MAP" : "",
  15035. parameters.envMap ? "#define USE_ENVMAP" : "",
  15036. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15037. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15038. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15039. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15040. parameters.vertexColors ? "#define USE_COLOR" : "",
  15041. parameters.metal ? "#define METAL" : "",
  15042. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15043. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15044. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15045. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15046. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15047. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15048. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15049. "uniform mat4 viewMatrix;",
  15050. "uniform vec3 cameraPosition;",
  15051. ""
  15052. ].join("\n");
  15053. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  15054. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  15055. _gl.attachShader( program, glVertexShader );
  15056. _gl.attachShader( program, glFragmentShader );
  15057. // Force a particular attribute to index 0.
  15058. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  15059. // And, color, for example is often automatically bound to index 0 so disabling it
  15060. if ( index0AttributeName !== undefined ) {
  15061. _gl.bindAttribLocation( program, 0, index0AttributeName );
  15062. } else {
  15063. _gl.bindAttribLocation( program, 0, 'position' );
  15064. }
  15065. _gl.linkProgram( program );
  15066. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  15067. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  15068. console.error( "Program Info Log: " + _gl.getProgramInfoLog( program ) );
  15069. }
  15070. // clean up
  15071. _gl.deleteShader( glFragmentShader );
  15072. _gl.deleteShader( glVertexShader );
  15073. // console.log( prefix_fragment + fragmentShader );
  15074. // console.log( prefix_vertex + vertexShader );
  15075. program.uniforms = {};
  15076. program.attributes = {};
  15077. var identifiers, u, a, i;
  15078. // cache uniform locations
  15079. identifiers = [
  15080. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  15081. 'morphTargetInfluences'
  15082. ];
  15083. if ( parameters.useVertexTexture ) {
  15084. identifiers.push( 'boneTexture' );
  15085. identifiers.push( 'boneTextureWidth' );
  15086. identifiers.push( 'boneTextureHeight' );
  15087. } else {
  15088. identifiers.push( 'boneGlobalMatrices' );
  15089. }
  15090. for ( u in uniforms ) {
  15091. identifiers.push( u );
  15092. }
  15093. cacheUniformLocations( program, identifiers );
  15094. // cache attributes locations
  15095. identifiers = [
  15096. "position", "normal", "uv", "uv2", "tangent", "color",
  15097. "skinIndex", "skinWeight", "lineDistance"
  15098. ];
  15099. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  15100. identifiers.push( "morphTarget" + i );
  15101. }
  15102. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  15103. identifiers.push( "morphNormal" + i );
  15104. }
  15105. for ( a in attributes ) {
  15106. identifiers.push( a );
  15107. }
  15108. cacheAttributeLocations( program, identifiers );
  15109. program.id = _programs_counter ++;
  15110. _programs.push( { program: program, code: code, usedTimes: 1 } );
  15111. _this.info.memory.programs = _programs.length;
  15112. return program;
  15113. };
  15114. // Shader parameters cache
  15115. function cacheUniformLocations ( program, identifiers ) {
  15116. var i, l, id;
  15117. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  15118. id = identifiers[ i ];
  15119. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  15120. }
  15121. };
  15122. function cacheAttributeLocations ( program, identifiers ) {
  15123. var i, l, id;
  15124. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  15125. id = identifiers[ i ];
  15126. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  15127. }
  15128. };
  15129. function addLineNumbers ( string ) {
  15130. var chunks = string.split( "\n" );
  15131. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  15132. // Chrome reports shader errors on lines
  15133. // starting counting from 1
  15134. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  15135. }
  15136. return chunks.join( "\n" );
  15137. };
  15138. function getShader ( type, string ) {
  15139. var shader;
  15140. if ( type === "fragment" ) {
  15141. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  15142. } else if ( type === "vertex" ) {
  15143. shader = _gl.createShader( _gl.VERTEX_SHADER );
  15144. }
  15145. _gl.shaderSource( shader, string );
  15146. _gl.compileShader( shader );
  15147. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  15148. console.error( _gl.getShaderInfoLog( shader ) );
  15149. console.error( addLineNumbers( string ) );
  15150. return null;
  15151. }
  15152. return shader;
  15153. };
  15154. // Textures
  15155. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  15156. if ( isImagePowerOfTwo ) {
  15157. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  15158. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  15159. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  15160. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  15161. } else {
  15162. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  15163. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  15164. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  15165. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  15166. }
  15167. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  15168. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  15169. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  15170. texture.__oldAnisotropy = texture.anisotropy;
  15171. }
  15172. }
  15173. };
  15174. this.setTexture = function ( texture, slot ) {
  15175. if ( texture.needsUpdate ) {
  15176. if ( ! texture.__webglInit ) {
  15177. texture.__webglInit = true;
  15178. texture.addEventListener( 'dispose', onTextureDispose );
  15179. texture.__webglTexture = _gl.createTexture();
  15180. _this.info.memory.textures ++;
  15181. }
  15182. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15183. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15184. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15185. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15186. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15187. var image = texture.image,
  15188. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  15189. glFormat = paramThreeToGL( texture.format ),
  15190. glType = paramThreeToGL( texture.type );
  15191. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  15192. var mipmap, mipmaps = texture.mipmaps;
  15193. if ( texture instanceof THREE.DataTexture ) {
  15194. // use manually created mipmaps if available
  15195. // if there are no manual mipmaps
  15196. // set 0 level mipmap and then use GL to generate other mipmap levels
  15197. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15198. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15199. mipmap = mipmaps[ i ];
  15200. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15201. }
  15202. texture.generateMipmaps = false;
  15203. } else {
  15204. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15205. }
  15206. } else if ( texture instanceof THREE.CompressedTexture ) {
  15207. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15208. mipmap = mipmaps[ i ];
  15209. if ( texture.format!==THREE.RGBAFormat ) {
  15210. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15211. } else {
  15212. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15213. }
  15214. }
  15215. } else { // regular Texture (image, video, canvas)
  15216. // use manually created mipmaps if available
  15217. // if there are no manual mipmaps
  15218. // set 0 level mipmap and then use GL to generate other mipmap levels
  15219. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15220. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15221. mipmap = mipmaps[ i ];
  15222. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15223. }
  15224. texture.generateMipmaps = false;
  15225. } else {
  15226. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  15227. }
  15228. }
  15229. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15230. texture.needsUpdate = false;
  15231. if ( texture.onUpdate ) texture.onUpdate();
  15232. } else {
  15233. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15234. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15235. }
  15236. };
  15237. function clampToMaxSize ( image, maxSize ) {
  15238. if ( image.width <= maxSize && image.height <= maxSize ) {
  15239. return image;
  15240. }
  15241. // Warning: Scaling through the canvas will only work with images that use
  15242. // premultiplied alpha.
  15243. var maxDimension = Math.max( image.width, image.height );
  15244. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15245. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15246. var canvas = document.createElement( 'canvas' );
  15247. canvas.width = newWidth;
  15248. canvas.height = newHeight;
  15249. var ctx = canvas.getContext( "2d" );
  15250. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15251. return canvas;
  15252. }
  15253. function setCubeTexture ( texture, slot ) {
  15254. if ( texture.image.length === 6 ) {
  15255. if ( texture.needsUpdate ) {
  15256. if ( ! texture.image.__webglTextureCube ) {
  15257. texture.addEventListener( 'dispose', onTextureDispose );
  15258. texture.image.__webglTextureCube = _gl.createTexture();
  15259. _this.info.memory.textures ++;
  15260. }
  15261. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15262. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15263. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15264. var isCompressed = texture instanceof THREE.CompressedTexture;
  15265. var cubeImage = [];
  15266. for ( var i = 0; i < 6; i ++ ) {
  15267. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15268. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15269. } else {
  15270. cubeImage[ i ] = texture.image[ i ];
  15271. }
  15272. }
  15273. var image = cubeImage[ 0 ],
  15274. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  15275. glFormat = paramThreeToGL( texture.format ),
  15276. glType = paramThreeToGL( texture.type );
  15277. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15278. for ( var i = 0; i < 6; i ++ ) {
  15279. if( !isCompressed ) {
  15280. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15281. } else {
  15282. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15283. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15284. mipmap = mipmaps[ j ];
  15285. if ( texture.format!==THREE.RGBAFormat ) {
  15286. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15287. } else {
  15288. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15289. }
  15290. }
  15291. }
  15292. }
  15293. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15294. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15295. }
  15296. texture.needsUpdate = false;
  15297. if ( texture.onUpdate ) texture.onUpdate();
  15298. } else {
  15299. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15300. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15301. }
  15302. }
  15303. };
  15304. function setCubeTextureDynamic ( texture, slot ) {
  15305. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15306. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15307. };
  15308. // Render targets
  15309. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15310. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15311. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15312. };
  15313. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15314. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15315. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15316. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15317. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15318. /* For some reason this is not working. Defaulting to RGBA4.
  15319. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15320. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15321. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15322. */
  15323. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15324. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15325. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15326. } else {
  15327. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15328. }
  15329. };
  15330. this.setRenderTarget = function ( renderTarget ) {
  15331. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15332. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15333. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15334. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15335. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15336. renderTarget.__webglTexture = _gl.createTexture();
  15337. _this.info.memory.textures ++;
  15338. // Setup texture, create render and frame buffers
  15339. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  15340. glFormat = paramThreeToGL( renderTarget.format ),
  15341. glType = paramThreeToGL( renderTarget.type );
  15342. if ( isCube ) {
  15343. renderTarget.__webglFramebuffer = [];
  15344. renderTarget.__webglRenderbuffer = [];
  15345. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15346. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15347. for ( var i = 0; i < 6; i ++ ) {
  15348. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15349. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15350. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15351. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15352. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15353. }
  15354. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15355. } else {
  15356. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15357. if ( renderTarget.shareDepthFrom ) {
  15358. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15359. } else {
  15360. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15361. }
  15362. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15363. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15364. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15365. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15366. if ( renderTarget.shareDepthFrom ) {
  15367. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15368. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15369. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15370. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15371. }
  15372. } else {
  15373. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15374. }
  15375. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15376. }
  15377. // Release everything
  15378. if ( isCube ) {
  15379. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15380. } else {
  15381. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15382. }
  15383. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15384. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15385. }
  15386. var framebuffer, width, height, vx, vy;
  15387. if ( renderTarget ) {
  15388. if ( isCube ) {
  15389. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15390. } else {
  15391. framebuffer = renderTarget.__webglFramebuffer;
  15392. }
  15393. width = renderTarget.width;
  15394. height = renderTarget.height;
  15395. vx = 0;
  15396. vy = 0;
  15397. } else {
  15398. framebuffer = null;
  15399. width = _viewportWidth;
  15400. height = _viewportHeight;
  15401. vx = _viewportX;
  15402. vy = _viewportY;
  15403. }
  15404. if ( framebuffer !== _currentFramebuffer ) {
  15405. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15406. _gl.viewport( vx, vy, width, height );
  15407. _currentFramebuffer = framebuffer;
  15408. }
  15409. _currentWidth = width;
  15410. _currentHeight = height;
  15411. };
  15412. function updateRenderTargetMipmap ( renderTarget ) {
  15413. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15414. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15415. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15416. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15417. } else {
  15418. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15419. _gl.generateMipmap( _gl.TEXTURE_2D );
  15420. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15421. }
  15422. };
  15423. // Fallback filters for non-power-of-2 textures
  15424. function filterFallback ( f ) {
  15425. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15426. return _gl.NEAREST;
  15427. }
  15428. return _gl.LINEAR;
  15429. };
  15430. // Map three.js constants to WebGL constants
  15431. function paramThreeToGL ( p ) {
  15432. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15433. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15434. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15435. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15436. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15437. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15438. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15439. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15440. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15441. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15442. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15443. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15444. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15445. if ( p === THREE.ByteType ) return _gl.BYTE;
  15446. if ( p === THREE.ShortType ) return _gl.SHORT;
  15447. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15448. if ( p === THREE.IntType ) return _gl.INT;
  15449. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15450. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15451. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15452. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15453. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15454. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15455. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15456. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15457. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15458. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15459. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15460. if ( p === THREE.OneFactor ) return _gl.ONE;
  15461. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15462. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15463. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15464. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15465. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15466. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15467. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15468. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15469. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15470. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15471. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15472. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15473. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15474. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15475. }
  15476. return 0;
  15477. };
  15478. // Allocations
  15479. function allocateBones ( object ) {
  15480. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15481. return 1024;
  15482. } else {
  15483. // default for when object is not specified
  15484. // ( for example when prebuilding shader
  15485. // to be used with multiple objects )
  15486. //
  15487. // - leave some extra space for other uniforms
  15488. // - limit here is ANGLE's 254 max uniform vectors
  15489. // (up to 54 should be safe)
  15490. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15491. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15492. var maxBones = nVertexMatrices;
  15493. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15494. maxBones = Math.min( object.bones.length, maxBones );
  15495. if ( maxBones < object.bones.length ) {
  15496. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15497. }
  15498. }
  15499. return maxBones;
  15500. }
  15501. };
  15502. function allocateLights( lights ) {
  15503. var dirLights = 0;
  15504. var pointLights = 0;
  15505. var spotLights = 0;
  15506. var hemiLights = 0;
  15507. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15508. var light = lights[ l ];
  15509. if ( light.onlyShadow ) continue;
  15510. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15511. if ( light instanceof THREE.PointLight ) pointLights ++;
  15512. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15513. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15514. }
  15515. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15516. };
  15517. function allocateShadows( lights ) {
  15518. var maxShadows = 0;
  15519. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  15520. var light = lights[ l ];
  15521. if ( ! light.castShadow ) continue;
  15522. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15523. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15524. }
  15525. return maxShadows;
  15526. };
  15527. // Initialization
  15528. function initGL() {
  15529. try {
  15530. var attributes = {
  15531. alpha: _alpha,
  15532. premultipliedAlpha: _premultipliedAlpha,
  15533. antialias: _antialias,
  15534. stencil: _stencil,
  15535. preserveDrawingBuffer: _preserveDrawingBuffer
  15536. };
  15537. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  15538. if ( _gl === null ) {
  15539. throw 'Error creating WebGL context.';
  15540. }
  15541. } catch ( error ) {
  15542. console.error( error );
  15543. }
  15544. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15545. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15546. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15547. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15548. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15549. if ( ! _glExtensionTextureFloat ) {
  15550. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15551. }
  15552. if ( ! _glExtensionStandardDerivatives ) {
  15553. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15554. }
  15555. if ( ! _glExtensionTextureFilterAnisotropic ) {
  15556. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15557. }
  15558. if ( ! _glExtensionCompressedTextureS3TC ) {
  15559. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15560. }
  15561. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15562. _gl.getShaderPrecisionFormat = function() {
  15563. return {
  15564. "rangeMin" : 1,
  15565. "rangeMax" : 1,
  15566. "precision" : 1
  15567. };
  15568. }
  15569. }
  15570. };
  15571. function setDefaultGLState () {
  15572. _gl.clearColor( 0, 0, 0, 1 );
  15573. _gl.clearDepth( 1 );
  15574. _gl.clearStencil( 0 );
  15575. _gl.enable( _gl.DEPTH_TEST );
  15576. _gl.depthFunc( _gl.LEQUAL );
  15577. _gl.frontFace( _gl.CCW );
  15578. _gl.cullFace( _gl.BACK );
  15579. _gl.enable( _gl.CULL_FACE );
  15580. _gl.enable( _gl.BLEND );
  15581. _gl.blendEquation( _gl.FUNC_ADD );
  15582. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15583. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  15584. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15585. };
  15586. // default plugins (order is important)
  15587. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15588. this.addPrePlugin( this.shadowMapPlugin );
  15589. this.addPostPlugin( new THREE.SpritePlugin() );
  15590. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15591. };
  15592. /**
  15593. * @author szimek / https://github.com/szimek/
  15594. * @author alteredq / http://alteredqualia.com/
  15595. */
  15596. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15597. this.width = width;
  15598. this.height = height;
  15599. options = options || {};
  15600. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15601. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15602. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15603. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15604. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15605. this.offset = new THREE.Vector2( 0, 0 );
  15606. this.repeat = new THREE.Vector2( 1, 1 );
  15607. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15608. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15609. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15610. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15611. this.generateMipmaps = true;
  15612. this.shareDepthFrom = null;
  15613. };
  15614. THREE.WebGLRenderTarget.prototype = {
  15615. constructor: THREE.WebGLRenderTarget,
  15616. clone: function () {
  15617. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15618. tmp.wrapS = this.wrapS;
  15619. tmp.wrapT = this.wrapT;
  15620. tmp.magFilter = this.magFilter;
  15621. tmp.minFilter = this.minFilter;
  15622. tmp.anisotropy = this.anisotropy;
  15623. tmp.offset.copy( this.offset );
  15624. tmp.repeat.copy( this.repeat );
  15625. tmp.format = this.format;
  15626. tmp.type = this.type;
  15627. tmp.depthBuffer = this.depthBuffer;
  15628. tmp.stencilBuffer = this.stencilBuffer;
  15629. tmp.generateMipmaps = this.generateMipmaps;
  15630. tmp.shareDepthFrom = this.shareDepthFrom;
  15631. return tmp;
  15632. },
  15633. dispose: function () {
  15634. this.dispatchEvent( { type: 'dispose' } );
  15635. }
  15636. };
  15637. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  15638. /**
  15639. * @author alteredq / http://alteredqualia.com
  15640. */
  15641. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15642. THREE.WebGLRenderTarget.call( this, width, height, options );
  15643. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15644. };
  15645. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15646. /**
  15647. * @author mrdoob / http://mrdoob.com/
  15648. */
  15649. THREE.RenderableVertex = function () {
  15650. this.position = new THREE.Vector3();
  15651. this.positionWorld = new THREE.Vector3();
  15652. this.positionScreen = new THREE.Vector4();
  15653. this.visible = true;
  15654. };
  15655. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15656. this.positionWorld.copy( vertex.positionWorld );
  15657. this.positionScreen.copy( vertex.positionScreen );
  15658. };
  15659. /**
  15660. * @author mrdoob / http://mrdoob.com/
  15661. */
  15662. THREE.RenderableFace3 = function () {
  15663. this.id = 0;
  15664. this.v1 = new THREE.RenderableVertex();
  15665. this.v2 = new THREE.RenderableVertex();
  15666. this.v3 = new THREE.RenderableVertex();
  15667. this.centroidModel = new THREE.Vector3();
  15668. this.normalModel = new THREE.Vector3();
  15669. this.normalModelView = new THREE.Vector3();
  15670. this.vertexNormalsLength = 0;
  15671. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15672. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15673. this.color = null;
  15674. this.material = null;
  15675. this.uvs = [[]];
  15676. this.z = 0;
  15677. };
  15678. /**
  15679. * @author mrdoob / http://mrdoob.com/
  15680. */
  15681. THREE.RenderableObject = function () {
  15682. this.id = 0;
  15683. this.object = null;
  15684. this.z = 0;
  15685. };
  15686. /**
  15687. * @author mrdoob / http://mrdoob.com/
  15688. */
  15689. THREE.RenderableSprite = function () {
  15690. this.id = 0;
  15691. this.object = null;
  15692. this.x = 0;
  15693. this.y = 0;
  15694. this.z = 0;
  15695. this.rotation = 0;
  15696. this.scale = new THREE.Vector2();
  15697. this.material = null;
  15698. };
  15699. /**
  15700. * @author mrdoob / http://mrdoob.com/
  15701. */
  15702. THREE.RenderableLine = function () {
  15703. this.id = 0;
  15704. this.v1 = new THREE.RenderableVertex();
  15705. this.v2 = new THREE.RenderableVertex();
  15706. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  15707. this.material = null;
  15708. this.z = 0;
  15709. };
  15710. /**
  15711. * @author mrdoob / http://mrdoob.com/
  15712. * @author alteredq / http://alteredqualia.com/
  15713. */
  15714. THREE.GeometryUtils = {
  15715. // Merge two geometries or geometry and geometry from object (using object's transform)
  15716. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  15717. var matrix, normalMatrix,
  15718. vertexOffset = geometry1.vertices.length,
  15719. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15720. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15721. vertices1 = geometry1.vertices,
  15722. vertices2 = geometry2.vertices,
  15723. faces1 = geometry1.faces,
  15724. faces2 = geometry2.faces,
  15725. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15726. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15727. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  15728. if ( object2 instanceof THREE.Mesh ) {
  15729. object2.matrixAutoUpdate && object2.updateMatrix();
  15730. matrix = object2.matrix;
  15731. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  15732. }
  15733. // vertices
  15734. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15735. var vertex = vertices2[ i ];
  15736. var vertexCopy = vertex.clone();
  15737. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15738. vertices1.push( vertexCopy );
  15739. }
  15740. // faces
  15741. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15742. var face = faces2[ i ], faceCopy, normal, color,
  15743. faceVertexNormals = face.vertexNormals,
  15744. faceVertexColors = face.vertexColors;
  15745. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15746. faceCopy.normal.copy( face.normal );
  15747. if ( normalMatrix ) {
  15748. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15749. }
  15750. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15751. normal = faceVertexNormals[ j ].clone();
  15752. if ( normalMatrix ) {
  15753. normal.applyMatrix3( normalMatrix ).normalize();
  15754. }
  15755. faceCopy.vertexNormals.push( normal );
  15756. }
  15757. faceCopy.color.copy( face.color );
  15758. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15759. color = faceVertexColors[ j ];
  15760. faceCopy.vertexColors.push( color.clone() );
  15761. }
  15762. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  15763. faceCopy.centroid.copy( face.centroid );
  15764. if ( matrix ) {
  15765. faceCopy.centroid.applyMatrix4( matrix );
  15766. }
  15767. faces1.push( faceCopy );
  15768. }
  15769. // uvs
  15770. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15771. var uv = uvs2[ i ], uvCopy = [];
  15772. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15773. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15774. }
  15775. uvs1.push( uvCopy );
  15776. }
  15777. },
  15778. // Get random point in triangle (via barycentric coordinates)
  15779. // (uniform distribution)
  15780. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15781. randomPointInTriangle: function () {
  15782. var vector = new THREE.Vector3();
  15783. return function ( vectorA, vectorB, vectorC ) {
  15784. var point = new THREE.Vector3();
  15785. var a = THREE.Math.random16();
  15786. var b = THREE.Math.random16();
  15787. if ( ( a + b ) > 1 ) {
  15788. a = 1 - a;
  15789. b = 1 - b;
  15790. }
  15791. var c = 1 - a - b;
  15792. point.copy( vectorA );
  15793. point.multiplyScalar( a );
  15794. vector.copy( vectorB );
  15795. vector.multiplyScalar( b );
  15796. point.add( vector );
  15797. vector.copy( vectorC );
  15798. vector.multiplyScalar( c );
  15799. point.add( vector );
  15800. return point;
  15801. };
  15802. }(),
  15803. // Get random point in face (triangle / quad)
  15804. // (uniform distribution)
  15805. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15806. var vA, vB, vC, vD;
  15807. vA = geometry.vertices[ face.a ];
  15808. vB = geometry.vertices[ face.b ];
  15809. vC = geometry.vertices[ face.c ];
  15810. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15811. },
  15812. // Get uniformly distributed random points in mesh
  15813. // - create array with cumulative sums of face areas
  15814. // - pick random number from 0 to total area
  15815. // - find corresponding place in area array by binary search
  15816. // - get random point in face
  15817. randomPointsInGeometry: function ( geometry, n ) {
  15818. var face, i,
  15819. faces = geometry.faces,
  15820. vertices = geometry.vertices,
  15821. il = faces.length,
  15822. totalArea = 0,
  15823. cumulativeAreas = [],
  15824. vA, vB, vC, vD;
  15825. // precompute face areas
  15826. for ( i = 0; i < il; i ++ ) {
  15827. face = faces[ i ];
  15828. vA = vertices[ face.a ];
  15829. vB = vertices[ face.b ];
  15830. vC = vertices[ face.c ];
  15831. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  15832. totalArea += face._area;
  15833. cumulativeAreas[ i ] = totalArea;
  15834. }
  15835. // binary search cumulative areas array
  15836. function binarySearchIndices( value ) {
  15837. function binarySearch( start, end ) {
  15838. // return closest larger index
  15839. // if exact number is not found
  15840. if ( end < start )
  15841. return start;
  15842. var mid = start + Math.floor( ( end - start ) / 2 );
  15843. if ( cumulativeAreas[ mid ] > value ) {
  15844. return binarySearch( start, mid - 1 );
  15845. } else if ( cumulativeAreas[ mid ] < value ) {
  15846. return binarySearch( mid + 1, end );
  15847. } else {
  15848. return mid;
  15849. }
  15850. }
  15851. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  15852. return result;
  15853. }
  15854. // pick random face weighted by face area
  15855. var r, index,
  15856. result = [];
  15857. var stats = {};
  15858. for ( i = 0; i < n; i ++ ) {
  15859. r = THREE.Math.random16() * totalArea;
  15860. index = binarySearchIndices( r );
  15861. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  15862. if ( ! stats[ index ] ) {
  15863. stats[ index ] = 1;
  15864. } else {
  15865. stats[ index ] += 1;
  15866. }
  15867. }
  15868. return result;
  15869. },
  15870. // Get triangle area (half of parallelogram)
  15871. // http://mathworld.wolfram.com/TriangleArea.html
  15872. triangleArea: function () {
  15873. var vector1 = new THREE.Vector3();
  15874. var vector2 = new THREE.Vector3();
  15875. return function ( vectorA, vectorB, vectorC ) {
  15876. vector1.subVectors( vectorB, vectorA );
  15877. vector2.subVectors( vectorC, vectorA );
  15878. vector1.cross( vector2 );
  15879. return 0.5 * vector1.length();
  15880. };
  15881. }(),
  15882. // Center geometry so that 0,0,0 is in center of bounding box
  15883. center: function ( geometry ) {
  15884. geometry.computeBoundingBox();
  15885. var bb = geometry.boundingBox;
  15886. var offset = new THREE.Vector3();
  15887. offset.addVectors( bb.min, bb.max );
  15888. offset.multiplyScalar( -0.5 );
  15889. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  15890. geometry.computeBoundingBox();
  15891. return offset;
  15892. },
  15893. triangulateQuads: function ( geometry ) {
  15894. var i, il, j, jl;
  15895. var faces = [];
  15896. var faceVertexUvs = [];
  15897. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15898. faceVertexUvs[ i ] = [];
  15899. }
  15900. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15901. var face = geometry.faces[ i ];
  15902. faces.push( face );
  15903. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15904. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15905. }
  15906. }
  15907. geometry.faces = faces;
  15908. geometry.faceVertexUvs = faceVertexUvs;
  15909. geometry.computeCentroids();
  15910. geometry.computeFaceNormals();
  15911. geometry.computeVertexNormals();
  15912. if ( geometry.hasTangents ) geometry.computeTangents();
  15913. }
  15914. };
  15915. /**
  15916. * @author alteredq / http://alteredqualia.com/
  15917. * @author mrdoob / http://mrdoob.com/
  15918. */
  15919. THREE.ImageUtils = {
  15920. crossOrigin: undefined,
  15921. loadTexture: function ( url, mapping, onLoad, onError ) {
  15922. var loader = new THREE.ImageLoader();
  15923. loader.crossOrigin = this.crossOrigin;
  15924. var texture = new THREE.Texture( undefined, mapping );
  15925. var image = loader.load( url, function () {
  15926. texture.needsUpdate = true;
  15927. if ( onLoad ) onLoad( texture );
  15928. } );
  15929. texture.image = image;
  15930. texture.sourceFile = url;
  15931. return texture;
  15932. },
  15933. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15934. var texture = new THREE.CompressedTexture();
  15935. texture.mapping = mapping;
  15936. var request = new XMLHttpRequest();
  15937. request.onload = function () {
  15938. var buffer = request.response;
  15939. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15940. texture.format = dds.format;
  15941. texture.mipmaps = dds.mipmaps;
  15942. texture.image.width = dds.width;
  15943. texture.image.height = dds.height;
  15944. // gl.generateMipmap fails for compressed textures
  15945. // mipmaps must be embedded in the DDS file
  15946. // or texture filters must not use mipmapping
  15947. texture.generateMipmaps = false;
  15948. texture.needsUpdate = true;
  15949. if ( onLoad ) onLoad( texture );
  15950. }
  15951. request.onerror = onError;
  15952. request.open( 'GET', url, true );
  15953. request.responseType = "arraybuffer";
  15954. request.send( null );
  15955. return texture;
  15956. },
  15957. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15958. var images = [];
  15959. images.loadCount = 0;
  15960. var texture = new THREE.Texture();
  15961. texture.image = images;
  15962. if ( mapping !== undefined ) texture.mapping = mapping;
  15963. // no flipping needed for cube textures
  15964. texture.flipY = false;
  15965. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15966. var cubeImage = new Image();
  15967. images[ i ] = cubeImage;
  15968. cubeImage.onload = function () {
  15969. images.loadCount += 1;
  15970. if ( images.loadCount === 6 ) {
  15971. texture.needsUpdate = true;
  15972. if ( onLoad ) onLoad( texture );
  15973. }
  15974. };
  15975. cubeImage.onerror = onError;
  15976. cubeImage.crossOrigin = this.crossOrigin;
  15977. cubeImage.src = array[ i ];
  15978. }
  15979. return texture;
  15980. },
  15981. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15982. var images = [];
  15983. images.loadCount = 0;
  15984. var texture = new THREE.CompressedTexture();
  15985. texture.image = images;
  15986. if ( mapping !== undefined ) texture.mapping = mapping;
  15987. // no flipping for cube textures
  15988. // (also flipping doesn't work for compressed textures )
  15989. texture.flipY = false;
  15990. // can't generate mipmaps for compressed textures
  15991. // mips must be embedded in DDS files
  15992. texture.generateMipmaps = false;
  15993. var generateCubeFaceCallback = function ( rq, img ) {
  15994. return function () {
  15995. var buffer = rq.response;
  15996. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15997. img.format = dds.format;
  15998. img.mipmaps = dds.mipmaps;
  15999. img.width = dds.width;
  16000. img.height = dds.height;
  16001. images.loadCount += 1;
  16002. if ( images.loadCount === 6 ) {
  16003. texture.format = dds.format;
  16004. texture.needsUpdate = true;
  16005. if ( onLoad ) onLoad( texture );
  16006. }
  16007. }
  16008. }
  16009. // compressed cubemap textures as 6 separate DDS files
  16010. if ( array instanceof Array ) {
  16011. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16012. var cubeImage = {};
  16013. images[ i ] = cubeImage;
  16014. var request = new XMLHttpRequest();
  16015. request.onload = generateCubeFaceCallback( request, cubeImage );
  16016. request.onerror = onError;
  16017. var url = array[ i ];
  16018. request.open( 'GET', url, true );
  16019. request.responseType = "arraybuffer";
  16020. request.send( null );
  16021. }
  16022. // compressed cubemap texture stored in a single DDS file
  16023. } else {
  16024. var url = array;
  16025. var request = new XMLHttpRequest();
  16026. request.onload = function( ) {
  16027. var buffer = request.response;
  16028. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16029. if ( dds.isCubemap ) {
  16030. var faces = dds.mipmaps.length / dds.mipmapCount;
  16031. for ( var f = 0; f < faces; f ++ ) {
  16032. images[ f ] = { mipmaps : [] };
  16033. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16034. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16035. images[ f ].format = dds.format;
  16036. images[ f ].width = dds.width;
  16037. images[ f ].height = dds.height;
  16038. }
  16039. }
  16040. texture.format = dds.format;
  16041. texture.needsUpdate = true;
  16042. if ( onLoad ) onLoad( texture );
  16043. }
  16044. }
  16045. request.onerror = onError;
  16046. request.open( 'GET', url, true );
  16047. request.responseType = "arraybuffer";
  16048. request.send( null );
  16049. }
  16050. return texture;
  16051. },
  16052. loadDDSTexture: function ( url, mapping, onLoad, onError ) {
  16053. var images = [];
  16054. images.loadCount = 0;
  16055. var texture = new THREE.CompressedTexture();
  16056. texture.image = images;
  16057. if ( mapping !== undefined ) texture.mapping = mapping;
  16058. // no flipping for cube textures
  16059. // (also flipping doesn't work for compressed textures )
  16060. texture.flipY = false;
  16061. // can't generate mipmaps for compressed textures
  16062. // mips must be embedded in DDS files
  16063. texture.generateMipmaps = false;
  16064. {
  16065. var request = new XMLHttpRequest();
  16066. request.onload = function( ) {
  16067. var buffer = request.response;
  16068. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16069. if ( dds.isCubemap ) {
  16070. var faces = dds.mipmaps.length / dds.mipmapCount;
  16071. for ( var f = 0; f < faces; f ++ ) {
  16072. images[ f ] = { mipmaps : [] };
  16073. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16074. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16075. images[ f ].format = dds.format;
  16076. images[ f ].width = dds.width;
  16077. images[ f ].height = dds.height;
  16078. }
  16079. }
  16080. } else {
  16081. texture.image.width = dds.width;
  16082. texture.image.height = dds.height;
  16083. texture.mipmaps = dds.mipmaps;
  16084. }
  16085. texture.format = dds.format;
  16086. texture.needsUpdate = true;
  16087. if ( onLoad ) onLoad( texture );
  16088. }
  16089. request.onerror = onError;
  16090. request.open( 'GET', url, true );
  16091. request.responseType = "arraybuffer";
  16092. request.send( null );
  16093. }
  16094. return texture;
  16095. },
  16096. parseDDS: function ( buffer, loadMipmaps ) {
  16097. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  16098. // Adapted from @toji's DDS utils
  16099. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  16100. // All values and structures referenced from:
  16101. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  16102. var DDS_MAGIC = 0x20534444;
  16103. var DDSD_CAPS = 0x1,
  16104. DDSD_HEIGHT = 0x2,
  16105. DDSD_WIDTH = 0x4,
  16106. DDSD_PITCH = 0x8,
  16107. DDSD_PIXELFORMAT = 0x1000,
  16108. DDSD_MIPMAPCOUNT = 0x20000,
  16109. DDSD_LINEARSIZE = 0x80000,
  16110. DDSD_DEPTH = 0x800000;
  16111. var DDSCAPS_COMPLEX = 0x8,
  16112. DDSCAPS_MIPMAP = 0x400000,
  16113. DDSCAPS_TEXTURE = 0x1000;
  16114. var DDSCAPS2_CUBEMAP = 0x200,
  16115. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  16116. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  16117. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  16118. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  16119. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  16120. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  16121. DDSCAPS2_VOLUME = 0x200000;
  16122. var DDPF_ALPHAPIXELS = 0x1,
  16123. DDPF_ALPHA = 0x2,
  16124. DDPF_FOURCC = 0x4,
  16125. DDPF_RGB = 0x40,
  16126. DDPF_YUV = 0x200,
  16127. DDPF_LUMINANCE = 0x20000;
  16128. function fourCCToInt32( value ) {
  16129. return value.charCodeAt(0) +
  16130. (value.charCodeAt(1) << 8) +
  16131. (value.charCodeAt(2) << 16) +
  16132. (value.charCodeAt(3) << 24);
  16133. }
  16134. function int32ToFourCC( value ) {
  16135. return String.fromCharCode(
  16136. value & 0xff,
  16137. (value >> 8) & 0xff,
  16138. (value >> 16) & 0xff,
  16139. (value >> 24) & 0xff
  16140. );
  16141. }
  16142. function loadARGBMip( buffer, dataOffset, width, height ) {
  16143. var dataLength = width*height*4;
  16144. var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength );
  16145. var byteArray = new Uint8Array( dataLength );
  16146. var dst = 0;
  16147. var src = 0;
  16148. for ( var y = 0; y < height; y++ ) {
  16149. for ( var x = 0; x < width; x++ ) {
  16150. var b = srcBuffer[src]; src++;
  16151. var g = srcBuffer[src]; src++;
  16152. var r = srcBuffer[src]; src++;
  16153. var a = srcBuffer[src]; src++;
  16154. byteArray[dst] = r; dst++; //r
  16155. byteArray[dst] = g; dst++; //g
  16156. byteArray[dst] = b; dst++; //b
  16157. byteArray[dst] = a; dst++; //a
  16158. }
  16159. }
  16160. return byteArray;
  16161. }
  16162. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  16163. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  16164. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  16165. var headerLengthInt = 31; // The header length in 32 bit ints
  16166. // Offsets into the header array
  16167. var off_magic = 0;
  16168. var off_size = 1;
  16169. var off_flags = 2;
  16170. var off_height = 3;
  16171. var off_width = 4;
  16172. var off_mipmapCount = 7;
  16173. var off_pfFlags = 20;
  16174. var off_pfFourCC = 21;
  16175. var off_RGBBitCount = 22;
  16176. var off_RBitMask = 23;
  16177. var off_GBitMask = 24;
  16178. var off_BBitMask = 25;
  16179. var off_ABitMask = 26;
  16180. var off_caps = 27;
  16181. var off_caps2 = 28;
  16182. var off_caps3 = 29;
  16183. var off_caps4 = 30;
  16184. // Parse header
  16185. var header = new Int32Array( buffer, 0, headerLengthInt );
  16186. if ( header[ off_magic ] !== DDS_MAGIC ) {
  16187. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  16188. return dds;
  16189. }
  16190. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  16191. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  16192. return dds;
  16193. }
  16194. var blockBytes;
  16195. var fourCC = header[ off_pfFourCC ];
  16196. var isRGBAUncompressed = false;
  16197. switch ( fourCC ) {
  16198. case FOURCC_DXT1:
  16199. blockBytes = 8;
  16200. dds.format = THREE.RGB_S3TC_DXT1_Format;
  16201. break;
  16202. case FOURCC_DXT3:
  16203. blockBytes = 16;
  16204. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  16205. break;
  16206. case FOURCC_DXT5:
  16207. blockBytes = 16;
  16208. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  16209. break;
  16210. default:
  16211. if( header[off_RGBBitCount] ==32
  16212. && header[off_RBitMask]&0xff0000
  16213. && header[off_GBitMask]&0xff00
  16214. && header[off_BBitMask]&0xff
  16215. && header[off_ABitMask]&0xff000000 ) {
  16216. isRGBAUncompressed = true;
  16217. blockBytes = 64;
  16218. dds.format = THREE.RGBAFormat;
  16219. } else {
  16220. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  16221. return dds;
  16222. }
  16223. }
  16224. dds.mipmapCount = 1;
  16225. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  16226. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  16227. }
  16228. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  16229. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  16230. dds.width = header[ off_width ];
  16231. dds.height = header[ off_height ];
  16232. var dataOffset = header[ off_size ] + 4;
  16233. // Extract mipmaps buffers
  16234. var width = dds.width;
  16235. var height = dds.height;
  16236. var faces = dds.isCubemap ? 6 : 1;
  16237. for ( var face = 0; face < faces; face ++ ) {
  16238. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16239. if( isRGBAUncompressed ) {
  16240. var byteArray = loadARGBMip( buffer, dataOffset, width, height );
  16241. var dataLength = byteArray.length;
  16242. } else {
  16243. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16244. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16245. }
  16246. var mipmap = { "data": byteArray, "width": width, "height": height };
  16247. dds.mipmaps.push( mipmap );
  16248. dataOffset += dataLength;
  16249. width = Math.max( width * 0.5, 1 );
  16250. height = Math.max( height * 0.5, 1 );
  16251. }
  16252. width = dds.width;
  16253. height = dds.height;
  16254. }
  16255. return dds;
  16256. },
  16257. getNormalMap: function ( image, depth ) {
  16258. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16259. var cross = function ( a, b ) {
  16260. 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 ] ];
  16261. }
  16262. var subtract = function ( a, b ) {
  16263. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16264. }
  16265. var normalize = function ( a ) {
  16266. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16267. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16268. }
  16269. depth = depth | 1;
  16270. var width = image.width;
  16271. var height = image.height;
  16272. var canvas = document.createElement( 'canvas' );
  16273. canvas.width = width;
  16274. canvas.height = height;
  16275. var context = canvas.getContext( '2d' );
  16276. context.drawImage( image, 0, 0 );
  16277. var data = context.getImageData( 0, 0, width, height ).data;
  16278. var imageData = context.createImageData( width, height );
  16279. var output = imageData.data;
  16280. for ( var x = 0; x < width; x ++ ) {
  16281. for ( var y = 0; y < height; y ++ ) {
  16282. var ly = y - 1 < 0 ? 0 : y - 1;
  16283. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16284. var lx = x - 1 < 0 ? 0 : x - 1;
  16285. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16286. var points = [];
  16287. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16288. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16289. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16290. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16291. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16292. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16293. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16294. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16295. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16296. var normals = [];
  16297. var num_points = points.length;
  16298. for ( var i = 0; i < num_points; i ++ ) {
  16299. var v1 = points[ i ];
  16300. var v2 = points[ ( i + 1 ) % num_points ];
  16301. v1 = subtract( v1, origin );
  16302. v2 = subtract( v2, origin );
  16303. normals.push( normalize( cross( v1, v2 ) ) );
  16304. }
  16305. var normal = [ 0, 0, 0 ];
  16306. for ( var i = 0; i < normals.length; i ++ ) {
  16307. normal[ 0 ] += normals[ i ][ 0 ];
  16308. normal[ 1 ] += normals[ i ][ 1 ];
  16309. normal[ 2 ] += normals[ i ][ 2 ];
  16310. }
  16311. normal[ 0 ] /= normals.length;
  16312. normal[ 1 ] /= normals.length;
  16313. normal[ 2 ] /= normals.length;
  16314. var idx = ( y * width + x ) * 4;
  16315. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16316. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16317. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16318. output[ idx + 3 ] = 255;
  16319. }
  16320. }
  16321. context.putImageData( imageData, 0, 0 );
  16322. return canvas;
  16323. },
  16324. generateDataTexture: function ( width, height, color ) {
  16325. var size = width * height;
  16326. var data = new Uint8Array( 3 * size );
  16327. var r = Math.floor( color.r * 255 );
  16328. var g = Math.floor( color.g * 255 );
  16329. var b = Math.floor( color.b * 255 );
  16330. for ( var i = 0; i < size; i ++ ) {
  16331. data[ i * 3 ] = r;
  16332. data[ i * 3 + 1 ] = g;
  16333. data[ i * 3 + 2 ] = b;
  16334. }
  16335. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16336. texture.needsUpdate = true;
  16337. return texture;
  16338. }
  16339. };
  16340. /**
  16341. * @author alteredq / http://alteredqualia.com/
  16342. */
  16343. THREE.SceneUtils = {
  16344. createMultiMaterialObject: function ( geometry, materials ) {
  16345. var group = new THREE.Object3D();
  16346. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16347. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16348. }
  16349. return group;
  16350. },
  16351. detach : function ( child, parent, scene ) {
  16352. child.applyMatrix( parent.matrixWorld );
  16353. parent.remove( child );
  16354. scene.add( child );
  16355. },
  16356. attach: function ( child, scene, parent ) {
  16357. var matrixWorldInverse = new THREE.Matrix4();
  16358. matrixWorldInverse.getInverse( parent.matrixWorld );
  16359. child.applyMatrix( matrixWorldInverse );
  16360. scene.remove( child );
  16361. parent.add( child );
  16362. }
  16363. };
  16364. /**
  16365. * @author zz85 / http://www.lab4games.net/zz85/blog
  16366. * @author alteredq / http://alteredqualia.com/
  16367. *
  16368. * For Text operations in three.js (See TextGeometry)
  16369. *
  16370. * It uses techniques used in:
  16371. *
  16372. * typeface.js and canvastext
  16373. * For converting fonts and rendering with javascript
  16374. * http://typeface.neocracy.org
  16375. *
  16376. * Triangulation ported from AS3
  16377. * Simple Polygon Triangulation
  16378. * http://actionsnippet.com/?p=1462
  16379. *
  16380. * A Method to triangulate shapes with holes
  16381. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16382. *
  16383. */
  16384. THREE.FontUtils = {
  16385. faces : {},
  16386. // Just for now. face[weight][style]
  16387. face : "helvetiker",
  16388. weight: "normal",
  16389. style : "normal",
  16390. size : 150,
  16391. divisions : 10,
  16392. getFace : function() {
  16393. return this.faces[ this.face ][ this.weight ][ this.style ];
  16394. },
  16395. loadFace : function( data ) {
  16396. var family = data.familyName.toLowerCase();
  16397. var ThreeFont = this;
  16398. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16399. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16400. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16401. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16402. return data;
  16403. },
  16404. drawText : function( text ) {
  16405. var characterPts = [], allPts = [];
  16406. // RenderText
  16407. var i, p,
  16408. face = this.getFace(),
  16409. scale = this.size / face.resolution,
  16410. offset = 0,
  16411. chars = String( text ).split( '' ),
  16412. length = chars.length;
  16413. var fontPaths = [];
  16414. for ( i = 0; i < length; i ++ ) {
  16415. var path = new THREE.Path();
  16416. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16417. offset += ret.offset;
  16418. fontPaths.push( ret.path );
  16419. }
  16420. // get the width
  16421. var width = offset / 2;
  16422. //
  16423. // for ( p = 0; p < allPts.length; p++ ) {
  16424. //
  16425. // allPts[ p ].x -= width;
  16426. //
  16427. // }
  16428. //var extract = this.extractPoints( allPts, characterPts );
  16429. //extract.contour = allPts;
  16430. //extract.paths = fontPaths;
  16431. //extract.offset = width;
  16432. return { paths : fontPaths, offset : width };
  16433. },
  16434. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16435. var pts = [];
  16436. var i, i2, divisions,
  16437. outline, action, length,
  16438. scaleX, scaleY,
  16439. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16440. laste,
  16441. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16442. if ( !glyph ) return;
  16443. if ( glyph.o ) {
  16444. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16445. length = outline.length;
  16446. scaleX = scale;
  16447. scaleY = scale;
  16448. for ( i = 0; i < length; ) {
  16449. action = outline[ i ++ ];
  16450. //console.log( action );
  16451. switch( action ) {
  16452. case 'm':
  16453. // Move To
  16454. x = outline[ i++ ] * scaleX + offset;
  16455. y = outline[ i++ ] * scaleY;
  16456. path.moveTo( x, y );
  16457. break;
  16458. case 'l':
  16459. // Line To
  16460. x = outline[ i++ ] * scaleX + offset;
  16461. y = outline[ i++ ] * scaleY;
  16462. path.lineTo(x,y);
  16463. break;
  16464. case 'q':
  16465. // QuadraticCurveTo
  16466. cpx = outline[ i++ ] * scaleX + offset;
  16467. cpy = outline[ i++ ] * scaleY;
  16468. cpx1 = outline[ i++ ] * scaleX + offset;
  16469. cpy1 = outline[ i++ ] * scaleY;
  16470. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16471. laste = pts[ pts.length - 1 ];
  16472. if ( laste ) {
  16473. cpx0 = laste.x;
  16474. cpy0 = laste.y;
  16475. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16476. var t = i2 / divisions;
  16477. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16478. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16479. }
  16480. }
  16481. break;
  16482. case 'b':
  16483. // Cubic Bezier Curve
  16484. cpx = outline[ i++ ] * scaleX + offset;
  16485. cpy = outline[ i++ ] * scaleY;
  16486. cpx1 = outline[ i++ ] * scaleX + offset;
  16487. cpy1 = outline[ i++ ] * -scaleY;
  16488. cpx2 = outline[ i++ ] * scaleX + offset;
  16489. cpy2 = outline[ i++ ] * -scaleY;
  16490. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16491. laste = pts[ pts.length - 1 ];
  16492. if ( laste ) {
  16493. cpx0 = laste.x;
  16494. cpy0 = laste.y;
  16495. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16496. var t = i2 / divisions;
  16497. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16498. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16499. }
  16500. }
  16501. break;
  16502. }
  16503. }
  16504. }
  16505. return { offset: glyph.ha*scale, path:path};
  16506. }
  16507. };
  16508. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16509. // Parameters
  16510. parameters = parameters || {};
  16511. var size = parameters.size !== undefined ? parameters.size : 100;
  16512. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16513. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16514. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16515. var style = parameters.style !== undefined ? parameters.style : "normal";
  16516. THREE.FontUtils.size = size;
  16517. THREE.FontUtils.divisions = curveSegments;
  16518. THREE.FontUtils.face = font;
  16519. THREE.FontUtils.weight = weight;
  16520. THREE.FontUtils.style = style;
  16521. // Get a Font data json object
  16522. var data = THREE.FontUtils.drawText( text );
  16523. var paths = data.paths;
  16524. var shapes = [];
  16525. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16526. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16527. }
  16528. return shapes;
  16529. };
  16530. /**
  16531. * This code is a quick port of code written in C++ which was submitted to
  16532. * flipcode.com by John W. Ratcliff // July 22, 2000
  16533. * See original code and more information here:
  16534. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16535. *
  16536. * ported to actionscript by Zevan Rosser
  16537. * www.actionsnippet.com
  16538. *
  16539. * ported to javascript by Joshua Koo
  16540. * http://www.lab4games.net/zz85/blog
  16541. *
  16542. */
  16543. ( function( namespace ) {
  16544. var EPSILON = 0.0000000001;
  16545. // takes in an contour array and returns
  16546. var process = function( contour, indices ) {
  16547. var n = contour.length;
  16548. if ( n < 3 ) return null;
  16549. var result = [],
  16550. verts = [],
  16551. vertIndices = [];
  16552. /* we want a counter-clockwise polygon in verts */
  16553. var u, v, w;
  16554. if ( area( contour ) > 0.0 ) {
  16555. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16556. } else {
  16557. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16558. }
  16559. var nv = n;
  16560. /* remove nv - 2 vertices, creating 1 triangle every time */
  16561. var count = 2 * nv; /* error detection */
  16562. for( v = nv - 1; nv > 2; ) {
  16563. /* if we loop, it is probably a non-simple polygon */
  16564. if ( ( count-- ) <= 0 ) {
  16565. //** Triangulate: ERROR - probable bad polygon!
  16566. //throw ( "Warning, unable to triangulate polygon!" );
  16567. //return null;
  16568. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16569. console.log( "Warning, unable to triangulate polygon!" );
  16570. if ( indices ) return vertIndices;
  16571. return result;
  16572. }
  16573. /* three consecutive vertices in current polygon, <u,v,w> */
  16574. u = v; if ( nv <= u ) u = 0; /* previous */
  16575. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16576. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16577. if ( snip( contour, u, v, w, nv, verts ) ) {
  16578. var a, b, c, s, t;
  16579. /* true names of the vertices */
  16580. a = verts[ u ];
  16581. b = verts[ v ];
  16582. c = verts[ w ];
  16583. /* output Triangle */
  16584. result.push( [ contour[ a ],
  16585. contour[ b ],
  16586. contour[ c ] ] );
  16587. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16588. /* remove v from the remaining polygon */
  16589. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16590. verts[ s ] = verts[ t ];
  16591. }
  16592. nv--;
  16593. /* reset error detection counter */
  16594. count = 2 * nv;
  16595. }
  16596. }
  16597. if ( indices ) return vertIndices;
  16598. return result;
  16599. };
  16600. // calculate area of the contour polygon
  16601. var area = function ( contour ) {
  16602. var n = contour.length;
  16603. var a = 0.0;
  16604. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16605. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16606. }
  16607. return a * 0.5;
  16608. };
  16609. var snip = function ( contour, u, v, w, n, verts ) {
  16610. var p;
  16611. var ax, ay, bx, by;
  16612. var cx, cy, px, py;
  16613. ax = contour[ verts[ u ] ].x;
  16614. ay = contour[ verts[ u ] ].y;
  16615. bx = contour[ verts[ v ] ].x;
  16616. by = contour[ verts[ v ] ].y;
  16617. cx = contour[ verts[ w ] ].x;
  16618. cy = contour[ verts[ w ] ].y;
  16619. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16620. var aX, aY, bX, bY, cX, cY;
  16621. var apx, apy, bpx, bpy, cpx, cpy;
  16622. var cCROSSap, bCROSScp, aCROSSbp;
  16623. aX = cx - bx; aY = cy - by;
  16624. bX = ax - cx; bY = ay - cy;
  16625. cX = bx - ax; cY = by - ay;
  16626. for ( p = 0; p < n; p++ ) {
  16627. px = contour[ verts[ p ] ].x
  16628. py = contour[ verts[ p ] ].y
  16629. if ( ( (px === ax) && (py === ay) ) ||
  16630. ( (px === bx) && (py === by) ) ||
  16631. ( (px === cx) && (py === cy) ) ) continue;
  16632. apx = px - ax; apy = py - ay;
  16633. bpx = px - bx; bpy = py - by;
  16634. cpx = px - cx; cpy = py - cy;
  16635. // see if p is inside triangle abc
  16636. aCROSSbp = aX*bpy - aY*bpx;
  16637. cCROSSap = cX*apy - cY*apx;
  16638. bCROSScp = bX*cpy - bY*cpx;
  16639. if ( (aCROSSbp >= -EPSILON) && (bCROSScp >= -EPSILON) && (cCROSSap >= -EPSILON) ) return false;
  16640. }
  16641. return true;
  16642. };
  16643. namespace.Triangulate = process;
  16644. namespace.Triangulate.area = area;
  16645. return namespace;
  16646. })(THREE.FontUtils);
  16647. // To use the typeface.js face files, hook up the API
  16648. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16649. THREE.typeface_js = self._typeface_js;
  16650. /**
  16651. * @author zz85 / http://www.lab4games.net/zz85/blog
  16652. * Extensible curve object
  16653. *
  16654. * Some common of Curve methods
  16655. * .getPoint(t), getTangent(t)
  16656. * .getPointAt(u), getTagentAt(u)
  16657. * .getPoints(), .getSpacedPoints()
  16658. * .getLength()
  16659. * .updateArcLengths()
  16660. *
  16661. * This following classes subclasses THREE.Curve:
  16662. *
  16663. * -- 2d classes --
  16664. * THREE.LineCurve
  16665. * THREE.QuadraticBezierCurve
  16666. * THREE.CubicBezierCurve
  16667. * THREE.SplineCurve
  16668. * THREE.ArcCurve
  16669. * THREE.EllipseCurve
  16670. *
  16671. * -- 3d classes --
  16672. * THREE.LineCurve3
  16673. * THREE.QuadraticBezierCurve3
  16674. * THREE.CubicBezierCurve3
  16675. * THREE.SplineCurve3
  16676. * THREE.ClosedSplineCurve3
  16677. *
  16678. * A series of curves can be represented as a THREE.CurvePath
  16679. *
  16680. **/
  16681. /**************************************************************
  16682. * Abstract Curve base class
  16683. **************************************************************/
  16684. THREE.Curve = function () {
  16685. };
  16686. // Virtual base class method to overwrite and implement in subclasses
  16687. // - t [0 .. 1]
  16688. THREE.Curve.prototype.getPoint = function ( t ) {
  16689. console.log( "Warning, getPoint() not implemented!" );
  16690. return null;
  16691. };
  16692. // Get point at relative position in curve according to arc length
  16693. // - u [0 .. 1]
  16694. THREE.Curve.prototype.getPointAt = function ( u ) {
  16695. var t = this.getUtoTmapping( u );
  16696. return this.getPoint( t );
  16697. };
  16698. // Get sequence of points using getPoint( t )
  16699. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16700. if ( !divisions ) divisions = 5;
  16701. var d, pts = [];
  16702. for ( d = 0; d <= divisions; d ++ ) {
  16703. pts.push( this.getPoint( d / divisions ) );
  16704. }
  16705. return pts;
  16706. };
  16707. // Get sequence of points using getPointAt( u )
  16708. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16709. if ( !divisions ) divisions = 5;
  16710. var d, pts = [];
  16711. for ( d = 0; d <= divisions; d ++ ) {
  16712. pts.push( this.getPointAt( d / divisions ) );
  16713. }
  16714. return pts;
  16715. };
  16716. // Get total curve arc length
  16717. THREE.Curve.prototype.getLength = function () {
  16718. var lengths = this.getLengths();
  16719. return lengths[ lengths.length - 1 ];
  16720. };
  16721. // Get list of cumulative segment lengths
  16722. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16723. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16724. if ( this.cacheArcLengths
  16725. && ( this.cacheArcLengths.length == divisions + 1 )
  16726. && !this.needsUpdate) {
  16727. //console.log( "cached", this.cacheArcLengths );
  16728. return this.cacheArcLengths;
  16729. }
  16730. this.needsUpdate = false;
  16731. var cache = [];
  16732. var current, last = this.getPoint( 0 );
  16733. var p, sum = 0;
  16734. cache.push( 0 );
  16735. for ( p = 1; p <= divisions; p ++ ) {
  16736. current = this.getPoint ( p / divisions );
  16737. sum += current.distanceTo( last );
  16738. cache.push( sum );
  16739. last = current;
  16740. }
  16741. this.cacheArcLengths = cache;
  16742. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16743. };
  16744. THREE.Curve.prototype.updateArcLengths = function() {
  16745. this.needsUpdate = true;
  16746. this.getLengths();
  16747. };
  16748. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16749. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16750. var arcLengths = this.getLengths();
  16751. var i = 0, il = arcLengths.length;
  16752. var targetArcLength; // The targeted u distance value to get
  16753. if ( distance ) {
  16754. targetArcLength = distance;
  16755. } else {
  16756. targetArcLength = u * arcLengths[ il - 1 ];
  16757. }
  16758. //var time = Date.now();
  16759. // binary search for the index with largest value smaller than target u distance
  16760. var low = 0, high = il - 1, comparison;
  16761. while ( low <= high ) {
  16762. 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
  16763. comparison = arcLengths[ i ] - targetArcLength;
  16764. if ( comparison < 0 ) {
  16765. low = i + 1;
  16766. continue;
  16767. } else if ( comparison > 0 ) {
  16768. high = i - 1;
  16769. continue;
  16770. } else {
  16771. high = i;
  16772. break;
  16773. // DONE
  16774. }
  16775. }
  16776. i = high;
  16777. //console.log('b' , i, low, high, Date.now()- time);
  16778. if ( arcLengths[ i ] == targetArcLength ) {
  16779. var t = i / ( il - 1 );
  16780. return t;
  16781. }
  16782. // we could get finer grain at lengths, or use simple interpolatation between two points
  16783. var lengthBefore = arcLengths[ i ];
  16784. var lengthAfter = arcLengths[ i + 1 ];
  16785. var segmentLength = lengthAfter - lengthBefore;
  16786. // determine where we are between the 'before' and 'after' points
  16787. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16788. // add that fractional amount to t
  16789. var t = ( i + segmentFraction ) / ( il -1 );
  16790. return t;
  16791. };
  16792. // Returns a unit vector tangent at t
  16793. // In case any sub curve does not implement its tangent derivation,
  16794. // 2 points a small delta apart will be used to find its gradient
  16795. // which seems to give a reasonable approximation
  16796. THREE.Curve.prototype.getTangent = function( t ) {
  16797. var delta = 0.0001;
  16798. var t1 = t - delta;
  16799. var t2 = t + delta;
  16800. // Capping in case of danger
  16801. if ( t1 < 0 ) t1 = 0;
  16802. if ( t2 > 1 ) t2 = 1;
  16803. var pt1 = this.getPoint( t1 );
  16804. var pt2 = this.getPoint( t2 );
  16805. var vec = pt2.clone().sub(pt1);
  16806. return vec.normalize();
  16807. };
  16808. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16809. var t = this.getUtoTmapping( u );
  16810. return this.getTangent( t );
  16811. };
  16812. /**************************************************************
  16813. * Utils
  16814. **************************************************************/
  16815. THREE.Curve.Utils = {
  16816. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16817. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16818. },
  16819. // Puay Bing, thanks for helping with this derivative!
  16820. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16821. return -3 * p0 * (1 - t) * (1 - t) +
  16822. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16823. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16824. 3 * t * t * p3;
  16825. },
  16826. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16827. // To check if my formulas are correct
  16828. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16829. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16830. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16831. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16832. return h00 + h10 + h01 + h11;
  16833. },
  16834. // Catmull-Rom
  16835. interpolate: function( p0, p1, p2, p3, t ) {
  16836. var v0 = ( p2 - p0 ) * 0.5;
  16837. var v1 = ( p3 - p1 ) * 0.5;
  16838. var t2 = t * t;
  16839. var t3 = t * t2;
  16840. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16841. }
  16842. };
  16843. // TODO: Transformation for Curves?
  16844. /**************************************************************
  16845. * 3D Curves
  16846. **************************************************************/
  16847. // A Factory method for creating new curve subclasses
  16848. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16849. constructor.prototype = Object.create( THREE.Curve.prototype );
  16850. constructor.prototype.getPoint = getPointFunc;
  16851. return constructor;
  16852. };
  16853. /**
  16854. * @author zz85 / http://www.lab4games.net/zz85/blog
  16855. *
  16856. **/
  16857. /**************************************************************
  16858. * Curved Path - a curve path is simply a array of connected
  16859. * curves, but retains the api of a curve
  16860. **************************************************************/
  16861. THREE.CurvePath = function () {
  16862. this.curves = [];
  16863. this.bends = [];
  16864. this.autoClose = false; // Automatically closes the path
  16865. };
  16866. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16867. THREE.CurvePath.prototype.add = function ( curve ) {
  16868. this.curves.push( curve );
  16869. };
  16870. THREE.CurvePath.prototype.checkConnection = function() {
  16871. // TODO
  16872. // If the ending of curve is not connected to the starting
  16873. // or the next curve, then, this is not a real path
  16874. };
  16875. THREE.CurvePath.prototype.closePath = function() {
  16876. // TODO Test
  16877. // and verify for vector3 (needs to implement equals)
  16878. // Add a line curve if start and end of lines are not connected
  16879. var startPoint = this.curves[0].getPoint(0);
  16880. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16881. if (!startPoint.equals(endPoint)) {
  16882. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16883. }
  16884. };
  16885. // To get accurate point with reference to
  16886. // entire path distance at time t,
  16887. // following has to be done:
  16888. // 1. Length of each sub path have to be known
  16889. // 2. Locate and identify type of curve
  16890. // 3. Get t for the curve
  16891. // 4. Return curve.getPointAt(t')
  16892. THREE.CurvePath.prototype.getPoint = function( t ) {
  16893. var d = t * this.getLength();
  16894. var curveLengths = this.getCurveLengths();
  16895. var i = 0, diff, curve;
  16896. // To think about boundaries points.
  16897. while ( i < curveLengths.length ) {
  16898. if ( curveLengths[ i ] >= d ) {
  16899. diff = curveLengths[ i ] - d;
  16900. curve = this.curves[ i ];
  16901. var u = 1 - diff / curve.getLength();
  16902. return curve.getPointAt( u );
  16903. break;
  16904. }
  16905. i ++;
  16906. }
  16907. return null;
  16908. // loop where sum != 0, sum > d , sum+1 <d
  16909. };
  16910. /*
  16911. THREE.CurvePath.prototype.getTangent = function( t ) {
  16912. };*/
  16913. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16914. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16915. // getPoint() depends on getLength
  16916. THREE.CurvePath.prototype.getLength = function() {
  16917. var lens = this.getCurveLengths();
  16918. return lens[ lens.length - 1 ];
  16919. };
  16920. // Compute lengths and cache them
  16921. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16922. THREE.CurvePath.prototype.getCurveLengths = function() {
  16923. // We use cache values if curves and cache array are same length
  16924. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16925. return this.cacheLengths;
  16926. };
  16927. // Get length of subsurve
  16928. // Push sums into cached array
  16929. var lengths = [], sums = 0;
  16930. var i, il = this.curves.length;
  16931. for ( i = 0; i < il; i ++ ) {
  16932. sums += this.curves[ i ].getLength();
  16933. lengths.push( sums );
  16934. }
  16935. this.cacheLengths = lengths;
  16936. return lengths;
  16937. };
  16938. // Returns min and max coordinates, as well as centroid
  16939. THREE.CurvePath.prototype.getBoundingBox = function () {
  16940. var points = this.getPoints();
  16941. var maxX, maxY, maxZ;
  16942. var minX, minY, minZ;
  16943. maxX = maxY = Number.NEGATIVE_INFINITY;
  16944. minX = minY = Number.POSITIVE_INFINITY;
  16945. var p, i, il, sum;
  16946. var v3 = points[0] instanceof THREE.Vector3;
  16947. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16948. for ( i = 0, il = points.length; i < il; i ++ ) {
  16949. p = points[ i ];
  16950. if ( p.x > maxX ) maxX = p.x;
  16951. else if ( p.x < minX ) minX = p.x;
  16952. if ( p.y > maxY ) maxY = p.y;
  16953. else if ( p.y < minY ) minY = p.y;
  16954. if ( v3 ) {
  16955. if ( p.z > maxZ ) maxZ = p.z;
  16956. else if ( p.z < minZ ) minZ = p.z;
  16957. }
  16958. sum.add( p );
  16959. }
  16960. var ret = {
  16961. minX: minX,
  16962. minY: minY,
  16963. maxX: maxX,
  16964. maxY: maxY,
  16965. centroid: sum.divideScalar( il )
  16966. };
  16967. if ( v3 ) {
  16968. ret.maxZ = maxZ;
  16969. ret.minZ = minZ;
  16970. }
  16971. return ret;
  16972. };
  16973. /**************************************************************
  16974. * Create Geometries Helpers
  16975. **************************************************************/
  16976. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16977. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16978. var pts = this.getPoints( divisions, true );
  16979. return this.createGeometry( pts );
  16980. };
  16981. // Generate geometry from equidistance sampling along the path
  16982. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16983. var pts = this.getSpacedPoints( divisions, true );
  16984. return this.createGeometry( pts );
  16985. };
  16986. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16987. var geometry = new THREE.Geometry();
  16988. for ( var i = 0; i < points.length; i ++ ) {
  16989. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16990. }
  16991. return geometry;
  16992. };
  16993. /**************************************************************
  16994. * Bend / Wrap Helper Methods
  16995. **************************************************************/
  16996. // Wrap path / Bend modifiers?
  16997. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16998. this.bends.push( bendpath );
  16999. };
  17000. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  17001. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  17002. var i, il;
  17003. if ( !bends ) {
  17004. bends = this.bends;
  17005. }
  17006. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17007. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17008. }
  17009. return oldPts;
  17010. };
  17011. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  17012. var oldPts = this.getSpacedPoints( segments );
  17013. var i, il;
  17014. if ( !bends ) {
  17015. bends = this.bends;
  17016. }
  17017. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17018. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17019. }
  17020. return oldPts;
  17021. };
  17022. // This returns getPoints() bend/wrapped around the contour of a path.
  17023. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  17024. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  17025. var bounds = this.getBoundingBox();
  17026. var i, il, p, oldX, oldY, xNorm;
  17027. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  17028. p = oldPts[ i ];
  17029. oldX = p.x;
  17030. oldY = p.y;
  17031. xNorm = oldX / bounds.maxX;
  17032. // If using actual distance, for length > path, requires line extrusions
  17033. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  17034. xNorm = path.getUtoTmapping( xNorm, oldX );
  17035. // check for out of bounds?
  17036. var pathPt = path.getPoint( xNorm );
  17037. var normal = path.getTangent( xNorm );
  17038. normal.set( -normal.y, normal.x ).multiplyScalar( oldY );
  17039. p.x = pathPt.x + normal.x;
  17040. p.y = pathPt.y + normal.y;
  17041. }
  17042. return oldPts;
  17043. };
  17044. /**
  17045. * @author alteredq / http://alteredqualia.com/
  17046. */
  17047. THREE.Gyroscope = function () {
  17048. THREE.Object3D.call( this );
  17049. };
  17050. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  17051. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  17052. this.matrixAutoUpdate && this.updateMatrix();
  17053. // update matrixWorld
  17054. if ( this.matrixWorldNeedsUpdate || force ) {
  17055. if ( this.parent ) {
  17056. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  17057. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  17058. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  17059. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  17060. } else {
  17061. this.matrixWorld.copy( this.matrix );
  17062. }
  17063. this.matrixWorldNeedsUpdate = false;
  17064. force = true;
  17065. }
  17066. // update children
  17067. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  17068. this.children[ i ].updateMatrixWorld( force );
  17069. }
  17070. };
  17071. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  17072. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  17073. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  17074. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  17075. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  17076. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  17077. /**
  17078. * @author zz85 / http://www.lab4games.net/zz85/blog
  17079. * Creates free form 2d path using series of points, lines or curves.
  17080. *
  17081. **/
  17082. THREE.Path = function ( points ) {
  17083. THREE.CurvePath.call(this);
  17084. this.actions = [];
  17085. if ( points ) {
  17086. this.fromPoints( points );
  17087. }
  17088. };
  17089. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  17090. THREE.PathActions = {
  17091. MOVE_TO: 'moveTo',
  17092. LINE_TO: 'lineTo',
  17093. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  17094. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  17095. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  17096. ARC: 'arc', // Circle
  17097. ELLIPSE: 'ellipse'
  17098. };
  17099. // TODO Clean up PATH API
  17100. // Create path using straight lines to connect all points
  17101. // - vectors: array of Vector2
  17102. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17103. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17104. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17105. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17106. };
  17107. };
  17108. // startPath() endPath()?
  17109. THREE.Path.prototype.moveTo = function ( x, y ) {
  17110. var args = Array.prototype.slice.call( arguments );
  17111. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17112. };
  17113. THREE.Path.prototype.lineTo = function ( x, y ) {
  17114. var args = Array.prototype.slice.call( arguments );
  17115. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17116. var x0 = lastargs[ lastargs.length - 2 ];
  17117. var y0 = lastargs[ lastargs.length - 1 ];
  17118. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17119. this.curves.push( curve );
  17120. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17121. };
  17122. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17123. var args = Array.prototype.slice.call( arguments );
  17124. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17125. var x0 = lastargs[ lastargs.length - 2 ];
  17126. var y0 = lastargs[ lastargs.length - 1 ];
  17127. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17128. new THREE.Vector2( aCPx, aCPy ),
  17129. new THREE.Vector2( aX, aY ) );
  17130. this.curves.push( curve );
  17131. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17132. };
  17133. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17134. aCP2x, aCP2y,
  17135. aX, aY ) {
  17136. var args = Array.prototype.slice.call( arguments );
  17137. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17138. var x0 = lastargs[ lastargs.length - 2 ];
  17139. var y0 = lastargs[ lastargs.length - 1 ];
  17140. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17141. new THREE.Vector2( aCP1x, aCP1y ),
  17142. new THREE.Vector2( aCP2x, aCP2y ),
  17143. new THREE.Vector2( aX, aY ) );
  17144. this.curves.push( curve );
  17145. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17146. };
  17147. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17148. var args = Array.prototype.slice.call( arguments );
  17149. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17150. var x0 = lastargs[ lastargs.length - 2 ];
  17151. var y0 = lastargs[ lastargs.length - 1 ];
  17152. //---
  17153. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17154. Array.prototype.push.apply( npts, pts );
  17155. var curve = new THREE.SplineCurve( npts );
  17156. this.curves.push( curve );
  17157. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17158. };
  17159. // FUTURE: Change the API or follow canvas API?
  17160. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17161. aStartAngle, aEndAngle, aClockwise ) {
  17162. var lastargs = this.actions[ this.actions.length - 1].args;
  17163. var x0 = lastargs[ lastargs.length - 2 ];
  17164. var y0 = lastargs[ lastargs.length - 1 ];
  17165. this.absarc(aX + x0, aY + y0, aRadius,
  17166. aStartAngle, aEndAngle, aClockwise );
  17167. };
  17168. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17169. aStartAngle, aEndAngle, aClockwise ) {
  17170. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17171. };
  17172. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17173. aStartAngle, aEndAngle, aClockwise ) {
  17174. var lastargs = this.actions[ this.actions.length - 1].args;
  17175. var x0 = lastargs[ lastargs.length - 2 ];
  17176. var y0 = lastargs[ lastargs.length - 1 ];
  17177. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17178. aStartAngle, aEndAngle, aClockwise );
  17179. };
  17180. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17181. aStartAngle, aEndAngle, aClockwise ) {
  17182. var args = Array.prototype.slice.call( arguments );
  17183. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17184. aStartAngle, aEndAngle, aClockwise );
  17185. this.curves.push( curve );
  17186. var lastPoint = curve.getPoint(1);
  17187. args.push(lastPoint.x);
  17188. args.push(lastPoint.y);
  17189. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17190. };
  17191. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17192. if ( ! divisions ) divisions = 40;
  17193. var points = [];
  17194. for ( var i = 0; i < divisions; i ++ ) {
  17195. points.push( this.getPoint( i / divisions ) );
  17196. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17197. }
  17198. // if ( closedPath ) {
  17199. //
  17200. // points.push( points[ 0 ] );
  17201. //
  17202. // }
  17203. return points;
  17204. };
  17205. /* Return an array of vectors based on contour of the path */
  17206. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17207. if (this.useSpacedPoints) {
  17208. console.log('tata');
  17209. return this.getSpacedPoints( divisions, closedPath );
  17210. }
  17211. divisions = divisions || 12;
  17212. var points = [];
  17213. var i, il, item, action, args;
  17214. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17215. laste, j,
  17216. t, tx, ty;
  17217. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17218. item = this.actions[ i ];
  17219. action = item.action;
  17220. args = item.args;
  17221. switch( action ) {
  17222. case THREE.PathActions.MOVE_TO:
  17223. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17224. break;
  17225. case THREE.PathActions.LINE_TO:
  17226. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17227. break;
  17228. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17229. cpx = args[ 2 ];
  17230. cpy = args[ 3 ];
  17231. cpx1 = args[ 0 ];
  17232. cpy1 = args[ 1 ];
  17233. if ( points.length > 0 ) {
  17234. laste = points[ points.length - 1 ];
  17235. cpx0 = laste.x;
  17236. cpy0 = laste.y;
  17237. } else {
  17238. laste = this.actions[ i - 1 ].args;
  17239. cpx0 = laste[ laste.length - 2 ];
  17240. cpy0 = laste[ laste.length - 1 ];
  17241. }
  17242. for ( j = 1; j <= divisions; j ++ ) {
  17243. t = j / divisions;
  17244. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17245. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17246. points.push( new THREE.Vector2( tx, ty ) );
  17247. }
  17248. break;
  17249. case THREE.PathActions.BEZIER_CURVE_TO:
  17250. cpx = args[ 4 ];
  17251. cpy = args[ 5 ];
  17252. cpx1 = args[ 0 ];
  17253. cpy1 = args[ 1 ];
  17254. cpx2 = args[ 2 ];
  17255. cpy2 = args[ 3 ];
  17256. if ( points.length > 0 ) {
  17257. laste = points[ points.length - 1 ];
  17258. cpx0 = laste.x;
  17259. cpy0 = laste.y;
  17260. } else {
  17261. laste = this.actions[ i - 1 ].args;
  17262. cpx0 = laste[ laste.length - 2 ];
  17263. cpy0 = laste[ laste.length - 1 ];
  17264. }
  17265. for ( j = 1; j <= divisions; j ++ ) {
  17266. t = j / divisions;
  17267. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17268. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17269. points.push( new THREE.Vector2( tx, ty ) );
  17270. }
  17271. break;
  17272. case THREE.PathActions.CSPLINE_THRU:
  17273. laste = this.actions[ i - 1 ].args;
  17274. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17275. var spts = [ last ];
  17276. var n = divisions * args[ 0 ].length;
  17277. spts = spts.concat( args[ 0 ] );
  17278. var spline = new THREE.SplineCurve( spts );
  17279. for ( j = 1; j <= n; j ++ ) {
  17280. points.push( spline.getPointAt( j / n ) ) ;
  17281. }
  17282. break;
  17283. case THREE.PathActions.ARC:
  17284. var aX = args[ 0 ], aY = args[ 1 ],
  17285. aRadius = args[ 2 ],
  17286. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17287. aClockwise = !!args[ 5 ];
  17288. var deltaAngle = aEndAngle - aStartAngle;
  17289. var angle;
  17290. var tdivisions = divisions * 2;
  17291. for ( j = 1; j <= tdivisions; j ++ ) {
  17292. t = j / tdivisions;
  17293. if ( ! aClockwise ) {
  17294. t = 1 - t;
  17295. }
  17296. angle = aStartAngle + t * deltaAngle;
  17297. tx = aX + aRadius * Math.cos( angle );
  17298. ty = aY + aRadius * Math.sin( angle );
  17299. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17300. points.push( new THREE.Vector2( tx, ty ) );
  17301. }
  17302. //console.log(points);
  17303. break;
  17304. case THREE.PathActions.ELLIPSE:
  17305. var aX = args[ 0 ], aY = args[ 1 ],
  17306. xRadius = args[ 2 ],
  17307. yRadius = args[ 3 ],
  17308. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17309. aClockwise = !!args[ 6 ];
  17310. var deltaAngle = aEndAngle - aStartAngle;
  17311. var angle;
  17312. var tdivisions = divisions * 2;
  17313. for ( j = 1; j <= tdivisions; j ++ ) {
  17314. t = j / tdivisions;
  17315. if ( ! aClockwise ) {
  17316. t = 1 - t;
  17317. }
  17318. angle = aStartAngle + t * deltaAngle;
  17319. tx = aX + xRadius * Math.cos( angle );
  17320. ty = aY + yRadius * Math.sin( angle );
  17321. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17322. points.push( new THREE.Vector2( tx, ty ) );
  17323. }
  17324. //console.log(points);
  17325. break;
  17326. } // end switch
  17327. }
  17328. // Normalize to remove the closing point by default.
  17329. var lastPoint = points[ points.length - 1];
  17330. var EPSILON = 0.0000000001;
  17331. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17332. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17333. points.splice( points.length - 1, 1);
  17334. if ( closedPath ) {
  17335. points.push( points[ 0 ] );
  17336. }
  17337. return points;
  17338. };
  17339. // Breaks path into shapes
  17340. THREE.Path.prototype.toShapes = function( isCCW ) {
  17341. function isPointInsidePolygon( inPt, inPolygon ) {
  17342. var EPSILON = 0.0000000001;
  17343. var polyLen = inPolygon.length;
  17344. // inPt on polygon contour => immediate success or
  17345. // toggling of inside/outside at every single! intersection point of an edge
  17346. // with the horizontal line through inPt, left of inPt
  17347. // not counting lowerY endpoints of edges and whole edges on that line
  17348. var inside = false;
  17349. for( var p = polyLen - 1, q = 0; q < polyLen; p = q++ ) {
  17350. var edgeLowPt = inPolygon[ p ];
  17351. var edgeHighPt = inPolygon[ q ];
  17352. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  17353. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  17354. if ( Math.abs(edgeDy) > EPSILON ) { // not parallel
  17355. if ( edgeDy < 0 ) {
  17356. edgeLowPt = inPolygon[ q ]; edgeDx = -edgeDx;
  17357. edgeHighPt = inPolygon[ p ]; edgeDy = -edgeDy;
  17358. }
  17359. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  17360. if ( inPt.y == edgeLowPt.y ) {
  17361. if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ?
  17362. // continue; // no intersection or edgeLowPt => doesn't count !!!
  17363. } else {
  17364. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  17365. if ( perpEdge == 0 ) return true; // inPt is on contour ?
  17366. if ( perpEdge < 0 ) continue;
  17367. inside = !inside; // true intersection left of inPt
  17368. }
  17369. } else { // parallel or colinear
  17370. if ( inPt.y != edgeLowPt.y ) continue; // parallel
  17371. // egde lies on the same horizontal line as inPt
  17372. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  17373. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  17374. // continue;
  17375. }
  17376. }
  17377. return inside;
  17378. }
  17379. var i, il, item, action, args;
  17380. var subPaths = [], lastPath = new THREE.Path();
  17381. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17382. item = this.actions[ i ];
  17383. args = item.args;
  17384. action = item.action;
  17385. if ( action == THREE.PathActions.MOVE_TO ) {
  17386. if ( lastPath.actions.length != 0 ) {
  17387. subPaths.push( lastPath );
  17388. lastPath = new THREE.Path();
  17389. }
  17390. }
  17391. lastPath[ action ].apply( lastPath, args );
  17392. }
  17393. if ( lastPath.actions.length != 0 ) {
  17394. subPaths.push( lastPath );
  17395. }
  17396. // console.log(subPaths);
  17397. if ( subPaths.length == 0 ) return [];
  17398. var solid, tmpPath, tmpShape, shapes = [];
  17399. if ( subPaths.length == 1) {
  17400. tmpPath = subPaths[0];
  17401. tmpShape = new THREE.Shape();
  17402. tmpShape.actions = tmpPath.actions;
  17403. tmpShape.curves = tmpPath.curves;
  17404. shapes.push( tmpShape );
  17405. return shapes;
  17406. }
  17407. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17408. holesFirst = isCCW ? !holesFirst : holesFirst;
  17409. // console.log("Holes first", holesFirst);
  17410. var betterShapeHoles = [];
  17411. var newShapes = [];
  17412. var newShapeHoles = [];
  17413. var mainIdx = 0;
  17414. var tmpPoints;
  17415. newShapes[mainIdx] = undefined;
  17416. newShapeHoles[mainIdx] = [];
  17417. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17418. tmpPath = subPaths[ i ];
  17419. tmpPoints = tmpPath.getPoints();
  17420. solid = THREE.Shape.Utils.isClockWise( tmpPoints );
  17421. solid = isCCW ? !solid : solid;
  17422. if ( solid ) {
  17423. if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx++;
  17424. newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints };
  17425. newShapes[mainIdx].s.actions = tmpPath.actions;
  17426. newShapes[mainIdx].s.curves = tmpPath.curves;
  17427. if ( holesFirst ) mainIdx++;
  17428. newShapeHoles[mainIdx] = [];
  17429. //console.log('cw', i);
  17430. } else {
  17431. newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } );
  17432. //console.log('ccw', i);
  17433. }
  17434. }
  17435. if ( newShapes.length > 1 ) {
  17436. var ambigious = false;
  17437. var toChange = [];
  17438. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
  17439. betterShapeHoles[sIdx] = [];
  17440. }
  17441. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
  17442. var sh = newShapes[sIdx];
  17443. var sho = newShapeHoles[sIdx];
  17444. for (var hIdx = 0; hIdx < sho.length; hIdx++ ) {
  17445. var ho = sho[hIdx];
  17446. var hole_unassigned = true;
  17447. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++ ) {
  17448. if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) {
  17449. if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  17450. if ( hole_unassigned ) {
  17451. hole_unassigned = false;
  17452. betterShapeHoles[s2Idx].push( ho );
  17453. } else {
  17454. ambigious = true;
  17455. }
  17456. }
  17457. }
  17458. if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); }
  17459. }
  17460. }
  17461. // console.log("ambigious: ", ambigious);
  17462. if ( toChange.length > 0 ) {
  17463. // console.log("to change: ", toChange);
  17464. if (! ambigious) newShapeHoles = betterShapeHoles;
  17465. }
  17466. }
  17467. var tmpHoles, j, jl;
  17468. for ( i = 0, il = newShapes.length; i < il; i ++ ) {
  17469. tmpShape = newShapes[i].s;
  17470. shapes.push( tmpShape );
  17471. tmpHoles = newShapeHoles[i];
  17472. for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  17473. tmpShape.holes.push( tmpHoles[j].h );
  17474. }
  17475. }
  17476. //console.log("shape", shapes);
  17477. return shapes;
  17478. };
  17479. /**
  17480. * @author zz85 / http://www.lab4games.net/zz85/blog
  17481. * Defines a 2d shape plane using paths.
  17482. **/
  17483. // STEP 1 Create a path.
  17484. // STEP 2 Turn path into shape.
  17485. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17486. // STEP 3a - Extract points from each shape, turn to vertices
  17487. // STEP 3b - Triangulate each shape, add faces.
  17488. THREE.Shape = function () {
  17489. THREE.Path.apply( this, arguments );
  17490. this.holes = [];
  17491. };
  17492. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17493. // Convenience method to return ExtrudeGeometry
  17494. THREE.Shape.prototype.extrude = function ( options ) {
  17495. var extruded = new THREE.ExtrudeGeometry( this, options );
  17496. return extruded;
  17497. };
  17498. // Convenience method to return ShapeGeometry
  17499. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17500. var geometry = new THREE.ShapeGeometry( this, options );
  17501. return geometry;
  17502. };
  17503. // Get points of holes
  17504. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17505. var i, il = this.holes.length, holesPts = [];
  17506. for ( i = 0; i < il; i ++ ) {
  17507. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17508. }
  17509. return holesPts;
  17510. };
  17511. // Get points of holes (spaced by regular distance)
  17512. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17513. var i, il = this.holes.length, holesPts = [];
  17514. for ( i = 0; i < il; i ++ ) {
  17515. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17516. }
  17517. return holesPts;
  17518. };
  17519. // Get points of shape and holes (keypoints based on segments parameter)
  17520. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17521. return {
  17522. shape: this.getTransformedPoints( divisions ),
  17523. holes: this.getPointsHoles( divisions )
  17524. };
  17525. };
  17526. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17527. if (this.useSpacedPoints) {
  17528. return this.extractAllSpacedPoints(divisions);
  17529. }
  17530. return this.extractAllPoints(divisions);
  17531. };
  17532. //
  17533. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17534. //
  17535. // return {
  17536. //
  17537. // shape: this.transform( bend, divisions ),
  17538. // holes: this.getPointsHoles( divisions, bend )
  17539. //
  17540. // };
  17541. //
  17542. // };
  17543. // Get points of shape and holes (spaced by regular distance)
  17544. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17545. return {
  17546. shape: this.getTransformedSpacedPoints( divisions ),
  17547. holes: this.getSpacedPointsHoles( divisions )
  17548. };
  17549. };
  17550. /**************************************************************
  17551. * Utils
  17552. **************************************************************/
  17553. THREE.Shape.Utils = {
  17554. triangulateShape: function ( contour, holes ) {
  17555. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  17556. // inOtherPt needs to be colinear to the inSegment
  17557. if ( inSegPt1.x != inSegPt2.x ) {
  17558. if ( inSegPt1.x < inSegPt2.x ) {
  17559. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  17560. } else {
  17561. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  17562. }
  17563. } else {
  17564. if ( inSegPt1.y < inSegPt2.y ) {
  17565. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  17566. } else {
  17567. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  17568. }
  17569. }
  17570. }
  17571. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  17572. var EPSILON = 0.0000000001;
  17573. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  17574. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  17575. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  17576. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  17577. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  17578. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  17579. if ( Math.abs(limit) > EPSILON ) { // not parallel
  17580. var perpSeg2;
  17581. if ( limit > 0 ) {
  17582. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  17583. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17584. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  17585. } else {
  17586. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  17587. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17588. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  17589. }
  17590. // i.e. to reduce rounding errors
  17591. // intersection at endpoint of segment#1?
  17592. if ( perpSeg2 == 0 ) {
  17593. if ( ( inExcludeAdjacentSegs ) &&
  17594. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17595. return [ inSeg1Pt1 ];
  17596. }
  17597. if ( perpSeg2 == limit ) {
  17598. if ( ( inExcludeAdjacentSegs ) &&
  17599. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17600. return [ inSeg1Pt2 ];
  17601. }
  17602. // intersection at endpoint of segment#2?
  17603. if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ];
  17604. if ( perpSeg1 == limit ) return [ inSeg2Pt2 ];
  17605. // return real intersection point
  17606. var factorSeg1 = perpSeg2 / limit;
  17607. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  17608. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  17609. } else { // parallel or colinear
  17610. if ( ( perpSeg1 != 0 ) ||
  17611. ( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return [];
  17612. // they are collinear or degenerate
  17613. var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point?
  17614. var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point?
  17615. // both segments are points
  17616. if ( seg1Pt && seg2Pt ) {
  17617. if ( (inSeg1Pt1.x != inSeg2Pt1.x) ||
  17618. (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points
  17619. return [ inSeg1Pt1 ]; // they are the same point
  17620. }
  17621. // segment#1 is a single point
  17622. if ( seg1Pt ) {
  17623. if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  17624. return [ inSeg1Pt1 ];
  17625. }
  17626. // segment#2 is a single point
  17627. if ( seg2Pt ) {
  17628. if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  17629. return [ inSeg2Pt1 ];
  17630. }
  17631. // they are collinear segments, which might overlap
  17632. var seg1min, seg1max, seg1minVal, seg1maxVal;
  17633. var seg2min, seg2max, seg2minVal, seg2maxVal;
  17634. if (seg1dx != 0) { // the segments are NOT on a vertical line
  17635. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  17636. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  17637. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  17638. } else {
  17639. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  17640. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  17641. }
  17642. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  17643. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  17644. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  17645. } else {
  17646. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  17647. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  17648. }
  17649. } else { // the segments are on a vertical line
  17650. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  17651. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  17652. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  17653. } else {
  17654. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  17655. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  17656. }
  17657. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  17658. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  17659. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  17660. } else {
  17661. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  17662. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  17663. }
  17664. }
  17665. if ( seg1minVal <= seg2minVal ) {
  17666. if ( seg1maxVal < seg2minVal ) return [];
  17667. if ( seg1maxVal == seg2minVal ) {
  17668. if ( inExcludeAdjacentSegs ) return [];
  17669. return [ seg2min ];
  17670. }
  17671. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  17672. return [ seg2min, seg2max ];
  17673. } else {
  17674. if ( seg1minVal > seg2maxVal ) return [];
  17675. if ( seg1minVal == seg2maxVal ) {
  17676. if ( inExcludeAdjacentSegs ) return [];
  17677. return [ seg1min ];
  17678. }
  17679. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  17680. return [ seg1min, seg2max ];
  17681. }
  17682. }
  17683. }
  17684. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  17685. // The order of legs is important
  17686. var EPSILON = 0.0000000001;
  17687. // translation of all points, so that Vertex is at (0,0)
  17688. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  17689. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  17690. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  17691. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  17692. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  17693. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  17694. if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg.
  17695. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  17696. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  17697. if ( from2toAngle > 0 ) { // main angle < 180 deg.
  17698. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  17699. } else { // main angle > 180 deg.
  17700. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  17701. }
  17702. } else { // angle == 180 deg.
  17703. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  17704. return ( from2otherAngle > 0 );
  17705. }
  17706. }
  17707. function removeHoles( contour, holes ) {
  17708. var shape = contour.concat(); // work on this shape
  17709. var hole;
  17710. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  17711. // Check if hole point lies within angle around shape point
  17712. var lastShapeIdx = shape.length - 1;
  17713. var prevShapeIdx = inShapeIdx - 1;
  17714. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  17715. var nextShapeIdx = inShapeIdx + 1;
  17716. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  17717. var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] );
  17718. if (! insideAngle ) {
  17719. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  17720. return false;
  17721. }
  17722. // Check if shape point lies within angle around hole point
  17723. var lastHoleIdx = hole.length - 1;
  17724. var prevHoleIdx = inHoleIdx - 1;
  17725. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  17726. var nextHoleIdx = inHoleIdx + 1;
  17727. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  17728. insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] );
  17729. if (! insideAngle ) {
  17730. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  17731. return false;
  17732. }
  17733. return true;
  17734. }
  17735. function intersectsShapeEdge( inShapePt, inHolePt ) {
  17736. // checks for intersections with shape edges
  17737. var sIdx, nextIdx, intersection;
  17738. for ( sIdx = 0; sIdx < shape.length; sIdx++ ) {
  17739. nextIdx = sIdx+1; nextIdx %= shape.length;
  17740. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true );
  17741. if ( intersection.length > 0 ) return true;
  17742. }
  17743. return false;
  17744. }
  17745. var indepHoles = [];
  17746. function intersectsHoleEdge( inShapePt, inHolePt ) {
  17747. // checks for intersections with hole edges
  17748. var ihIdx, chkHole,
  17749. hIdx, nextIdx, intersection;
  17750. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx++ ) {
  17751. chkHole = holes[indepHoles[ihIdx]];
  17752. for ( hIdx = 0; hIdx < chkHole.length; hIdx++ ) {
  17753. nextIdx = hIdx+1; nextIdx %= chkHole.length;
  17754. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true );
  17755. if ( intersection.length > 0 ) return true;
  17756. }
  17757. }
  17758. return false;
  17759. }
  17760. var holeIndex, shapeIndex,
  17761. shapePt, h, h2, holePt,
  17762. holeIdx, cutKey, failedCuts = [],
  17763. tmpShape1, tmpShape2,
  17764. tmpHole1, tmpHole2;
  17765. for (h in holes) { indepHoles.push( h ); }
  17766. var counter = indepHoles.length * 2;
  17767. while ( indepHoles.length > 0 ) {
  17768. counter --;
  17769. if ( counter < 0 ) {
  17770. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  17771. break;
  17772. }
  17773. // search for shape-vertex and hole-vertex,
  17774. // which can be connected without intersections
  17775. for ( shapeIndex = 0; shapeIndex < shape.length; shapeIndex++ ) {
  17776. shapePt = shape[ shapeIndex ];
  17777. holeIndex = -1;
  17778. // search for hole which can be reached without intersections
  17779. for ( h = 0; h < indepHoles.length; h++ ) {
  17780. holeIdx = indepHoles[h];
  17781. // prevent multiple checks
  17782. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  17783. if ( failedCuts[cutKey] !== undefined ) continue;
  17784. hole = holes[holeIdx];
  17785. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17786. holePt = hole[ h2 ];
  17787. if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  17788. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  17789. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  17790. holeIndex = h2;
  17791. indepHoles.splice(h,1);
  17792. tmpShape1 = shape.slice( 0, shapeIndex+1 );
  17793. tmpShape2 = shape.slice( shapeIndex );
  17794. tmpHole1 = hole.slice( holeIndex );
  17795. tmpHole2 = hole.slice( 0, holeIndex+1 );
  17796. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17797. // Debug only, to show the selected cuts
  17798. // glob_CutLines.push( [ shapePt, holePt ] );
  17799. break;
  17800. }
  17801. if ( holeIndex >= 0 ) break; // hole-vertex found
  17802. failedCuts[cutKey] = true; // remember failure
  17803. }
  17804. if ( holeIndex >= 0 ) break; // hole-vertex found
  17805. }
  17806. }
  17807. return shape; /* shape with no holes */
  17808. }
  17809. var i, il, f, face,
  17810. key, index,
  17811. allPointsMap = {};
  17812. // 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.
  17813. var allpoints = contour.concat();
  17814. for (var h in holes) { Array.prototype.push.apply( allpoints, holes[h] ); }
  17815. //console.log( "allpoints",allpoints, allpoints.length );
  17816. // prepare all points map
  17817. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17818. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17819. if ( allPointsMap[ key ] !== undefined ) {
  17820. console.log( "Duplicate point", key );
  17821. }
  17822. allPointsMap[ key ] = i;
  17823. }
  17824. // remove holes by cutting paths to holes and adding them to the shape
  17825. var shapeWithoutHoles = removeHoles( contour, holes );
  17826. var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  17827. //console.log( "triangles",triangles, triangles.length );
  17828. // check all face vertices against all points map
  17829. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17830. face = triangles[ i ];
  17831. for ( f = 0; f < 3; f ++ ) {
  17832. key = face[ f ].x + ":" + face[ f ].y;
  17833. index = allPointsMap[ key ];
  17834. if ( index !== undefined ) {
  17835. face[ f ] = index;
  17836. }
  17837. }
  17838. }
  17839. return triangles.concat();
  17840. },
  17841. isClockWise: function ( pts ) {
  17842. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17843. },
  17844. // Bezier Curves formulas obtained from
  17845. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17846. // Quad Bezier Functions
  17847. b2p0: function ( t, p ) {
  17848. var k = 1 - t;
  17849. return k * k * p;
  17850. },
  17851. b2p1: function ( t, p ) {
  17852. return 2 * ( 1 - t ) * t * p;
  17853. },
  17854. b2p2: function ( t, p ) {
  17855. return t * t * p;
  17856. },
  17857. b2: function ( t, p0, p1, p2 ) {
  17858. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17859. },
  17860. // Cubic Bezier Functions
  17861. b3p0: function ( t, p ) {
  17862. var k = 1 - t;
  17863. return k * k * k * p;
  17864. },
  17865. b3p1: function ( t, p ) {
  17866. var k = 1 - t;
  17867. return 3 * k * k * t * p;
  17868. },
  17869. b3p2: function ( t, p ) {
  17870. var k = 1 - t;
  17871. return 3 * k * t * t * p;
  17872. },
  17873. b3p3: function ( t, p ) {
  17874. return t * t * t * p;
  17875. },
  17876. b3: function ( t, p0, p1, p2, p3 ) {
  17877. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17878. }
  17879. };
  17880. /**************************************************************
  17881. * Line
  17882. **************************************************************/
  17883. THREE.LineCurve = function ( v1, v2 ) {
  17884. this.v1 = v1;
  17885. this.v2 = v2;
  17886. };
  17887. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17888. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17889. var point = this.v2.clone().sub(this.v1);
  17890. point.multiplyScalar( t ).add( this.v1 );
  17891. return point;
  17892. };
  17893. // Line curve is linear, so we can overwrite default getPointAt
  17894. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17895. return this.getPoint( u );
  17896. };
  17897. THREE.LineCurve.prototype.getTangent = function( t ) {
  17898. var tangent = this.v2.clone().sub(this.v1);
  17899. return tangent.normalize();
  17900. };
  17901. /**************************************************************
  17902. * Quadratic Bezier curve
  17903. **************************************************************/
  17904. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17905. this.v0 = v0;
  17906. this.v1 = v1;
  17907. this.v2 = v2;
  17908. };
  17909. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17910. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17911. var tx, ty;
  17912. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17913. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17914. return new THREE.Vector2( tx, ty );
  17915. };
  17916. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17917. var tx, ty;
  17918. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17919. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17920. // returns unit vector
  17921. var tangent = new THREE.Vector2( tx, ty );
  17922. tangent.normalize();
  17923. return tangent;
  17924. };
  17925. /**************************************************************
  17926. * Cubic Bezier curve
  17927. **************************************************************/
  17928. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17929. this.v0 = v0;
  17930. this.v1 = v1;
  17931. this.v2 = v2;
  17932. this.v3 = v3;
  17933. };
  17934. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17935. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  17936. var tx, ty;
  17937. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17938. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17939. return new THREE.Vector2( tx, ty );
  17940. };
  17941. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  17942. var tx, ty;
  17943. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17944. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17945. var tangent = new THREE.Vector2( tx, ty );
  17946. tangent.normalize();
  17947. return tangent;
  17948. };
  17949. /**************************************************************
  17950. * Spline curve
  17951. **************************************************************/
  17952. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  17953. this.points = (points == undefined) ? [] : points;
  17954. };
  17955. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  17956. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  17957. var v = new THREE.Vector2();
  17958. var c = [];
  17959. var points = this.points, point, intPoint, weight;
  17960. point = ( points.length - 1 ) * t;
  17961. intPoint = Math.floor( point );
  17962. weight = point - intPoint;
  17963. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17964. c[ 1 ] = intPoint;
  17965. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  17966. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  17967. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17968. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17969. return v;
  17970. };
  17971. /**************************************************************
  17972. * Ellipse curve
  17973. **************************************************************/
  17974. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  17975. this.aX = aX;
  17976. this.aY = aY;
  17977. this.xRadius = xRadius;
  17978. this.yRadius = yRadius;
  17979. this.aStartAngle = aStartAngle;
  17980. this.aEndAngle = aEndAngle;
  17981. this.aClockwise = aClockwise;
  17982. };
  17983. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  17984. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  17985. var angle;
  17986. var deltaAngle = this.aEndAngle - this.aStartAngle;
  17987. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  17988. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  17989. if ( this.aClockwise === true ) {
  17990. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  17991. } else {
  17992. angle = this.aStartAngle + t * deltaAngle;
  17993. }
  17994. var tx = this.aX + this.xRadius * Math.cos( angle );
  17995. var ty = this.aY + this.yRadius * Math.sin( angle );
  17996. return new THREE.Vector2( tx, ty );
  17997. };
  17998. /**************************************************************
  17999. * Arc curve
  18000. **************************************************************/
  18001. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18002. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18003. };
  18004. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  18005. /**************************************************************
  18006. * Line3D
  18007. **************************************************************/
  18008. THREE.LineCurve3 = THREE.Curve.create(
  18009. function ( v1, v2 ) {
  18010. this.v1 = v1;
  18011. this.v2 = v2;
  18012. },
  18013. function ( t ) {
  18014. var r = new THREE.Vector3();
  18015. r.subVectors( this.v2, this.v1 ); // diff
  18016. r.multiplyScalar( t );
  18017. r.add( this.v1 );
  18018. return r;
  18019. }
  18020. );
  18021. /**************************************************************
  18022. * Quadratic Bezier 3D curve
  18023. **************************************************************/
  18024. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  18025. function ( v0, v1, v2 ) {
  18026. this.v0 = v0;
  18027. this.v1 = v1;
  18028. this.v2 = v2;
  18029. },
  18030. function ( t ) {
  18031. var tx, ty, tz;
  18032. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  18033. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  18034. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  18035. return new THREE.Vector3( tx, ty, tz );
  18036. }
  18037. );
  18038. /**************************************************************
  18039. * Cubic Bezier 3D curve
  18040. **************************************************************/
  18041. THREE.CubicBezierCurve3 = THREE.Curve.create(
  18042. function ( v0, v1, v2, v3 ) {
  18043. this.v0 = v0;
  18044. this.v1 = v1;
  18045. this.v2 = v2;
  18046. this.v3 = v3;
  18047. },
  18048. function ( t ) {
  18049. var tx, ty, tz;
  18050. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18051. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18052. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  18053. return new THREE.Vector3( tx, ty, tz );
  18054. }
  18055. );
  18056. /**************************************************************
  18057. * Spline 3D curve
  18058. **************************************************************/
  18059. THREE.SplineCurve3 = THREE.Curve.create(
  18060. function ( points /* array of Vector3 */) {
  18061. this.points = (points == undefined) ? [] : points;
  18062. },
  18063. function ( t ) {
  18064. var v = new THREE.Vector3();
  18065. var c = [];
  18066. var points = this.points, point, intPoint, weight;
  18067. point = ( points.length - 1 ) * t;
  18068. intPoint = Math.floor( point );
  18069. weight = point - intPoint;
  18070. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18071. c[ 1 ] = intPoint;
  18072. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18073. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18074. var pt0 = points[ c[0] ],
  18075. pt1 = points[ c[1] ],
  18076. pt2 = points[ c[2] ],
  18077. pt3 = points[ c[3] ];
  18078. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  18079. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  18080. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  18081. return v;
  18082. }
  18083. );
  18084. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  18085. // var v = new THREE.Vector3();
  18086. // var c = [];
  18087. // var points = this.points, point, intPoint, weight;
  18088. // point = ( points.length - 1 ) * t;
  18089. // intPoint = Math.floor( point );
  18090. // weight = point - intPoint;
  18091. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18092. // c[ 1 ] = intPoint;
  18093. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18094. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18095. // var pt0 = points[ c[0] ],
  18096. // pt1 = points[ c[1] ],
  18097. // pt2 = points[ c[2] ],
  18098. // pt3 = points[ c[3] ];
  18099. // // t = weight;
  18100. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  18101. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  18102. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  18103. // return v;
  18104. // }
  18105. /**************************************************************
  18106. * Closed Spline 3D curve
  18107. **************************************************************/
  18108. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  18109. function ( points /* array of Vector3 */) {
  18110. this.points = (points == undefined) ? [] : points;
  18111. },
  18112. function ( t ) {
  18113. var v = new THREE.Vector3();
  18114. var c = [];
  18115. var points = this.points, point, intPoint, weight;
  18116. point = ( points.length - 0 ) * t;
  18117. // This needs to be from 0-length +1
  18118. intPoint = Math.floor( point );
  18119. weight = point - intPoint;
  18120. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  18121. c[ 0 ] = ( intPoint - 1 ) % points.length;
  18122. c[ 1 ] = ( intPoint ) % points.length;
  18123. c[ 2 ] = ( intPoint + 1 ) % points.length;
  18124. c[ 3 ] = ( intPoint + 2 ) % points.length;
  18125. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18126. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18127. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  18128. return v;
  18129. }
  18130. );
  18131. /**
  18132. * @author mikael emtinger / http://gomo.se/
  18133. */
  18134. THREE.AnimationHandler = (function() {
  18135. var playing = [];
  18136. var library = {};
  18137. var that = {};
  18138. //--- update ---
  18139. that.update = function( deltaTimeMS ) {
  18140. for( var i = 0; i < playing.length; i ++ )
  18141. playing[ i ].update( deltaTimeMS );
  18142. };
  18143. //--- add ---
  18144. that.addToUpdate = function( animation ) {
  18145. if ( playing.indexOf( animation ) === -1 )
  18146. playing.push( animation );
  18147. };
  18148. //--- remove ---
  18149. that.removeFromUpdate = function( animation ) {
  18150. var index = playing.indexOf( animation );
  18151. if( index !== -1 )
  18152. playing.splice( index, 1 );
  18153. };
  18154. //--- add ---
  18155. that.add = function( data ) {
  18156. if ( library[ data.name ] !== undefined )
  18157. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  18158. library[ data.name ] = data;
  18159. initData( data );
  18160. };
  18161. //--- get ---
  18162. that.get = function( name ) {
  18163. if ( typeof name === "string" ) {
  18164. if ( library[ name ] ) {
  18165. return library[ name ];
  18166. } else {
  18167. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  18168. return null;
  18169. }
  18170. } else {
  18171. // todo: add simple tween library
  18172. }
  18173. };
  18174. //--- parse ---
  18175. that.parse = function( root ) {
  18176. // setup hierarchy
  18177. var hierarchy = [];
  18178. if ( root instanceof THREE.SkinnedMesh ) {
  18179. for( var b = 0; b < root.bones.length; b++ ) {
  18180. hierarchy.push( root.bones[ b ] );
  18181. }
  18182. } else {
  18183. parseRecurseHierarchy( root, hierarchy );
  18184. }
  18185. return hierarchy;
  18186. };
  18187. var parseRecurseHierarchy = function( root, hierarchy ) {
  18188. hierarchy.push( root );
  18189. for( var c = 0; c < root.children.length; c++ )
  18190. parseRecurseHierarchy( root.children[ c ], hierarchy );
  18191. }
  18192. //--- init data ---
  18193. var initData = function( data ) {
  18194. if( data.initialized === true )
  18195. return;
  18196. // loop through all keys
  18197. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  18198. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18199. // remove minus times
  18200. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  18201. data.hierarchy[ h ].keys[ k ].time = 0;
  18202. // create quaternions
  18203. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  18204. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  18205. var quat = data.hierarchy[ h ].keys[ k ].rot;
  18206. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  18207. }
  18208. }
  18209. // prepare morph target keys
  18210. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  18211. // get all used
  18212. var usedMorphTargets = {};
  18213. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18214. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18215. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  18216. usedMorphTargets[ morphTargetName ] = -1;
  18217. }
  18218. }
  18219. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  18220. // set all used on all frames
  18221. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18222. var influences = {};
  18223. for ( var morphTargetName in usedMorphTargets ) {
  18224. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18225. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  18226. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  18227. break;
  18228. }
  18229. }
  18230. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  18231. influences[ morphTargetName ] = 0;
  18232. }
  18233. }
  18234. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  18235. }
  18236. }
  18237. // remove all keys that are on the same time
  18238. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18239. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  18240. data.hierarchy[ h ].keys.splice( k, 1 );
  18241. k --;
  18242. }
  18243. }
  18244. // set index
  18245. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18246. data.hierarchy[ h ].keys[ k ].index = k;
  18247. }
  18248. }
  18249. // done
  18250. data.initialized = true;
  18251. };
  18252. // interpolation types
  18253. that.LINEAR = 0;
  18254. that.CATMULLROM = 1;
  18255. that.CATMULLROM_FORWARD = 2;
  18256. return that;
  18257. }());
  18258. /**
  18259. * @author mikael emtinger / http://gomo.se/
  18260. * @author mrdoob / http://mrdoob.com/
  18261. * @author alteredq / http://alteredqualia.com/
  18262. */
  18263. THREE.Animation = function ( root, name ) {
  18264. this.root = root;
  18265. this.data = THREE.AnimationHandler.get( name );
  18266. this.hierarchy = THREE.AnimationHandler.parse( root );
  18267. this.currentTime = 0;
  18268. this.timeScale = 1;
  18269. this.isPlaying = false;
  18270. this.isPaused = true;
  18271. this.loop = true;
  18272. this.interpolationType = THREE.AnimationHandler.LINEAR;
  18273. this.points = [];
  18274. this.target = new THREE.Vector3();
  18275. };
  18276. THREE.Animation.prototype.play = function ( startTime ) {
  18277. this.currentTime = startTime !== undefined ? startTime : 0;
  18278. if ( this.isPlaying === false ) {
  18279. this.isPlaying = true;
  18280. this.reset();
  18281. this.update( 0 );
  18282. }
  18283. this.isPaused = false;
  18284. THREE.AnimationHandler.addToUpdate( this );
  18285. };
  18286. THREE.Animation.prototype.pause = function() {
  18287. if ( this.isPaused === true ) {
  18288. THREE.AnimationHandler.addToUpdate( this );
  18289. } else {
  18290. THREE.AnimationHandler.removeFromUpdate( this );
  18291. }
  18292. this.isPaused = !this.isPaused;
  18293. };
  18294. THREE.Animation.prototype.stop = function() {
  18295. this.isPlaying = false;
  18296. this.isPaused = false;
  18297. THREE.AnimationHandler.removeFromUpdate( this );
  18298. };
  18299. THREE.Animation.prototype.reset = function () {
  18300. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18301. var object = this.hierarchy[ h ];
  18302. object.matrixAutoUpdate = true;
  18303. if ( object.animationCache === undefined ) {
  18304. object.animationCache = {};
  18305. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  18306. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  18307. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18308. }
  18309. var prevKey = object.animationCache.prevKey;
  18310. var nextKey = object.animationCache.nextKey;
  18311. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  18312. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  18313. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  18314. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  18315. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  18316. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  18317. }
  18318. };
  18319. THREE.Animation.prototype.update = function ( delta ) {
  18320. if ( this.isPlaying === false ) return;
  18321. this.currentTime += delta * this.timeScale;
  18322. //
  18323. var vector;
  18324. var types = [ "pos", "rot", "scl" ];
  18325. var duration = this.data.length;
  18326. if ( this.loop === true && this.currentTime > duration ) {
  18327. this.currentTime %= duration;
  18328. this.reset();
  18329. }
  18330. this.currentTime = Math.min( this.currentTime, duration );
  18331. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18332. var object = this.hierarchy[ h ];
  18333. var animationCache = object.animationCache;
  18334. // loop through pos/rot/scl
  18335. for ( var t = 0; t < 3; t ++ ) {
  18336. // get keys
  18337. var type = types[ t ];
  18338. var prevKey = animationCache.prevKey[ type ];
  18339. var nextKey = animationCache.nextKey[ type ];
  18340. if ( nextKey.time <= this.currentTime ) {
  18341. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18342. nextKey = this.getNextKeyWith( type, h, 1 );
  18343. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18344. prevKey = nextKey;
  18345. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18346. }
  18347. animationCache.prevKey[ type ] = prevKey;
  18348. animationCache.nextKey[ type ] = nextKey;
  18349. }
  18350. object.matrixAutoUpdate = true;
  18351. object.matrixWorldNeedsUpdate = true;
  18352. var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18353. var prevXYZ = prevKey[ type ];
  18354. var nextXYZ = nextKey[ type ];
  18355. if ( scale < 0 ) scale = 0;
  18356. if ( scale > 1 ) scale = 1;
  18357. // interpolate
  18358. if ( type === "pos" ) {
  18359. vector = object.position;
  18360. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18361. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18362. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18363. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18364. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18365. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18366. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18367. this.points[ 1 ] = prevXYZ;
  18368. this.points[ 2 ] = nextXYZ;
  18369. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18370. scale = scale * 0.33 + 0.33;
  18371. var currentPoint = this.interpolateCatmullRom( this.points, scale );
  18372. vector.x = currentPoint[ 0 ];
  18373. vector.y = currentPoint[ 1 ];
  18374. vector.z = currentPoint[ 2 ];
  18375. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18376. var forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  18377. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18378. this.target.sub( vector );
  18379. this.target.y = 0;
  18380. this.target.normalize();
  18381. var angle = Math.atan2( this.target.x, this.target.z );
  18382. object.rotation.set( 0, angle, 0 );
  18383. }
  18384. }
  18385. } else if ( type === "rot" ) {
  18386. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18387. } else if ( type === "scl" ) {
  18388. vector = object.scale;
  18389. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18390. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18391. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18392. }
  18393. }
  18394. }
  18395. if ( this.loop === false && this.currentTime > duration ) {
  18396. this.stop();
  18397. }
  18398. };
  18399. // Catmull-Rom spline
  18400. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  18401. var c = [], v3 = [],
  18402. point, intPoint, weight, w2, w3,
  18403. pa, pb, pc, pd;
  18404. point = ( points.length - 1 ) * scale;
  18405. intPoint = Math.floor( point );
  18406. weight = point - intPoint;
  18407. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18408. c[ 1 ] = intPoint;
  18409. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18410. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18411. pa = points[ c[ 0 ] ];
  18412. pb = points[ c[ 1 ] ];
  18413. pc = points[ c[ 2 ] ];
  18414. pd = points[ c[ 3 ] ];
  18415. w2 = weight * weight;
  18416. w3 = weight * w2;
  18417. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18418. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18419. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18420. return v3;
  18421. };
  18422. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18423. var v0 = ( p2 - p0 ) * 0.5,
  18424. v1 = ( p3 - p1 ) * 0.5;
  18425. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18426. };
  18427. // Get next key with
  18428. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18429. var keys = this.data.hierarchy[ h ].keys;
  18430. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18431. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18432. key = key < keys.length - 1 ? key : keys.length - 1;
  18433. } else {
  18434. key = key % keys.length;
  18435. }
  18436. for ( ; key < keys.length; key++ ) {
  18437. if ( keys[ key ][ type ] !== undefined ) {
  18438. return keys[ key ];
  18439. }
  18440. }
  18441. return this.data.hierarchy[ h ].keys[ 0 ];
  18442. };
  18443. // Get previous key with
  18444. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18445. var keys = this.data.hierarchy[ h ].keys;
  18446. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18447. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18448. key = key > 0 ? key : 0;
  18449. } else {
  18450. key = key >= 0 ? key : key + keys.length;
  18451. }
  18452. for ( ; key >= 0; key -- ) {
  18453. if ( keys[ key ][ type ] !== undefined ) {
  18454. return keys[ key ];
  18455. }
  18456. }
  18457. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18458. };
  18459. /**
  18460. * @author mikael emtinger / http://gomo.se/
  18461. * @author mrdoob / http://mrdoob.com/
  18462. * @author alteredq / http://alteredqualia.com/
  18463. * @author khang duong
  18464. * @author erik kitson
  18465. */
  18466. THREE.KeyFrameAnimation = function ( root, data ) {
  18467. this.root = root;
  18468. this.data = THREE.AnimationHandler.get( data );
  18469. this.hierarchy = THREE.AnimationHandler.parse( root );
  18470. this.currentTime = 0;
  18471. this.timeScale = 0.001;
  18472. this.isPlaying = false;
  18473. this.isPaused = true;
  18474. this.loop = true;
  18475. // initialize to first keyframes
  18476. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18477. var keys = this.data.hierarchy[h].keys,
  18478. sids = this.data.hierarchy[h].sids,
  18479. obj = this.hierarchy[h];
  18480. if ( keys.length && sids ) {
  18481. for ( var s = 0; s < sids.length; s++ ) {
  18482. var sid = sids[ s ],
  18483. next = this.getNextKeyWith( sid, h, 0 );
  18484. if ( next ) {
  18485. next.apply( sid );
  18486. }
  18487. }
  18488. obj.matrixAutoUpdate = false;
  18489. this.data.hierarchy[h].node.updateMatrix();
  18490. obj.matrixWorldNeedsUpdate = true;
  18491. }
  18492. }
  18493. };
  18494. // Play
  18495. THREE.KeyFrameAnimation.prototype.play = function ( startTime ) {
  18496. this.currentTime = startTime !== undefined ? startTime : 0;
  18497. if ( this.isPlaying === false ) {
  18498. this.isPlaying = true;
  18499. // reset key cache
  18500. var h, hl = this.hierarchy.length,
  18501. object,
  18502. node;
  18503. for ( h = 0; h < hl; h++ ) {
  18504. object = this.hierarchy[ h ];
  18505. node = this.data.hierarchy[ h ];
  18506. if ( node.animationCache === undefined ) {
  18507. node.animationCache = {};
  18508. node.animationCache.prevKey = null;
  18509. node.animationCache.nextKey = null;
  18510. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18511. }
  18512. var keys = this.data.hierarchy[h].keys;
  18513. if (keys.length) {
  18514. node.animationCache.prevKey = keys[ 0 ];
  18515. node.animationCache.nextKey = keys[ 1 ];
  18516. this.startTime = Math.min( keys[0].time, this.startTime );
  18517. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18518. }
  18519. }
  18520. this.update( 0 );
  18521. }
  18522. this.isPaused = false;
  18523. THREE.AnimationHandler.addToUpdate( this );
  18524. };
  18525. // Pause
  18526. THREE.KeyFrameAnimation.prototype.pause = function() {
  18527. if( this.isPaused ) {
  18528. THREE.AnimationHandler.addToUpdate( this );
  18529. } else {
  18530. THREE.AnimationHandler.removeFromUpdate( this );
  18531. }
  18532. this.isPaused = !this.isPaused;
  18533. };
  18534. // Stop
  18535. THREE.KeyFrameAnimation.prototype.stop = function() {
  18536. this.isPlaying = false;
  18537. this.isPaused = false;
  18538. THREE.AnimationHandler.removeFromUpdate( this );
  18539. // reset JIT matrix and remove cache
  18540. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18541. var obj = this.hierarchy[ h ];
  18542. var node = this.data.hierarchy[ h ];
  18543. if ( node.animationCache !== undefined ) {
  18544. var original = node.animationCache.originalMatrix;
  18545. if( obj instanceof THREE.Bone ) {
  18546. original.copy( obj.skinMatrix );
  18547. obj.skinMatrix = original;
  18548. } else {
  18549. original.copy( obj.matrix );
  18550. obj.matrix = original;
  18551. }
  18552. delete node.animationCache;
  18553. }
  18554. }
  18555. };
  18556. // Update
  18557. THREE.KeyFrameAnimation.prototype.update = function ( delta ) {
  18558. if ( this.isPlaying === false ) return;
  18559. this.currentTime += delta * this.timeScale;
  18560. //
  18561. var duration = this.data.length;
  18562. if ( this.loop === true && this.currentTime > duration ) {
  18563. this.currentTime %= duration;
  18564. }
  18565. this.currentTime = Math.min( this.currentTime, duration );
  18566. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18567. var object = this.hierarchy[ h ];
  18568. var node = this.data.hierarchy[ h ];
  18569. var keys = node.keys,
  18570. animationCache = node.animationCache;
  18571. if ( keys.length ) {
  18572. var prevKey = animationCache.prevKey;
  18573. var nextKey = animationCache.nextKey;
  18574. if ( nextKey.time <= this.currentTime ) {
  18575. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18576. prevKey = nextKey;
  18577. nextKey = keys[ prevKey.index + 1 ];
  18578. }
  18579. animationCache.prevKey = prevKey;
  18580. animationCache.nextKey = nextKey;
  18581. }
  18582. if ( nextKey.time >= this.currentTime ) {
  18583. prevKey.interpolate( nextKey, this.currentTime );
  18584. } else {
  18585. prevKey.interpolate( nextKey, nextKey.time );
  18586. }
  18587. this.data.hierarchy[ h ].node.updateMatrix();
  18588. object.matrixWorldNeedsUpdate = true;
  18589. }
  18590. }
  18591. };
  18592. // Get next key with
  18593. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18594. var keys = this.data.hierarchy[ h ].keys;
  18595. key = key % keys.length;
  18596. for ( ; key < keys.length; key++ ) {
  18597. if ( keys[ key ].hasTarget( sid ) ) {
  18598. return keys[ key ];
  18599. }
  18600. }
  18601. return keys[ 0 ];
  18602. };
  18603. // Get previous key with
  18604. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18605. var keys = this.data.hierarchy[ h ].keys;
  18606. key = key >= 0 ? key : key + keys.length;
  18607. for ( ; key >= 0; key-- ) {
  18608. if ( keys[ key ].hasTarget( sid ) ) {
  18609. return keys[ key ];
  18610. }
  18611. }
  18612. return keys[ keys.length - 1 ];
  18613. };
  18614. /**
  18615. * @author mrdoob / http://mrdoob.com
  18616. */
  18617. THREE.MorphAnimation = function ( mesh ) {
  18618. this.mesh = mesh;
  18619. this.frames = mesh.morphTargetInfluences.length;
  18620. this.currentTime = 0;
  18621. this.duration = 1000;
  18622. this.loop = true;
  18623. this.isPlaying = false;
  18624. };
  18625. THREE.MorphAnimation.prototype = {
  18626. play: function () {
  18627. this.isPlaying = true;
  18628. },
  18629. pause: function () {
  18630. this.isPlaying = false;
  18631. },
  18632. update: ( function () {
  18633. var lastFrame = 0;
  18634. var currentFrame = 0;
  18635. return function ( delta ) {
  18636. if ( this.isPlaying === false ) return;
  18637. this.currentTime += delta;
  18638. if ( this.loop === true && this.currentTime > this.duration ) {
  18639. this.currentTime %= this.duration;
  18640. }
  18641. this.currentTime = Math.min( this.currentTime, this.duration );
  18642. var interpolation = this.duration / this.frames;
  18643. var frame = Math.floor( this.currentTime / interpolation );
  18644. if ( frame != currentFrame ) {
  18645. this.mesh.morphTargetInfluences[ lastFrame ] = 0;
  18646. this.mesh.morphTargetInfluences[ currentFrame ] = 1;
  18647. this.mesh.morphTargetInfluences[ frame ] = 0;
  18648. lastFrame = currentFrame;
  18649. currentFrame = frame;
  18650. }
  18651. this.mesh.morphTargetInfluences[ frame ] = ( this.currentTime % interpolation ) / interpolation;
  18652. this.mesh.morphTargetInfluences[ lastFrame ] = 1 - this.mesh.morphTargetInfluences[ frame ];
  18653. }
  18654. } )()
  18655. };
  18656. /**
  18657. * Camera for rendering cube maps
  18658. * - renders scene into axis-aligned cube
  18659. *
  18660. * @author alteredq / http://alteredqualia.com/
  18661. */
  18662. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18663. THREE.Object3D.call( this );
  18664. var fov = 90, aspect = 1;
  18665. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18666. cameraPX.up.set( 0, -1, 0 );
  18667. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18668. this.add( cameraPX );
  18669. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18670. cameraNX.up.set( 0, -1, 0 );
  18671. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18672. this.add( cameraNX );
  18673. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18674. cameraPY.up.set( 0, 0, 1 );
  18675. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18676. this.add( cameraPY );
  18677. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18678. cameraNY.up.set( 0, 0, -1 );
  18679. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18680. this.add( cameraNY );
  18681. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18682. cameraPZ.up.set( 0, -1, 0 );
  18683. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18684. this.add( cameraPZ );
  18685. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18686. cameraNZ.up.set( 0, -1, 0 );
  18687. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18688. this.add( cameraNZ );
  18689. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18690. this.updateCubeMap = function ( renderer, scene ) {
  18691. var renderTarget = this.renderTarget;
  18692. var generateMipmaps = renderTarget.generateMipmaps;
  18693. renderTarget.generateMipmaps = false;
  18694. renderTarget.activeCubeFace = 0;
  18695. renderer.render( scene, cameraPX, renderTarget );
  18696. renderTarget.activeCubeFace = 1;
  18697. renderer.render( scene, cameraNX, renderTarget );
  18698. renderTarget.activeCubeFace = 2;
  18699. renderer.render( scene, cameraPY, renderTarget );
  18700. renderTarget.activeCubeFace = 3;
  18701. renderer.render( scene, cameraNY, renderTarget );
  18702. renderTarget.activeCubeFace = 4;
  18703. renderer.render( scene, cameraPZ, renderTarget );
  18704. renderTarget.generateMipmaps = generateMipmaps;
  18705. renderTarget.activeCubeFace = 5;
  18706. renderer.render( scene, cameraNZ, renderTarget );
  18707. };
  18708. };
  18709. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18710. /**
  18711. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18712. *
  18713. * A general perpose camera, for setting FOV, Lens Focal Length,
  18714. * and switching between perspective and orthographic views easily.
  18715. * Use this only if you do not wish to manage
  18716. * both a Orthographic and Perspective Camera
  18717. *
  18718. */
  18719. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18720. THREE.Camera.call( this );
  18721. this.fov = fov;
  18722. this.left = -width / 2;
  18723. this.right = width / 2
  18724. this.top = height / 2;
  18725. this.bottom = -height / 2;
  18726. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18727. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18728. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18729. this.zoom = 1;
  18730. this.toPerspective();
  18731. var aspect = width/height;
  18732. };
  18733. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18734. THREE.CombinedCamera.prototype.toPerspective = function () {
  18735. // Switches to the Perspective Camera
  18736. this.near = this.cameraP.near;
  18737. this.far = this.cameraP.far;
  18738. this.cameraP.fov = this.fov / this.zoom ;
  18739. this.cameraP.updateProjectionMatrix();
  18740. this.projectionMatrix = this.cameraP.projectionMatrix;
  18741. this.inPerspectiveMode = true;
  18742. this.inOrthographicMode = false;
  18743. };
  18744. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18745. // Switches to the Orthographic camera estimating viewport from Perspective
  18746. var fov = this.fov;
  18747. var aspect = this.cameraP.aspect;
  18748. var near = this.cameraP.near;
  18749. var far = this.cameraP.far;
  18750. // The size that we set is the mid plane of the viewing frustum
  18751. var hyperfocus = ( near + far ) / 2;
  18752. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18753. var planeHeight = 2 * halfHeight;
  18754. var planeWidth = planeHeight * aspect;
  18755. var halfWidth = planeWidth / 2;
  18756. halfHeight /= this.zoom;
  18757. halfWidth /= this.zoom;
  18758. this.cameraO.left = -halfWidth;
  18759. this.cameraO.right = halfWidth;
  18760. this.cameraO.top = halfHeight;
  18761. this.cameraO.bottom = -halfHeight;
  18762. // this.cameraO.left = -farHalfWidth;
  18763. // this.cameraO.right = farHalfWidth;
  18764. // this.cameraO.top = farHalfHeight;
  18765. // this.cameraO.bottom = -farHalfHeight;
  18766. // this.cameraO.left = this.left / this.zoom;
  18767. // this.cameraO.right = this.right / this.zoom;
  18768. // this.cameraO.top = this.top / this.zoom;
  18769. // this.cameraO.bottom = this.bottom / this.zoom;
  18770. this.cameraO.updateProjectionMatrix();
  18771. this.near = this.cameraO.near;
  18772. this.far = this.cameraO.far;
  18773. this.projectionMatrix = this.cameraO.projectionMatrix;
  18774. this.inPerspectiveMode = false;
  18775. this.inOrthographicMode = true;
  18776. };
  18777. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18778. this.cameraP.aspect = width / height;
  18779. this.left = -width / 2;
  18780. this.right = width / 2
  18781. this.top = height / 2;
  18782. this.bottom = -height / 2;
  18783. };
  18784. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18785. this.fov = fov;
  18786. if ( this.inPerspectiveMode ) {
  18787. this.toPerspective();
  18788. } else {
  18789. this.toOrthographic();
  18790. }
  18791. };
  18792. // For mantaining similar API with PerspectiveCamera
  18793. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18794. if ( this.inPerspectiveMode ) {
  18795. this.toPerspective();
  18796. } else {
  18797. this.toPerspective();
  18798. this.toOrthographic();
  18799. }
  18800. };
  18801. /*
  18802. * Uses Focal Length (in mm) to estimate and set FOV
  18803. * 35mm (fullframe) camera is used if frame size is not specified;
  18804. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18805. */
  18806. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18807. if ( frameHeight === undefined ) frameHeight = 24;
  18808. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18809. this.setFov( fov );
  18810. return fov;
  18811. };
  18812. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18813. this.zoom = zoom;
  18814. if ( this.inPerspectiveMode ) {
  18815. this.toPerspective();
  18816. } else {
  18817. this.toOrthographic();
  18818. }
  18819. };
  18820. THREE.CombinedCamera.prototype.toFrontView = function() {
  18821. this.rotation.x = 0;
  18822. this.rotation.y = 0;
  18823. this.rotation.z = 0;
  18824. // should we be modifing the matrix instead?
  18825. this.rotationAutoUpdate = false;
  18826. };
  18827. THREE.CombinedCamera.prototype.toBackView = function() {
  18828. this.rotation.x = 0;
  18829. this.rotation.y = Math.PI;
  18830. this.rotation.z = 0;
  18831. this.rotationAutoUpdate = false;
  18832. };
  18833. THREE.CombinedCamera.prototype.toLeftView = function() {
  18834. this.rotation.x = 0;
  18835. this.rotation.y = - Math.PI / 2;
  18836. this.rotation.z = 0;
  18837. this.rotationAutoUpdate = false;
  18838. };
  18839. THREE.CombinedCamera.prototype.toRightView = function() {
  18840. this.rotation.x = 0;
  18841. this.rotation.y = Math.PI / 2;
  18842. this.rotation.z = 0;
  18843. this.rotationAutoUpdate = false;
  18844. };
  18845. THREE.CombinedCamera.prototype.toTopView = function() {
  18846. this.rotation.x = - Math.PI / 2;
  18847. this.rotation.y = 0;
  18848. this.rotation.z = 0;
  18849. this.rotationAutoUpdate = false;
  18850. };
  18851. THREE.CombinedCamera.prototype.toBottomView = function() {
  18852. this.rotation.x = Math.PI / 2;
  18853. this.rotation.y = 0;
  18854. this.rotation.z = 0;
  18855. this.rotationAutoUpdate = false;
  18856. };
  18857. /**
  18858. * @author mrdoob / http://mrdoob.com/
  18859. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18860. */
  18861. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18862. THREE.Geometry.call( this );
  18863. var scope = this;
  18864. this.width = width;
  18865. this.height = height;
  18866. this.depth = depth;
  18867. this.widthSegments = widthSegments || 1;
  18868. this.heightSegments = heightSegments || 1;
  18869. this.depthSegments = depthSegments || 1;
  18870. var width_half = this.width / 2;
  18871. var height_half = this.height / 2;
  18872. var depth_half = this.depth / 2;
  18873. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18874. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18875. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18876. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18877. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18878. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18879. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18880. var w, ix, iy,
  18881. gridX = scope.widthSegments,
  18882. gridY = scope.heightSegments,
  18883. width_half = width / 2,
  18884. height_half = height / 2,
  18885. offset = scope.vertices.length;
  18886. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18887. w = 'z';
  18888. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18889. w = 'y';
  18890. gridY = scope.depthSegments;
  18891. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18892. w = 'x';
  18893. gridX = scope.depthSegments;
  18894. }
  18895. var gridX1 = gridX + 1,
  18896. gridY1 = gridY + 1,
  18897. segment_width = width / gridX,
  18898. segment_height = height / gridY,
  18899. normal = new THREE.Vector3();
  18900. normal[ w ] = depth > 0 ? 1 : - 1;
  18901. for ( iy = 0; iy < gridY1; iy ++ ) {
  18902. for ( ix = 0; ix < gridX1; ix ++ ) {
  18903. var vector = new THREE.Vector3();
  18904. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18905. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18906. vector[ w ] = depth;
  18907. scope.vertices.push( vector );
  18908. }
  18909. }
  18910. for ( iy = 0; iy < gridY; iy++ ) {
  18911. for ( ix = 0; ix < gridX; ix++ ) {
  18912. var a = ix + gridX1 * iy;
  18913. var b = ix + gridX1 * ( iy + 1 );
  18914. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18915. var d = ( ix + 1 ) + gridX1 * iy;
  18916. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  18917. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  18918. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  18919. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  18920. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  18921. face.normal.copy( normal );
  18922. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18923. face.materialIndex = materialIndex;
  18924. scope.faces.push( face );
  18925. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  18926. face = new THREE.Face3( b + offset, c + offset, d + offset );
  18927. face.normal.copy( normal );
  18928. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18929. face.materialIndex = materialIndex;
  18930. scope.faces.push( face );
  18931. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  18932. }
  18933. }
  18934. }
  18935. this.computeCentroids();
  18936. this.mergeVertices();
  18937. };
  18938. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18939. /**
  18940. * @author mrdoob / http://mrdoob.com/
  18941. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18942. */
  18943. THREE.BoxGeometry2 = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18944. THREE.Geometry2.call( this );
  18945. var scope = this;
  18946. this.width = width;
  18947. this.height = height;
  18948. this.depth = depth;
  18949. this.widthSegments = widthSegments || 1;
  18950. this.heightSegments = heightSegments || 1;
  18951. this.depthSegments = depthSegments || 1;
  18952. var width_half = this.width / 2;
  18953. var height_half = this.height / 2;
  18954. var depth_half = this.depth / 2;
  18955. var vector = new THREE.Vector3();
  18956. var vectors = [];
  18957. var vertices = this.vertices;
  18958. var addVertex = function ( a, b, c ) {
  18959. vertices.push( vectors[ a ], vectors[ a + 1 ], vectors[ a + 2 ] );
  18960. vertices.push( vectors[ b ], vectors[ b + 1 ], vectors[ b + 2 ] );
  18961. vertices.push( vectors[ c ], vectors[ c + 1 ], vectors[ c + 2 ] );
  18962. };
  18963. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18964. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18965. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18966. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18967. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18968. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18969. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18970. var w, ix, iy,
  18971. gridX = scope.widthSegments,
  18972. gridY = scope.heightSegments,
  18973. width_half = width / 2,
  18974. height_half = height / 2,
  18975. offset = vectors.length;
  18976. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18977. w = 'z';
  18978. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18979. w = 'y';
  18980. gridY = scope.depthSegments;
  18981. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18982. w = 'x';
  18983. gridX = scope.depthSegments;
  18984. }
  18985. var gridX1 = gridX + 1,
  18986. gridY1 = gridY + 1,
  18987. segment_width = width / gridX,
  18988. segment_height = height / gridY,
  18989. normal = new THREE.Vector3();
  18990. normal[ w ] = depth > 0 ? 1 : - 1;
  18991. for ( iy = 0; iy < gridY1; iy ++ ) {
  18992. for ( ix = 0; ix < gridX1; ix ++ ) {
  18993. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18994. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18995. vector[ w ] = depth;
  18996. vectors.push( vector.x, vector.y, vector.z );
  18997. }
  18998. }
  18999. for ( iy = 0; iy < gridY; iy++ ) {
  19000. for ( ix = 0; ix < gridX; ix++ ) {
  19001. var a = ix + gridX1 * iy;
  19002. var b = ix + gridX1 * ( iy + 1 );
  19003. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  19004. var d = ( ix + 1 ) + gridX1 * iy;
  19005. addVertex( a * 3 + offset, b * 3 + offset, d * 3 + offset );
  19006. addVertex( b * 3 + offset, c * 3 + offset, d * 3 + offset );
  19007. }
  19008. }
  19009. }
  19010. this.vertices = new Float32Array( vertices );
  19011. };
  19012. THREE.BoxGeometry2.prototype = Object.create( THREE.Geometry2.prototype );
  19013. /**
  19014. * @author hughes
  19015. */
  19016. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  19017. THREE.Geometry.call( this );
  19018. this.radius = radius = radius || 50;
  19019. this.segments = segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  19020. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19021. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19022. var i, uvs = [],
  19023. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  19024. this.vertices.push(center);
  19025. uvs.push( centerUV );
  19026. for ( i = 0; i <= segments; i ++ ) {
  19027. var vertex = new THREE.Vector3();
  19028. var segment = thetaStart + i / segments * thetaLength;
  19029. vertex.x = radius * Math.cos( segment );
  19030. vertex.y = radius * Math.sin( segment );
  19031. this.vertices.push( vertex );
  19032. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  19033. }
  19034. var n = new THREE.Vector3( 0, 0, 1 );
  19035. for ( i = 1; i <= segments; i ++ ) {
  19036. var v1 = i;
  19037. var v2 = i + 1 ;
  19038. var v3 = 0;
  19039. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19040. this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] );
  19041. }
  19042. this.computeCentroids();
  19043. this.computeFaceNormals();
  19044. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19045. };
  19046. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19047. // DEPRECATED
  19048. THREE.CubeGeometry = THREE.BoxGeometry;
  19049. /**
  19050. * @author mrdoob / http://mrdoob.com/
  19051. */
  19052. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  19053. THREE.Geometry.call( this );
  19054. this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20;
  19055. this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  19056. this.height = height = height !== undefined ? height : 100;
  19057. this.radialSegments = radialSegments = radialSegments || 8;
  19058. this.heightSegments = heightSegments = heightSegments || 1;
  19059. this.openEnded = openEnded = openEnded !== undefined ? openEnded : false;
  19060. var heightHalf = height / 2;
  19061. var x, y, vertices = [], uvs = [];
  19062. for ( y = 0; y <= heightSegments; y ++ ) {
  19063. var verticesRow = [];
  19064. var uvsRow = [];
  19065. var v = y / heightSegments;
  19066. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19067. for ( x = 0; x <= radialSegments; x ++ ) {
  19068. var u = x / radialSegments;
  19069. var vertex = new THREE.Vector3();
  19070. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  19071. vertex.y = - v * height + heightHalf;
  19072. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  19073. this.vertices.push( vertex );
  19074. verticesRow.push( this.vertices.length - 1 );
  19075. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19076. }
  19077. vertices.push( verticesRow );
  19078. uvs.push( uvsRow );
  19079. }
  19080. var tanTheta = ( radiusBottom - radiusTop ) / height;
  19081. var na, nb;
  19082. for ( x = 0; x < radialSegments; x ++ ) {
  19083. if ( radiusTop !== 0 ) {
  19084. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  19085. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  19086. } else {
  19087. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  19088. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  19089. }
  19090. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  19091. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  19092. for ( y = 0; y < heightSegments; y ++ ) {
  19093. var v1 = vertices[ y ][ x ];
  19094. var v2 = vertices[ y + 1 ][ x ];
  19095. var v3 = vertices[ y + 1 ][ x + 1 ];
  19096. var v4 = vertices[ y ][ x + 1 ];
  19097. var n1 = na.clone();
  19098. var n2 = na.clone();
  19099. var n3 = nb.clone();
  19100. var n4 = nb.clone();
  19101. var uv1 = uvs[ y ][ x ].clone();
  19102. var uv2 = uvs[ y + 1 ][ x ].clone();
  19103. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  19104. var uv4 = uvs[ y ][ x + 1 ].clone();
  19105. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19106. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19107. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19108. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19109. }
  19110. }
  19111. // top cap
  19112. if ( openEnded === false && radiusTop > 0 ) {
  19113. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  19114. for ( x = 0; x < radialSegments; x ++ ) {
  19115. var v1 = vertices[ 0 ][ x ];
  19116. var v2 = vertices[ 0 ][ x + 1 ];
  19117. var v3 = this.vertices.length - 1;
  19118. var n1 = new THREE.Vector3( 0, 1, 0 );
  19119. var n2 = new THREE.Vector3( 0, 1, 0 );
  19120. var n3 = new THREE.Vector3( 0, 1, 0 );
  19121. var uv1 = uvs[ 0 ][ x ].clone();
  19122. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  19123. var uv3 = new THREE.Vector2( uv2.x, 0 );
  19124. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19125. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19126. }
  19127. }
  19128. // bottom cap
  19129. if ( openEnded === false && radiusBottom > 0 ) {
  19130. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  19131. for ( x = 0; x < radialSegments; x ++ ) {
  19132. var v1 = vertices[ y ][ x + 1 ];
  19133. var v2 = vertices[ y ][ x ];
  19134. var v3 = this.vertices.length - 1;
  19135. var n1 = new THREE.Vector3( 0, - 1, 0 );
  19136. var n2 = new THREE.Vector3( 0, - 1, 0 );
  19137. var n3 = new THREE.Vector3( 0, - 1, 0 );
  19138. var uv1 = uvs[ y ][ x + 1 ].clone();
  19139. var uv2 = uvs[ y ][ x ].clone();
  19140. var uv3 = new THREE.Vector2( uv2.x, 1 );
  19141. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19142. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19143. }
  19144. }
  19145. this.computeCentroids();
  19146. this.computeFaceNormals();
  19147. }
  19148. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19149. /**
  19150. * @author zz85 / http://www.lab4games.net/zz85/blog
  19151. *
  19152. * Creates extruded geometry from a path shape.
  19153. *
  19154. * parameters = {
  19155. *
  19156. * curveSegments: <int>, // number of points on the curves
  19157. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  19158. * amount: <int>, // Depth to extrude the shape
  19159. *
  19160. * bevelEnabled: <bool>, // turn on bevel
  19161. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19162. * bevelSize: <float>, // how far from shape outline is bevel
  19163. * bevelSegments: <int>, // number of bevel layers
  19164. *
  19165. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  19166. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  19167. *
  19168. * material: <int> // material index for front and back faces
  19169. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  19170. * uvGenerator: <Object> // object that provides UV generator functions
  19171. *
  19172. * }
  19173. **/
  19174. THREE.ExtrudeGeometry = function ( shapes, options ) {
  19175. if ( typeof( shapes ) === "undefined" ) {
  19176. shapes = [];
  19177. return;
  19178. }
  19179. THREE.Geometry.call( this );
  19180. shapes = shapes instanceof Array ? shapes : [ shapes ];
  19181. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19182. this.addShapeList( shapes, options );
  19183. this.computeCentroids();
  19184. this.computeFaceNormals();
  19185. // can't really use automatic vertex normals
  19186. // as then front and back sides get smoothed too
  19187. // should do separate smoothing just for sides
  19188. //this.computeVertexNormals();
  19189. //console.log( "took", ( Date.now() - startTime ) );
  19190. };
  19191. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19192. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19193. var sl = shapes.length;
  19194. for ( var s = 0; s < sl; s ++ ) {
  19195. var shape = shapes[ s ];
  19196. this.addShape( shape, options );
  19197. }
  19198. };
  19199. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  19200. var amount = options.amount !== undefined ? options.amount : 100;
  19201. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  19202. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  19203. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19204. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  19205. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19206. var steps = options.steps !== undefined ? options.steps : 1;
  19207. var extrudePath = options.extrudePath;
  19208. var extrudePts, extrudeByPath = false;
  19209. var material = options.material;
  19210. var extrudeMaterial = options.extrudeMaterial;
  19211. // Use default WorldUVGenerator if no UV generators are specified.
  19212. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  19213. var shapebb = this.shapebb;
  19214. //shapebb = shape.getBoundingBox();
  19215. var splineTube, binormal, normal, position2;
  19216. if ( extrudePath ) {
  19217. extrudePts = extrudePath.getSpacedPoints( steps );
  19218. extrudeByPath = true;
  19219. bevelEnabled = false; // bevels not supported for path extrusion
  19220. // SETUP TNB variables
  19221. // Reuse TNB from TubeGeomtry for now.
  19222. // TODO1 - have a .isClosed in spline?
  19223. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  19224. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19225. binormal = new THREE.Vector3();
  19226. normal = new THREE.Vector3();
  19227. position2 = new THREE.Vector3();
  19228. }
  19229. // Safeguards if bevels are not enabled
  19230. if ( ! bevelEnabled ) {
  19231. bevelSegments = 0;
  19232. bevelThickness = 0;
  19233. bevelSize = 0;
  19234. }
  19235. // Variables initalization
  19236. var ahole, h, hl; // looping of holes
  19237. var scope = this;
  19238. var bevelPoints = [];
  19239. var shapesOffset = this.vertices.length;
  19240. var shapePoints = shape.extractPoints( curveSegments );
  19241. var vertices = shapePoints.shape;
  19242. var holes = shapePoints.holes;
  19243. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  19244. if ( reverse ) {
  19245. vertices = vertices.reverse();
  19246. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19247. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19248. ahole = holes[ h ];
  19249. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  19250. holes[ h ] = ahole.reverse();
  19251. }
  19252. }
  19253. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  19254. }
  19255. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  19256. /* Vertices */
  19257. var contour = vertices; // vertices has all points but contour has only points of circumference
  19258. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19259. ahole = holes[ h ];
  19260. vertices = vertices.concat( ahole );
  19261. }
  19262. function scalePt2 ( pt, vec, size ) {
  19263. if ( !vec ) console.log( "die" );
  19264. return vec.clone().multiplyScalar( size ).add( pt );
  19265. }
  19266. var b, bs, t, z,
  19267. vert, vlen = vertices.length,
  19268. face, flen = faces.length,
  19269. cont, clen = contour.length;
  19270. // Find directions for point movement
  19271. var RAD_TO_DEGREES = 180 / Math.PI;
  19272. function getBevelVec( inPt, inPrev, inNext ) {
  19273. var EPSILON = 0.0000000001;
  19274. var sign = THREE.Math.sign;
  19275. // computes for inPt the corresponding point inPt' on a new contour
  19276. // shiftet by 1 unit (length of normalized vector) to the left
  19277. // if we walk along contour clockwise, this new contour is outside the old one
  19278. //
  19279. // inPt' is the intersection of the two lines parallel to the two
  19280. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19281. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  19282. // good reading for geometry algorithms (here: line-line intersection)
  19283. // http://geomalgorithms.com/a05-_intersect-1.html
  19284. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  19285. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  19286. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  19287. // check for colinear edges
  19288. var colinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19289. if ( Math.abs( colinear0 ) > EPSILON ) { // not colinear
  19290. // length of vectors for normalizing
  19291. var v_prev_len = Math.sqrt( v_prev_lensq );
  19292. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  19293. // shift adjacent points by unit vectors to the left
  19294. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  19295. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  19296. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  19297. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  19298. // scaling factor for v_prev to intersection point
  19299. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  19300. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  19301. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19302. // vector from inPt to intersection point
  19303. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  19304. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  19305. // Don't normalize!, otherwise sharp corners become ugly
  19306. // but prevent crazy spikes
  19307. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y )
  19308. if ( v_trans_lensq <= 2 ) {
  19309. return new THREE.Vector2( v_trans_x, v_trans_y );
  19310. } else {
  19311. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  19312. }
  19313. } else { // handle special case of colinear edges
  19314. var direction_eq = false; // assumes: opposite
  19315. if ( v_prev_x > EPSILON ) {
  19316. if ( v_next_x > EPSILON ) { direction_eq = true; }
  19317. } else {
  19318. if ( v_prev_x < -EPSILON ) {
  19319. if ( v_next_x < -EPSILON ) { direction_eq = true; }
  19320. } else {
  19321. if ( sign(v_prev_y) == sign(v_next_y) ) { direction_eq = true; }
  19322. }
  19323. }
  19324. if ( direction_eq ) {
  19325. // console.log("Warning: lines are a straight sequence");
  19326. v_trans_x = -v_prev_y;
  19327. v_trans_y = v_prev_x;
  19328. shrink_by = Math.sqrt( v_prev_lensq );
  19329. } else {
  19330. // console.log("Warning: lines are a straight spike");
  19331. v_trans_x = v_prev_x;
  19332. v_trans_y = v_prev_y;
  19333. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  19334. }
  19335. }
  19336. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  19337. }
  19338. var contourMovements = [];
  19339. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19340. if ( j === il ) j = 0;
  19341. if ( k === il ) k = 0;
  19342. // (j)---(i)---(k)
  19343. // console.log('i,j,k', i, j , k)
  19344. var pt_i = contour[ i ];
  19345. var pt_j = contour[ j ];
  19346. var pt_k = contour[ k ];
  19347. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19348. }
  19349. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19350. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19351. ahole = holes[ h ];
  19352. oneHoleMovements = [];
  19353. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19354. if ( j === il ) j = 0;
  19355. if ( k === il ) k = 0;
  19356. // (j)---(i)---(k)
  19357. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19358. }
  19359. holesMovements.push( oneHoleMovements );
  19360. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19361. }
  19362. // Loop bevelSegments, 1 for the front, 1 for the back
  19363. for ( b = 0; b < bevelSegments; b ++ ) {
  19364. //for ( b = bevelSegments; b > 0; b -- ) {
  19365. t = b / bevelSegments;
  19366. z = bevelThickness * ( 1 - t );
  19367. //z = bevelThickness * t;
  19368. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  19369. //bs = bevelSize * t ; // linear
  19370. // contract shape
  19371. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19372. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19373. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  19374. v( vert.x, vert.y, - z );
  19375. }
  19376. // expand holes
  19377. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19378. ahole = holes[ h ];
  19379. oneHoleMovements = holesMovements[ h ];
  19380. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19381. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19382. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  19383. v( vert.x, vert.y, -z );
  19384. }
  19385. }
  19386. }
  19387. bs = bevelSize;
  19388. // Back facing vertices
  19389. for ( i = 0; i < vlen; i ++ ) {
  19390. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19391. if ( !extrudeByPath ) {
  19392. v( vert.x, vert.y, 0 );
  19393. } else {
  19394. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19395. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19396. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19397. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  19398. v( position2.x, position2.y, position2.z );
  19399. }
  19400. }
  19401. // Add stepped vertices...
  19402. // Including front facing vertices
  19403. var s;
  19404. for ( s = 1; s <= steps; s ++ ) {
  19405. for ( i = 0; i < vlen; i ++ ) {
  19406. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19407. if ( !extrudeByPath ) {
  19408. v( vert.x, vert.y, amount / steps * s );
  19409. } else {
  19410. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19411. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19412. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19413. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19414. v( position2.x, position2.y, position2.z );
  19415. }
  19416. }
  19417. }
  19418. // Add bevel segments planes
  19419. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19420. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19421. t = b / bevelSegments;
  19422. z = bevelThickness * ( 1 - t );
  19423. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19424. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19425. // contract shape
  19426. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19427. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19428. v( vert.x, vert.y, amount + z );
  19429. }
  19430. // expand holes
  19431. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19432. ahole = holes[ h ];
  19433. oneHoleMovements = holesMovements[ h ];
  19434. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19435. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19436. if ( !extrudeByPath ) {
  19437. v( vert.x, vert.y, amount + z );
  19438. } else {
  19439. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19440. }
  19441. }
  19442. }
  19443. }
  19444. /* Faces */
  19445. // Top and bottom faces
  19446. buildLidFaces();
  19447. // Sides faces
  19448. buildSideFaces();
  19449. ///// Internal functions
  19450. function buildLidFaces() {
  19451. if ( bevelEnabled ) {
  19452. var layer = 0 ; // steps + 1
  19453. var offset = vlen * layer;
  19454. // Bottom faces
  19455. for ( i = 0; i < flen; i ++ ) {
  19456. face = faces[ i ];
  19457. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19458. }
  19459. layer = steps + bevelSegments * 2;
  19460. offset = vlen * layer;
  19461. // Top faces
  19462. for ( i = 0; i < flen; i ++ ) {
  19463. face = faces[ i ];
  19464. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19465. }
  19466. } else {
  19467. // Bottom faces
  19468. for ( i = 0; i < flen; i++ ) {
  19469. face = faces[ i ];
  19470. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19471. }
  19472. // Top faces
  19473. for ( i = 0; i < flen; i ++ ) {
  19474. face = faces[ i ];
  19475. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19476. }
  19477. }
  19478. }
  19479. // Create faces for the z-sides of the shape
  19480. function buildSideFaces() {
  19481. var layeroffset = 0;
  19482. sidewalls( contour, layeroffset );
  19483. layeroffset += contour.length;
  19484. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19485. ahole = holes[ h ];
  19486. sidewalls( ahole, layeroffset );
  19487. //, true
  19488. layeroffset += ahole.length;
  19489. }
  19490. }
  19491. function sidewalls( contour, layeroffset ) {
  19492. var j, k;
  19493. i = contour.length;
  19494. while ( --i >= 0 ) {
  19495. j = i;
  19496. k = i - 1;
  19497. if ( k < 0 ) k = contour.length - 1;
  19498. //console.log('b', i,j, i-1, k,vertices.length);
  19499. var s = 0, sl = steps + bevelSegments * 2;
  19500. for ( s = 0; s < sl; s ++ ) {
  19501. var slen1 = vlen * s;
  19502. var slen2 = vlen * ( s + 1 );
  19503. var a = layeroffset + j + slen1,
  19504. b = layeroffset + k + slen1,
  19505. c = layeroffset + k + slen2,
  19506. d = layeroffset + j + slen2;
  19507. f4( a, b, c, d, contour, s, sl, j, k );
  19508. }
  19509. }
  19510. }
  19511. function v( x, y, z ) {
  19512. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19513. }
  19514. function f3( a, b, c, isBottom ) {
  19515. a += shapesOffset;
  19516. b += shapesOffset;
  19517. c += shapesOffset;
  19518. // normal, color, material
  19519. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19520. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19521. scope.faceVertexUvs[ 0 ].push( uvs );
  19522. }
  19523. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19524. a += shapesOffset;
  19525. b += shapesOffset;
  19526. c += shapesOffset;
  19527. d += shapesOffset;
  19528. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  19529. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  19530. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19531. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19532. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  19533. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  19534. }
  19535. };
  19536. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19537. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19538. var ax = geometry.vertices[ indexA ].x,
  19539. ay = geometry.vertices[ indexA ].y,
  19540. bx = geometry.vertices[ indexB ].x,
  19541. by = geometry.vertices[ indexB ].y,
  19542. cx = geometry.vertices[ indexC ].x,
  19543. cy = geometry.vertices[ indexC ].y;
  19544. return [
  19545. new THREE.Vector2( ax, ay ),
  19546. new THREE.Vector2( bx, by ),
  19547. new THREE.Vector2( cx, cy )
  19548. ];
  19549. },
  19550. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19551. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19552. },
  19553. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19554. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19555. contourIndex1, contourIndex2 ) {
  19556. var ax = geometry.vertices[ indexA ].x,
  19557. ay = geometry.vertices[ indexA ].y,
  19558. az = geometry.vertices[ indexA ].z,
  19559. bx = geometry.vertices[ indexB ].x,
  19560. by = geometry.vertices[ indexB ].y,
  19561. bz = geometry.vertices[ indexB ].z,
  19562. cx = geometry.vertices[ indexC ].x,
  19563. cy = geometry.vertices[ indexC ].y,
  19564. cz = geometry.vertices[ indexC ].z,
  19565. dx = geometry.vertices[ indexD ].x,
  19566. dy = geometry.vertices[ indexD ].y,
  19567. dz = geometry.vertices[ indexD ].z;
  19568. if ( Math.abs( ay - by ) < 0.01 ) {
  19569. return [
  19570. new THREE.Vector2( ax, 1 - az ),
  19571. new THREE.Vector2( bx, 1 - bz ),
  19572. new THREE.Vector2( cx, 1 - cz ),
  19573. new THREE.Vector2( dx, 1 - dz )
  19574. ];
  19575. } else {
  19576. return [
  19577. new THREE.Vector2( ay, 1 - az ),
  19578. new THREE.Vector2( by, 1 - bz ),
  19579. new THREE.Vector2( cy, 1 - cz ),
  19580. new THREE.Vector2( dy, 1 - dz )
  19581. ];
  19582. }
  19583. }
  19584. };
  19585. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19586. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19587. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19588. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19589. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19590. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19591. /**
  19592. * @author jonobr1 / http://jonobr1.com
  19593. *
  19594. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19595. * ExtrudeGeometry.
  19596. *
  19597. * parameters = {
  19598. *
  19599. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19600. *
  19601. * material: <int> // material index for front and back faces
  19602. * uvGenerator: <Object> // object that provides UV generator functions
  19603. *
  19604. * }
  19605. **/
  19606. THREE.ShapeGeometry = function ( shapes, options ) {
  19607. THREE.Geometry.call( this );
  19608. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19609. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19610. this.addShapeList( shapes, options );
  19611. this.computeCentroids();
  19612. this.computeFaceNormals();
  19613. };
  19614. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19615. /**
  19616. * Add an array of shapes to THREE.ShapeGeometry.
  19617. */
  19618. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19619. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19620. this.addShape( shapes[ i ], options );
  19621. }
  19622. return this;
  19623. };
  19624. /**
  19625. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19626. */
  19627. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19628. if ( options === undefined ) options = {};
  19629. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19630. var material = options.material;
  19631. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19632. var shapebb = this.shapebb;
  19633. //
  19634. var i, l, hole, s;
  19635. var shapesOffset = this.vertices.length;
  19636. var shapePoints = shape.extractPoints( curveSegments );
  19637. var vertices = shapePoints.shape;
  19638. var holes = shapePoints.holes;
  19639. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19640. if ( reverse ) {
  19641. vertices = vertices.reverse();
  19642. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19643. for ( i = 0, l = holes.length; i < l; i++ ) {
  19644. hole = holes[ i ];
  19645. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19646. holes[ i ] = hole.reverse();
  19647. }
  19648. }
  19649. reverse = false;
  19650. }
  19651. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19652. // Vertices
  19653. var contour = vertices;
  19654. for ( i = 0, l = holes.length; i < l; i++ ) {
  19655. hole = holes[ i ];
  19656. vertices = vertices.concat( hole );
  19657. }
  19658. //
  19659. var vert, vlen = vertices.length;
  19660. var face, flen = faces.length;
  19661. var cont, clen = contour.length;
  19662. for ( i = 0; i < vlen; i++ ) {
  19663. vert = vertices[ i ];
  19664. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19665. }
  19666. for ( i = 0; i < flen; i++ ) {
  19667. face = faces[ i ];
  19668. var a = face[ 0 ] + shapesOffset;
  19669. var b = face[ 1 ] + shapesOffset;
  19670. var c = face[ 2 ] + shapesOffset;
  19671. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19672. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19673. }
  19674. };
  19675. /**
  19676. * @author astrodud / http://astrodud.isgreat.org/
  19677. * @author zz85 / https://github.com/zz85
  19678. * @author bhouston / http://exocortex.com
  19679. */
  19680. // points - to create a closed torus, one must use a set of points
  19681. // like so: [ a, b, c, d, a ], see first is the same as last.
  19682. // segments - the number of circumference segments to create
  19683. // phiStart - the starting radian
  19684. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19685. // 2*pi is a closed lathe, less than 2PI is a portion.
  19686. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19687. THREE.Geometry.call( this );
  19688. segments = segments || 12;
  19689. phiStart = phiStart || 0;
  19690. phiLength = phiLength || 2 * Math.PI;
  19691. var inversePointLength = 1.0 / ( points.length - 1 );
  19692. var inverseSegments = 1.0 / segments;
  19693. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19694. var phi = phiStart + i * inverseSegments * phiLength;
  19695. var c = Math.cos( phi ),
  19696. s = Math.sin( phi );
  19697. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19698. var pt = points[ j ];
  19699. var vertex = new THREE.Vector3();
  19700. vertex.x = c * pt.x - s * pt.y;
  19701. vertex.y = s * pt.x + c * pt.y;
  19702. vertex.z = pt.z;
  19703. this.vertices.push( vertex );
  19704. }
  19705. }
  19706. var np = points.length;
  19707. for ( var i = 0, il = segments; i < il; i ++ ) {
  19708. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19709. var base = j + np * i;
  19710. var a = base;
  19711. var b = base + np;
  19712. var c = base + 1 + np;
  19713. var d = base + 1;
  19714. var u0 = i * inverseSegments;
  19715. var v0 = j * inversePointLength;
  19716. var u1 = u0 + inverseSegments;
  19717. var v1 = v0 + inversePointLength;
  19718. this.faces.push( new THREE.Face3( a, b, d ) );
  19719. this.faceVertexUvs[ 0 ].push( [
  19720. new THREE.Vector2( u0, v0 ),
  19721. new THREE.Vector2( u1, v0 ),
  19722. new THREE.Vector2( u0, v1 )
  19723. ] );
  19724. this.faces.push( new THREE.Face3( b, c, d ) );
  19725. this.faceVertexUvs[ 0 ].push( [
  19726. new THREE.Vector2( u1, v0 ),
  19727. new THREE.Vector2( u1, v1 ),
  19728. new THREE.Vector2( u0, v1 )
  19729. ] );
  19730. }
  19731. }
  19732. this.mergeVertices();
  19733. this.computeCentroids();
  19734. this.computeFaceNormals();
  19735. this.computeVertexNormals();
  19736. };
  19737. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19738. /**
  19739. * @author mrdoob / http://mrdoob.com/
  19740. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19741. */
  19742. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19743. THREE.Geometry.call( this );
  19744. this.width = width;
  19745. this.height = height;
  19746. this.widthSegments = widthSegments || 1;
  19747. this.heightSegments = heightSegments || 1;
  19748. var ix, iz;
  19749. var width_half = width / 2;
  19750. var height_half = height / 2;
  19751. var gridX = this.widthSegments;
  19752. var gridZ = this.heightSegments;
  19753. var gridX1 = gridX + 1;
  19754. var gridZ1 = gridZ + 1;
  19755. var segment_width = this.width / gridX;
  19756. var segment_height = this.height / gridZ;
  19757. var normal = new THREE.Vector3( 0, 0, 1 );
  19758. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19759. for ( ix = 0; ix < gridX1; ix ++ ) {
  19760. var x = ix * segment_width - width_half;
  19761. var y = iz * segment_height - height_half;
  19762. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19763. }
  19764. }
  19765. for ( iz = 0; iz < gridZ; iz ++ ) {
  19766. for ( ix = 0; ix < gridX; ix ++ ) {
  19767. var a = ix + gridX1 * iz;
  19768. var b = ix + gridX1 * ( iz + 1 );
  19769. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19770. var d = ( ix + 1 ) + gridX1 * iz;
  19771. var uva = new THREE.Vector2( ix / gridX, 1 - iz / gridZ );
  19772. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ );
  19773. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ );
  19774. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ );
  19775. var face = new THREE.Face3( a, b, d );
  19776. face.normal.copy( normal );
  19777. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19778. this.faces.push( face );
  19779. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19780. face = new THREE.Face3( b, c, d );
  19781. face.normal.copy( normal );
  19782. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19783. this.faces.push( face );
  19784. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19785. }
  19786. }
  19787. this.computeCentroids();
  19788. };
  19789. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19790. /**
  19791. * @author mrdoob / http://mrdoob.com/
  19792. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19793. */
  19794. THREE.PlaneGeometry2 = function ( width, height, widthSegments, heightSegments ) {
  19795. THREE.Geometry2.call( this, ( widthSegments * heightSegments ) * 2 * 3 );
  19796. var vertices = this.vertices;
  19797. var normals = this.normals;
  19798. var uvs = this.uvs;
  19799. this.width = width;
  19800. this.height = height;
  19801. this.widthSegments = widthSegments || 1;
  19802. this.heightSegments = heightSegments || 1;
  19803. var widthHalf = width / 2;
  19804. var heightHalf = height / 2;
  19805. var gridX = this.widthSegments;
  19806. var gridY = this.heightSegments;
  19807. var segmentWidth = this.width / gridX;
  19808. var segmentHeight = this.height / gridY;
  19809. var offset = 0;
  19810. var normal = new THREE.Vector3( 0, 0, 1 );
  19811. for ( var iy = 0; iy < gridY; iy ++ ) {
  19812. var y1 = iy * segmentHeight - heightHalf;
  19813. var y2 = ( iy + 1 ) * segmentHeight - heightHalf;
  19814. for ( var ix = 0; ix < gridX; ix ++ ) {
  19815. var x1 = ix * segmentWidth - widthHalf;
  19816. var x2 = ( ix + 1 ) * segmentWidth - widthHalf;
  19817. vertices[ offset ++ ] = x1;
  19818. vertices[ offset ++ ] = y1;
  19819. offset ++;
  19820. vertices[ offset ++ ] = x2;
  19821. vertices[ offset ++ ] = y1;
  19822. offset ++;
  19823. vertices[ offset ++ ] = x1;
  19824. vertices[ offset ++ ] = y2;
  19825. offset ++;
  19826. vertices[ offset ++ ] = x2;
  19827. vertices[ offset ++ ] = y1;
  19828. offset ++;
  19829. vertices[ offset ++ ] = x2;
  19830. vertices[ offset ++ ] = y2;
  19831. offset ++;
  19832. vertices[ offset ++ ] = x1;
  19833. vertices[ offset ++ ] = y2;
  19834. offset ++;
  19835. }
  19836. }
  19837. };
  19838. THREE.PlaneGeometry2.prototype = Object.create( THREE.Geometry2.prototype );
  19839. /**
  19840. * @author Kaleb Murphy
  19841. */
  19842. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19843. THREE.Geometry.call( this );
  19844. innerRadius = innerRadius || 0;
  19845. outerRadius = outerRadius || 50;
  19846. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19847. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19848. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19849. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19850. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19851. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19852. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19853. var vertex = new THREE.Vector3();
  19854. var segment = thetaStart + o / thetaSegments * thetaLength;
  19855. vertex.x = radius * Math.cos( segment );
  19856. vertex.y = radius * Math.sin( segment );
  19857. this.vertices.push( vertex );
  19858. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  19859. }
  19860. radius += radiusStep;
  19861. }
  19862. var n = new THREE.Vector3( 0, 0, 1 );
  19863. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19864. var thetaSegment = i * thetaSegments;
  19865. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19866. var segment = o + thetaSegment;
  19867. var v1 = segment + i;
  19868. var v2 = segment + thetaSegments + i;
  19869. var v3 = segment + thetaSegments + 1 + i;
  19870. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19871. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19872. v1 = segment + i;
  19873. v2 = segment + thetaSegments + 1 + i;
  19874. v3 = segment + 1 + i;
  19875. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19876. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19877. }
  19878. }
  19879. this.computeCentroids();
  19880. this.computeFaceNormals();
  19881. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19882. };
  19883. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19884. /**
  19885. * @author mrdoob / http://mrdoob.com/
  19886. */
  19887. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19888. THREE.Geometry.call( this );
  19889. this.radius = radius = radius || 50;
  19890. this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19891. this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19892. this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0;
  19893. this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19894. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19895. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19896. var x, y, vertices = [], uvs = [];
  19897. for ( y = 0; y <= heightSegments; y ++ ) {
  19898. var verticesRow = [];
  19899. var uvsRow = [];
  19900. for ( x = 0; x <= widthSegments; x ++ ) {
  19901. var u = x / widthSegments;
  19902. var v = y / heightSegments;
  19903. var vertex = new THREE.Vector3();
  19904. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19905. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19906. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19907. this.vertices.push( vertex );
  19908. verticesRow.push( this.vertices.length - 1 );
  19909. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19910. }
  19911. vertices.push( verticesRow );
  19912. uvs.push( uvsRow );
  19913. }
  19914. for ( y = 0; y < this.heightSegments; y ++ ) {
  19915. for ( x = 0; x < this.widthSegments; x ++ ) {
  19916. var v1 = vertices[ y ][ x + 1 ];
  19917. var v2 = vertices[ y ][ x ];
  19918. var v3 = vertices[ y + 1 ][ x ];
  19919. var v4 = vertices[ y + 1 ][ x + 1 ];
  19920. var n1 = this.vertices[ v1 ].clone().normalize();
  19921. var n2 = this.vertices[ v2 ].clone().normalize();
  19922. var n3 = this.vertices[ v3 ].clone().normalize();
  19923. var n4 = this.vertices[ v4 ].clone().normalize();
  19924. var uv1 = uvs[ y ][ x + 1 ].clone();
  19925. var uv2 = uvs[ y ][ x ].clone();
  19926. var uv3 = uvs[ y + 1 ][ x ].clone();
  19927. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19928. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19929. uv1.x = ( uv1.x + uv2.x ) / 2;
  19930. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19931. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19932. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19933. uv3.x = ( uv3.x + uv4.x ) / 2;
  19934. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19935. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19936. } else {
  19937. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19938. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19939. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19940. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19941. }
  19942. }
  19943. }
  19944. this.computeCentroids();
  19945. this.computeFaceNormals();
  19946. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19947. };
  19948. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19949. /**
  19950. * @author zz85 / http://www.lab4games.net/zz85/blog
  19951. * @author alteredq / http://alteredqualia.com/
  19952. *
  19953. * For creating 3D text geometry in three.js
  19954. *
  19955. * Text = 3D Text
  19956. *
  19957. * parameters = {
  19958. * size: <float>, // size of the text
  19959. * height: <float>, // thickness to extrude text
  19960. * curveSegments: <int>, // number of points on the curves
  19961. *
  19962. * font: <string>, // font name
  19963. * weight: <string>, // font weight (normal, bold)
  19964. * style: <string>, // font style (normal, italics)
  19965. *
  19966. * bevelEnabled: <bool>, // turn on bevel
  19967. * bevelThickness: <float>, // how deep into text bevel goes
  19968. * bevelSize: <float>, // how far from text outline is bevel
  19969. * }
  19970. *
  19971. */
  19972. /* Usage Examples
  19973. // TextGeometry wrapper
  19974. var text3d = new TextGeometry( text, options );
  19975. // Complete manner
  19976. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19977. var text3d = new ExtrudeGeometry( textShapes, options );
  19978. */
  19979. THREE.TextGeometry = function ( text, parameters ) {
  19980. parameters = parameters || {};
  19981. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19982. // translate parameters to ExtrudeGeometry API
  19983. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19984. // defaults
  19985. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19986. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19987. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19988. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19989. };
  19990. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19991. /**
  19992. * @author oosmoxiecode
  19993. * @author mrdoob / http://mrdoob.com/
  19994. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19995. */
  19996. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19997. THREE.Geometry.call( this );
  19998. var scope = this;
  19999. this.radius = radius || 100;
  20000. this.tube = tube || 40;
  20001. this.radialSegments = radialSegments || 8;
  20002. this.tubularSegments = tubularSegments || 6;
  20003. this.arc = arc || Math.PI * 2;
  20004. var center = new THREE.Vector3(), uvs = [], normals = [];
  20005. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  20006. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  20007. var u = i / this.tubularSegments * this.arc;
  20008. var v = j / this.radialSegments * Math.PI * 2;
  20009. center.x = this.radius * Math.cos( u );
  20010. center.y = this.radius * Math.sin( u );
  20011. var vertex = new THREE.Vector3();
  20012. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  20013. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  20014. vertex.z = this.tube * Math.sin( v );
  20015. this.vertices.push( vertex );
  20016. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  20017. normals.push( vertex.clone().sub( center ).normalize() );
  20018. }
  20019. }
  20020. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  20021. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  20022. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  20023. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20024. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  20025. var d = ( this.tubularSegments + 1 ) * j + i;
  20026. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  20027. this.faces.push( face );
  20028. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  20029. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  20030. this.faces.push( face );
  20031. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  20032. }
  20033. }
  20034. this.computeCentroids();
  20035. this.computeFaceNormals();
  20036. };
  20037. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20038. /**
  20039. * @author oosmoxiecode
  20040. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20041. */
  20042. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  20043. THREE.Geometry.call( this );
  20044. var scope = this;
  20045. this.radius = radius || 100;
  20046. this.tube = tube || 40;
  20047. this.radialSegments = radialSegments || 64;
  20048. this.tubularSegments = tubularSegments || 8;
  20049. this.p = p || 2;
  20050. this.q = q || 3;
  20051. this.heightScale = heightScale || 1;
  20052. this.grid = new Array( this.radialSegments );
  20053. var tang = new THREE.Vector3();
  20054. var n = new THREE.Vector3();
  20055. var bitan = new THREE.Vector3();
  20056. for ( var i = 0; i < this.radialSegments; ++ i ) {
  20057. this.grid[ i ] = new Array( this.tubularSegments );
  20058. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  20059. var p1 = getPos( u, this.q, this.p, this.radius, this.heightScale );
  20060. var p2 = getPos( u + 0.01, this.q, this.p, this.radius, this.heightScale );
  20061. tang.subVectors( p2, p1 );
  20062. n.addVectors( p2, p1 );
  20063. bitan.crossVectors( tang, n );
  20064. n.crossVectors( bitan, tang );
  20065. bitan.normalize();
  20066. n.normalize();
  20067. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  20068. var v = j / this.tubularSegments * 2 * Math.PI;
  20069. var cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20070. var cy = this.tube * Math.sin( v );
  20071. var pos = new THREE.Vector3();
  20072. pos.x = p1.x + cx * n.x + cy * bitan.x;
  20073. pos.y = p1.y + cx * n.y + cy * bitan.y;
  20074. pos.z = p1.z + cx * n.z + cy * bitan.z;
  20075. this.grid[ i ][ j ] = scope.vertices.push( pos ) - 1;
  20076. }
  20077. }
  20078. for ( var i = 0; i < this.radialSegments; ++ i ) {
  20079. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  20080. var ip = ( i + 1 ) % this.radialSegments;
  20081. var jp = ( j + 1 ) % this.tubularSegments;
  20082. var a = this.grid[ i ][ j ];
  20083. var b = this.grid[ ip ][ j ];
  20084. var c = this.grid[ ip ][ jp ];
  20085. var d = this.grid[ i ][ jp ];
  20086. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  20087. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  20088. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  20089. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  20090. this.faces.push( new THREE.Face3( a, b, d ) );
  20091. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  20092. this.faces.push( new THREE.Face3( b, c, d ) );
  20093. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  20094. }
  20095. }
  20096. this.computeCentroids();
  20097. this.computeFaceNormals();
  20098. this.computeVertexNormals();
  20099. function getPos( u, in_q, in_p, radius, heightScale ) {
  20100. var cu = Math.cos( u );
  20101. var su = Math.sin( u );
  20102. var quOverP = in_q / in_p * u;
  20103. var cs = Math.cos( quOverP );
  20104. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  20105. var ty = radius * ( 2 + cs ) * su * 0.5;
  20106. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  20107. return new THREE.Vector3( tx, ty, tz );
  20108. }
  20109. };
  20110. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20111. /**
  20112. * @author WestLangley / https://github.com/WestLangley
  20113. * @author zz85 / https://github.com/zz85
  20114. * @author miningold / https://github.com/miningold
  20115. *
  20116. * Modified from the TorusKnotGeometry by @oosmoxiecode
  20117. *
  20118. * Creates a tube which extrudes along a 3d spline
  20119. *
  20120. * Uses parallel transport frames as described in
  20121. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20122. */
  20123. THREE.TubeGeometry = function( path, segments, radius, radialSegments, closed ) {
  20124. THREE.Geometry.call( this );
  20125. this.path = path;
  20126. this.segments = segments || 64;
  20127. this.radius = radius || 1;
  20128. this.radialSegments = radialSegments || 8;
  20129. this.closed = closed || false;
  20130. this.grid = [];
  20131. var scope = this,
  20132. tangent,
  20133. normal,
  20134. binormal,
  20135. numpoints = this.segments + 1,
  20136. x, y, z,
  20137. tx, ty, tz,
  20138. u, v,
  20139. cx, cy,
  20140. pos, pos2 = new THREE.Vector3(),
  20141. i, j,
  20142. ip, jp,
  20143. a, b, c, d,
  20144. uva, uvb, uvc, uvd;
  20145. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  20146. tangents = frames.tangents,
  20147. normals = frames.normals,
  20148. binormals = frames.binormals;
  20149. // proxy internals
  20150. this.tangents = tangents;
  20151. this.normals = normals;
  20152. this.binormals = binormals;
  20153. function vert( x, y, z ) {
  20154. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  20155. }
  20156. // consruct the grid
  20157. for ( i = 0; i < numpoints; i++ ) {
  20158. this.grid[ i ] = [];
  20159. u = i / ( numpoints - 1 );
  20160. pos = path.getPointAt( u );
  20161. tangent = tangents[ i ];
  20162. normal = normals[ i ];
  20163. binormal = binormals[ i ];
  20164. for ( j = 0; j < this.radialSegments; j++ ) {
  20165. v = j / this.radialSegments * 2 * Math.PI;
  20166. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20167. cy = this.radius * Math.sin( v );
  20168. pos2.copy( pos );
  20169. pos2.x += cx * normal.x + cy * binormal.x;
  20170. pos2.y += cx * normal.y + cy * binormal.y;
  20171. pos2.z += cx * normal.z + cy * binormal.z;
  20172. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  20173. }
  20174. }
  20175. // construct the mesh
  20176. for ( i = 0; i < this.segments; i++ ) {
  20177. for ( j = 0; j < this.radialSegments; j++ ) {
  20178. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  20179. jp = (j + 1) % this.radialSegments;
  20180. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  20181. b = this.grid[ ip ][ j ];
  20182. c = this.grid[ ip ][ jp ];
  20183. d = this.grid[ i ][ jp ];
  20184. uva = new THREE.Vector2( i / this.segments, j / this.radialSegments );
  20185. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radialSegments );
  20186. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radialSegments );
  20187. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radialSegments );
  20188. this.faces.push( new THREE.Face3( a, b, d ) );
  20189. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  20190. this.faces.push( new THREE.Face3( b, c, d ) );
  20191. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  20192. }
  20193. }
  20194. this.computeCentroids();
  20195. this.computeFaceNormals();
  20196. this.computeVertexNormals();
  20197. };
  20198. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20199. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  20200. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  20201. var tangent = new THREE.Vector3(),
  20202. normal = new THREE.Vector3(),
  20203. binormal = new THREE.Vector3(),
  20204. tangents = [],
  20205. normals = [],
  20206. binormals = [],
  20207. vec = new THREE.Vector3(),
  20208. mat = new THREE.Matrix4(),
  20209. numpoints = segments + 1,
  20210. theta,
  20211. epsilon = 0.0001,
  20212. smallest,
  20213. tx, ty, tz,
  20214. i, u, v;
  20215. // expose internals
  20216. this.tangents = tangents;
  20217. this.normals = normals;
  20218. this.binormals = binormals;
  20219. // compute the tangent vectors for each segment on the path
  20220. for ( i = 0; i < numpoints; i++ ) {
  20221. u = i / ( numpoints - 1 );
  20222. tangents[ i ] = path.getTangentAt( u );
  20223. tangents[ i ].normalize();
  20224. }
  20225. initialNormal3();
  20226. function initialNormal1(lastBinormal) {
  20227. // fixed start binormal. Has dangers of 0 vectors
  20228. normals[ 0 ] = new THREE.Vector3();
  20229. binormals[ 0 ] = new THREE.Vector3();
  20230. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  20231. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  20232. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20233. }
  20234. function initialNormal2() {
  20235. // This uses the Frenet-Serret formula for deriving binormal
  20236. var t2 = path.getTangentAt( epsilon );
  20237. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  20238. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  20239. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  20240. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20241. }
  20242. function initialNormal3() {
  20243. // select an initial normal vector perpenicular to the first tangent vector,
  20244. // and in the direction of the smallest tangent xyz component
  20245. normals[ 0 ] = new THREE.Vector3();
  20246. binormals[ 0 ] = new THREE.Vector3();
  20247. smallest = Number.MAX_VALUE;
  20248. tx = Math.abs( tangents[ 0 ].x );
  20249. ty = Math.abs( tangents[ 0 ].y );
  20250. tz = Math.abs( tangents[ 0 ].z );
  20251. if ( tx <= smallest ) {
  20252. smallest = tx;
  20253. normal.set( 1, 0, 0 );
  20254. }
  20255. if ( ty <= smallest ) {
  20256. smallest = ty;
  20257. normal.set( 0, 1, 0 );
  20258. }
  20259. if ( tz <= smallest ) {
  20260. normal.set( 0, 0, 1 );
  20261. }
  20262. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20263. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20264. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20265. }
  20266. // compute the slowly-varying normal and binormal vectors for each segment on the path
  20267. for ( i = 1; i < numpoints; i++ ) {
  20268. normals[ i ] = normals[ i-1 ].clone();
  20269. binormals[ i ] = binormals[ i-1 ].clone();
  20270. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  20271. if ( vec.length() > epsilon ) {
  20272. vec.normalize();
  20273. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  20274. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20275. }
  20276. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20277. }
  20278. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20279. if ( closed ) {
  20280. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  20281. theta /= ( numpoints - 1 );
  20282. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  20283. theta = -theta;
  20284. }
  20285. for ( i = 1; i < numpoints; i++ ) {
  20286. // twist a little...
  20287. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20288. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20289. }
  20290. }
  20291. };
  20292. /**
  20293. * @author clockworkgeek / https://github.com/clockworkgeek
  20294. * @author timothypratley / https://github.com/timothypratley
  20295. * @author WestLangley / http://github.com/WestLangley
  20296. */
  20297. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  20298. THREE.Geometry.call( this );
  20299. radius = radius || 1;
  20300. detail = detail || 0;
  20301. var that = this;
  20302. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  20303. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  20304. }
  20305. var midpoints = [], p = this.vertices;
  20306. var f = [];
  20307. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20308. var v1 = p[ faces[ i ][ 0 ] ];
  20309. var v2 = p[ faces[ i ][ 1 ] ];
  20310. var v3 = p[ faces[ i ][ 2 ] ];
  20311. f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20312. }
  20313. for ( var i = 0, l = f.length; i < l; i ++ ) {
  20314. subdivide(f[ i ], detail);
  20315. }
  20316. // Handle case when face straddles the seam
  20317. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  20318. var uvs = this.faceVertexUvs[ 0 ][ i ];
  20319. var x0 = uvs[ 0 ].x;
  20320. var x1 = uvs[ 1 ].x;
  20321. var x2 = uvs[ 2 ].x;
  20322. var max = Math.max( x0, Math.max( x1, x2 ) );
  20323. var min = Math.min( x0, Math.min( x1, x2 ) );
  20324. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  20325. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  20326. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  20327. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  20328. }
  20329. }
  20330. // Apply radius
  20331. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  20332. this.vertices[ i ].multiplyScalar( radius );
  20333. }
  20334. // Merge vertices
  20335. this.mergeVertices();
  20336. this.computeCentroids();
  20337. this.computeFaceNormals();
  20338. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20339. // Project vector onto sphere's surface
  20340. function prepare( vector ) {
  20341. var vertex = vector.normalize().clone();
  20342. vertex.index = that.vertices.push( vertex ) - 1;
  20343. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  20344. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  20345. var v = inclination( vector ) / Math.PI + 0.5;
  20346. vertex.uv = new THREE.Vector2( u, 1 - v );
  20347. return vertex;
  20348. }
  20349. // Approximate a curved face with recursively sub-divided triangles.
  20350. function make( v1, v2, v3 ) {
  20351. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20352. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  20353. that.faces.push( face );
  20354. var azi = azimuth( face.centroid );
  20355. that.faceVertexUvs[ 0 ].push( [
  20356. correctUV( v1.uv, v1, azi ),
  20357. correctUV( v2.uv, v2, azi ),
  20358. correctUV( v3.uv, v3, azi )
  20359. ] );
  20360. }
  20361. // Analytically subdivide a face to the required detail level.
  20362. function subdivide(face, detail ) {
  20363. var cols = Math.pow(2, detail);
  20364. var cells = Math.pow(4, detail);
  20365. var a = prepare( that.vertices[ face.a ] );
  20366. var b = prepare( that.vertices[ face.b ] );
  20367. var c = prepare( that.vertices[ face.c ] );
  20368. var v = [];
  20369. // Construct all of the vertices for this subdivision.
  20370. for ( var i = 0 ; i <= cols; i ++ ) {
  20371. v[ i ] = [];
  20372. var aj = prepare( a.clone().lerp( c, i / cols ) );
  20373. var bj = prepare( b.clone().lerp( c, i / cols ) );
  20374. var rows = cols - i;
  20375. for ( var j = 0; j <= rows; j ++) {
  20376. if ( j == 0 && i == cols ) {
  20377. v[ i ][ j ] = aj;
  20378. } else {
  20379. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  20380. }
  20381. }
  20382. }
  20383. // Construct all of the faces.
  20384. for ( var i = 0; i < cols ; i ++ ) {
  20385. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  20386. var k = Math.floor( j / 2 );
  20387. if ( j % 2 == 0 ) {
  20388. make(
  20389. v[ i ][ k + 1],
  20390. v[ i + 1 ][ k ],
  20391. v[ i ][ k ]
  20392. );
  20393. } else {
  20394. make(
  20395. v[ i ][ k + 1 ],
  20396. v[ i + 1][ k + 1],
  20397. v[ i + 1 ][ k ]
  20398. );
  20399. }
  20400. }
  20401. }
  20402. }
  20403. // Angle around the Y axis, counter-clockwise when looking from above.
  20404. function azimuth( vector ) {
  20405. return Math.atan2( vector.z, -vector.x );
  20406. }
  20407. // Angle above the XZ plane.
  20408. function inclination( vector ) {
  20409. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20410. }
  20411. // Texture fixing helper. Spheres have some odd behaviours.
  20412. function correctUV( uv, vector, azimuth ) {
  20413. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  20414. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  20415. return uv.clone();
  20416. }
  20417. };
  20418. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20419. /**
  20420. * @author timothypratley / https://github.com/timothypratley
  20421. */
  20422. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20423. this.radius = radius;
  20424. this.detail = detail;
  20425. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20426. var vertices = [
  20427. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  20428. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  20429. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  20430. ];
  20431. var faces = [
  20432. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  20433. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  20434. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  20435. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  20436. ];
  20437. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20438. };
  20439. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20440. /**
  20441. * @author timothypratley / https://github.com/timothypratley
  20442. */
  20443. THREE.OctahedronGeometry = function ( radius, detail ) {
  20444. var vertices = [
  20445. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  20446. ];
  20447. var faces = [
  20448. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  20449. ];
  20450. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20451. };
  20452. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20453. /**
  20454. * @author timothypratley / https://github.com/timothypratley
  20455. */
  20456. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20457. var vertices = [
  20458. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  20459. ];
  20460. var faces = [
  20461. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  20462. ];
  20463. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20464. };
  20465. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20466. /**
  20467. * @author zz85 / https://github.com/zz85
  20468. * Parametric Surfaces Geometry
  20469. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20470. *
  20471. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  20472. *
  20473. */
  20474. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  20475. THREE.Geometry.call( this );
  20476. var verts = this.vertices;
  20477. var faces = this.faces;
  20478. var uvs = this.faceVertexUvs[ 0 ];
  20479. var i, il, j, p;
  20480. var u, v;
  20481. var stackCount = stacks + 1;
  20482. var sliceCount = slices + 1;
  20483. for ( i = 0; i <= stacks; i ++ ) {
  20484. v = i / stacks;
  20485. for ( j = 0; j <= slices; j ++ ) {
  20486. u = j / slices;
  20487. p = func( u, v );
  20488. verts.push( p );
  20489. }
  20490. }
  20491. var a, b, c, d;
  20492. var uva, uvb, uvc, uvd;
  20493. for ( i = 0; i < stacks; i ++ ) {
  20494. for ( j = 0; j < slices; j ++ ) {
  20495. a = i * sliceCount + j;
  20496. b = i * sliceCount + j + 1;
  20497. c = (i + 1) * sliceCount + j + 1;
  20498. d = (i + 1) * sliceCount + j;
  20499. uva = new THREE.Vector2( j / slices, i / stacks );
  20500. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20501. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20502. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20503. faces.push( new THREE.Face3( a, b, d ) );
  20504. uvs.push( [ uva, uvb, uvd ] );
  20505. faces.push( new THREE.Face3( b, c, d ) );
  20506. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  20507. }
  20508. }
  20509. // console.log(this);
  20510. // magic bullet
  20511. // var diff = this.mergeVertices();
  20512. // console.log('removed ', diff, ' vertices by merging');
  20513. this.computeCentroids();
  20514. this.computeFaceNormals();
  20515. this.computeVertexNormals();
  20516. };
  20517. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20518. /**
  20519. * @author sroucheray / http://sroucheray.org/
  20520. * @author mrdoob / http://mrdoob.com/
  20521. */
  20522. THREE.AxisHelper = function ( size ) {
  20523. size = size || 1;
  20524. var geometry = new THREE.Geometry();
  20525. geometry.vertices.push(
  20526. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  20527. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  20528. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  20529. );
  20530. geometry.colors.push(
  20531. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20532. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20533. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20534. );
  20535. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20536. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20537. };
  20538. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20539. /**
  20540. * @author WestLangley / http://github.com/WestLangley
  20541. * @author zz85 / http://github.com/zz85
  20542. * @author bhouston / http://exocortex.com
  20543. *
  20544. * Creates an arrow for visualizing directions
  20545. *
  20546. * Parameters:
  20547. * dir - Vector3
  20548. * origin - Vector3
  20549. * length - Number
  20550. * hex - color in hex value
  20551. * headLength - Number
  20552. * headWidth - Number
  20553. */
  20554. THREE.ArrowHelper = function ( dir, origin, length, hex, headLength, headWidth ) {
  20555. // dir is assumed to be normalized
  20556. THREE.Object3D.call( this );
  20557. if ( hex === undefined ) hex = 0xffff00;
  20558. if ( length === undefined ) length = 1;
  20559. if ( headLength === undefined ) headLength = 0.2 * length;
  20560. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20561. this.position = origin;
  20562. var lineGeometry = new THREE.Geometry();
  20563. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20564. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20565. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20566. this.line.matrixAutoUpdate = false;
  20567. this.add( this.line );
  20568. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  20569. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  20570. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20571. this.cone.matrixAutoUpdate = false;
  20572. this.add( this.cone );
  20573. this.setDirection( dir );
  20574. this.setLength( length, headLength, headWidth );
  20575. };
  20576. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20577. THREE.ArrowHelper.prototype.setDirection = function () {
  20578. var axis = new THREE.Vector3();
  20579. var radians;
  20580. return function ( dir ) {
  20581. // dir is assumed to be normalized
  20582. if ( dir.y > 0.99999 ) {
  20583. this.quaternion.set( 0, 0, 0, 1 );
  20584. } else if ( dir.y < - 0.99999 ) {
  20585. this.quaternion.set( 1, 0, 0, 0 );
  20586. } else {
  20587. axis.set( dir.z, 0, - dir.x ).normalize();
  20588. radians = Math.acos( dir.y );
  20589. this.quaternion.setFromAxisAngle( axis, radians );
  20590. }
  20591. };
  20592. }();
  20593. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  20594. if ( headLength === undefined ) headLength = 0.2 * length;
  20595. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20596. this.line.scale.set( 1, length, 1 );
  20597. this.line.updateMatrix();
  20598. this.cone.scale.set( headWidth, headLength, headWidth );
  20599. this.cone.position.y = length;
  20600. this.cone.updateMatrix();
  20601. };
  20602. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20603. this.line.material.color.setHex( hex );
  20604. this.cone.material.color.setHex( hex );
  20605. };
  20606. /**
  20607. * @author mrdoob / http://mrdoob.com/
  20608. */
  20609. THREE.BoxHelper = function ( object ) {
  20610. // 5____4
  20611. // 1/___0/|
  20612. // | 6__|_7
  20613. // 2/___3/
  20614. var vertices = [
  20615. new THREE.Vector3( 1, 1, 1 ),
  20616. new THREE.Vector3( - 1, 1, 1 ),
  20617. new THREE.Vector3( - 1, - 1, 1 ),
  20618. new THREE.Vector3( 1, - 1, 1 ),
  20619. new THREE.Vector3( 1, 1, - 1 ),
  20620. new THREE.Vector3( - 1, 1, - 1 ),
  20621. new THREE.Vector3( - 1, - 1, - 1 ),
  20622. new THREE.Vector3( 1, - 1, - 1 )
  20623. ];
  20624. this.vertices = vertices;
  20625. // TODO: Wouldn't be nice if Line had .segments?
  20626. var geometry = new THREE.Geometry();
  20627. geometry.vertices.push(
  20628. vertices[ 0 ], vertices[ 1 ],
  20629. vertices[ 1 ], vertices[ 2 ],
  20630. vertices[ 2 ], vertices[ 3 ],
  20631. vertices[ 3 ], vertices[ 0 ],
  20632. vertices[ 4 ], vertices[ 5 ],
  20633. vertices[ 5 ], vertices[ 6 ],
  20634. vertices[ 6 ], vertices[ 7 ],
  20635. vertices[ 7 ], vertices[ 4 ],
  20636. vertices[ 0 ], vertices[ 4 ],
  20637. vertices[ 1 ], vertices[ 5 ],
  20638. vertices[ 2 ], vertices[ 6 ],
  20639. vertices[ 3 ], vertices[ 7 ]
  20640. );
  20641. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20642. if ( object !== undefined ) {
  20643. this.update( object );
  20644. }
  20645. };
  20646. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20647. THREE.BoxHelper.prototype.update = function ( object ) {
  20648. var geometry = object.geometry;
  20649. if ( geometry.boundingBox === null ) {
  20650. geometry.computeBoundingBox();
  20651. }
  20652. var min = geometry.boundingBox.min;
  20653. var max = geometry.boundingBox.max;
  20654. var vertices = this.vertices;
  20655. vertices[ 0 ].set( max.x, max.y, max.z );
  20656. vertices[ 1 ].set( min.x, max.y, max.z );
  20657. vertices[ 2 ].set( min.x, min.y, max.z );
  20658. vertices[ 3 ].set( max.x, min.y, max.z );
  20659. vertices[ 4 ].set( max.x, max.y, min.z );
  20660. vertices[ 5 ].set( min.x, max.y, min.z );
  20661. vertices[ 6 ].set( min.x, min.y, min.z );
  20662. vertices[ 7 ].set( max.x, min.y, min.z );
  20663. this.geometry.computeBoundingSphere();
  20664. this.geometry.verticesNeedUpdate = true;
  20665. this.matrixAutoUpdate = false;
  20666. this.matrixWorld = object.matrixWorld;
  20667. };
  20668. /**
  20669. * @author WestLangley / http://github.com/WestLangley
  20670. */
  20671. // a helper to show the world-axis-aligned bounding box for an object
  20672. THREE.BoundingBoxHelper = function ( object, hex ) {
  20673. var color = ( hex !== undefined ) ? hex : 0x888888;
  20674. this.object = object;
  20675. this.box = new THREE.Box3();
  20676. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20677. };
  20678. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20679. THREE.BoundingBoxHelper.prototype.update = function () {
  20680. this.box.setFromObject( this.object );
  20681. this.box.size( this.scale );
  20682. this.box.center( this.position );
  20683. };
  20684. /**
  20685. * @author alteredq / http://alteredqualia.com/
  20686. *
  20687. * - shows frustum, line of sight and up of the camera
  20688. * - suitable for fast updates
  20689. * - based on frustum visualization in lightgl.js shadowmap example
  20690. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20691. */
  20692. THREE.CameraHelper = function ( camera ) {
  20693. var geometry = new THREE.Geometry();
  20694. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20695. var pointMap = {};
  20696. // colors
  20697. var hexFrustum = 0xffaa00;
  20698. var hexCone = 0xff0000;
  20699. var hexUp = 0x00aaff;
  20700. var hexTarget = 0xffffff;
  20701. var hexCross = 0x333333;
  20702. // near
  20703. addLine( "n1", "n2", hexFrustum );
  20704. addLine( "n2", "n4", hexFrustum );
  20705. addLine( "n4", "n3", hexFrustum );
  20706. addLine( "n3", "n1", hexFrustum );
  20707. // far
  20708. addLine( "f1", "f2", hexFrustum );
  20709. addLine( "f2", "f4", hexFrustum );
  20710. addLine( "f4", "f3", hexFrustum );
  20711. addLine( "f3", "f1", hexFrustum );
  20712. // sides
  20713. addLine( "n1", "f1", hexFrustum );
  20714. addLine( "n2", "f2", hexFrustum );
  20715. addLine( "n3", "f3", hexFrustum );
  20716. addLine( "n4", "f4", hexFrustum );
  20717. // cone
  20718. addLine( "p", "n1", hexCone );
  20719. addLine( "p", "n2", hexCone );
  20720. addLine( "p", "n3", hexCone );
  20721. addLine( "p", "n4", hexCone );
  20722. // up
  20723. addLine( "u1", "u2", hexUp );
  20724. addLine( "u2", "u3", hexUp );
  20725. addLine( "u3", "u1", hexUp );
  20726. // target
  20727. addLine( "c", "t", hexTarget );
  20728. addLine( "p", "c", hexCross );
  20729. // cross
  20730. addLine( "cn1", "cn2", hexCross );
  20731. addLine( "cn3", "cn4", hexCross );
  20732. addLine( "cf1", "cf2", hexCross );
  20733. addLine( "cf3", "cf4", hexCross );
  20734. function addLine( a, b, hex ) {
  20735. addPoint( a, hex );
  20736. addPoint( b, hex );
  20737. }
  20738. function addPoint( id, hex ) {
  20739. geometry.vertices.push( new THREE.Vector3() );
  20740. geometry.colors.push( new THREE.Color( hex ) );
  20741. if ( pointMap[ id ] === undefined ) {
  20742. pointMap[ id ] = [];
  20743. }
  20744. pointMap[ id ].push( geometry.vertices.length - 1 );
  20745. }
  20746. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20747. this.camera = camera;
  20748. this.matrixWorld = camera.matrixWorld;
  20749. this.matrixAutoUpdate = false;
  20750. this.pointMap = pointMap;
  20751. this.update();
  20752. };
  20753. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20754. THREE.CameraHelper.prototype.update = function () {
  20755. var vector = new THREE.Vector3();
  20756. var camera = new THREE.Camera();
  20757. var projector = new THREE.Projector();
  20758. return function () {
  20759. var scope = this;
  20760. var w = 1, h = 1;
  20761. // we need just camera projection matrix
  20762. // world matrix must be identity
  20763. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20764. // center / target
  20765. setPoint( "c", 0, 0, -1 );
  20766. setPoint( "t", 0, 0, 1 );
  20767. // near
  20768. setPoint( "n1", -w, -h, -1 );
  20769. setPoint( "n2", w, -h, -1 );
  20770. setPoint( "n3", -w, h, -1 );
  20771. setPoint( "n4", w, h, -1 );
  20772. // far
  20773. setPoint( "f1", -w, -h, 1 );
  20774. setPoint( "f2", w, -h, 1 );
  20775. setPoint( "f3", -w, h, 1 );
  20776. setPoint( "f4", w, h, 1 );
  20777. // up
  20778. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20779. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20780. setPoint( "u3", 0, h * 2, -1 );
  20781. // cross
  20782. setPoint( "cf1", -w, 0, 1 );
  20783. setPoint( "cf2", w, 0, 1 );
  20784. setPoint( "cf3", 0, -h, 1 );
  20785. setPoint( "cf4", 0, h, 1 );
  20786. setPoint( "cn1", -w, 0, -1 );
  20787. setPoint( "cn2", w, 0, -1 );
  20788. setPoint( "cn3", 0, -h, -1 );
  20789. setPoint( "cn4", 0, h, -1 );
  20790. function setPoint( point, x, y, z ) {
  20791. vector.set( x, y, z );
  20792. projector.unprojectVector( vector, camera );
  20793. var points = scope.pointMap[ point ];
  20794. if ( points !== undefined ) {
  20795. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20796. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20797. }
  20798. }
  20799. }
  20800. this.geometry.verticesNeedUpdate = true;
  20801. };
  20802. }();
  20803. /**
  20804. * @author alteredq / http://alteredqualia.com/
  20805. * @author mrdoob / http://mrdoob.com/
  20806. * @author WestLangley / http://github.com/WestLangley
  20807. */
  20808. THREE.DirectionalLightHelper = function ( light, size ) {
  20809. THREE.Object3D.call( this );
  20810. this.light = light;
  20811. this.light.updateMatrixWorld();
  20812. this.matrixWorld = light.matrixWorld;
  20813. this.matrixAutoUpdate = false;
  20814. size = size || 1;
  20815. var geometry = new THREE.PlaneGeometry( size, size );
  20816. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20817. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20818. this.lightPlane = new THREE.Mesh( geometry, material );
  20819. this.add( this.lightPlane );
  20820. geometry = new THREE.Geometry();
  20821. geometry.vertices.push( new THREE.Vector3() );
  20822. geometry.vertices.push( new THREE.Vector3() );
  20823. material = new THREE.LineBasicMaterial( { fog: false } );
  20824. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20825. this.targetLine = new THREE.Line( geometry, material );
  20826. this.add( this.targetLine );
  20827. this.update();
  20828. };
  20829. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20830. THREE.DirectionalLightHelper.prototype.dispose = function () {
  20831. this.lightPlane.geometry.dispose();
  20832. this.lightPlane.material.dispose();
  20833. this.targetLine.geometry.dispose();
  20834. this.targetLine.material.dispose();
  20835. };
  20836. THREE.DirectionalLightHelper.prototype.update = function () {
  20837. var v1 = new THREE.Vector3();
  20838. var v2 = new THREE.Vector3();
  20839. var v3 = new THREE.Vector3();
  20840. return function () {
  20841. v1.setFromMatrixPosition( this.light.matrixWorld );
  20842. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20843. v3.subVectors( v2, v1 );
  20844. this.lightPlane.lookAt( v3 );
  20845. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20846. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  20847. this.targetLine.geometry.verticesNeedUpdate = true;
  20848. this.targetLine.material.color.copy( this.lightPlane.material.color );
  20849. }
  20850. }();
  20851. /**
  20852. * @author WestLangley / http://github.com/WestLangley
  20853. */
  20854. THREE.EdgesHelper = function ( object, hex ) {
  20855. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20856. var edge = [ 0, 0 ], hash = {};
  20857. var sortFunction = function ( a, b ) { return a - b };
  20858. var keys = [ 'a', 'b', 'c' ];
  20859. var geometry = new THREE.BufferGeometry();
  20860. var geometry2 = object.geometry.clone();
  20861. geometry2.mergeVertices();
  20862. geometry2.computeFaceNormals();
  20863. var vertices = geometry2.vertices;
  20864. var faces = geometry2.faces;
  20865. var numEdges = 0;
  20866. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20867. var face = faces[ i ];
  20868. for ( var j = 0; j < 3; j ++ ) {
  20869. edge[ 0 ] = face[ keys[ j ] ];
  20870. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20871. edge.sort( sortFunction );
  20872. var key = edge.toString();
  20873. if ( hash[ key ] === undefined ) {
  20874. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  20875. numEdges ++;
  20876. } else {
  20877. hash[ key ].face2 = i;
  20878. }
  20879. }
  20880. }
  20881. geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
  20882. var coords = geometry.attributes.position.array;
  20883. var index = 0;
  20884. for ( var key in hash ) {
  20885. var h = hash[ key ];
  20886. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) < 0.9999 ) { // hardwired const OK
  20887. var vertex = vertices[ h.vert1 ];
  20888. coords[ index ++ ] = vertex.x;
  20889. coords[ index ++ ] = vertex.y;
  20890. coords[ index ++ ] = vertex.z;
  20891. vertex = vertices[ h.vert2 ];
  20892. coords[ index ++ ] = vertex.x;
  20893. coords[ index ++ ] = vertex.y;
  20894. coords[ index ++ ] = vertex.z;
  20895. }
  20896. }
  20897. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  20898. this.matrixAutoUpdate = false;
  20899. this.matrixWorld = object.matrixWorld;
  20900. };
  20901. THREE.EdgesHelper.prototype = Object.create( THREE.Line.prototype );
  20902. /**
  20903. * @author mrdoob / http://mrdoob.com/
  20904. * @author WestLangley / http://github.com/WestLangley
  20905. */
  20906. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20907. this.object = object;
  20908. this.size = ( size !== undefined ) ? size : 1;
  20909. var color = ( hex !== undefined ) ? hex : 0xffff00;
  20910. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20911. var geometry = new THREE.Geometry();
  20912. var faces = this.object.geometry.faces;
  20913. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20914. geometry.vertices.push( new THREE.Vector3() );
  20915. geometry.vertices.push( new THREE.Vector3() );
  20916. }
  20917. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20918. this.matrixAutoUpdate = false;
  20919. this.normalMatrix = new THREE.Matrix3();
  20920. this.update();
  20921. };
  20922. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20923. THREE.FaceNormalsHelper.prototype.update = ( function ( object ) {
  20924. var v1 = new THREE.Vector3();
  20925. return function ( object ) {
  20926. this.object.updateMatrixWorld( true );
  20927. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20928. var vertices = this.geometry.vertices;
  20929. var faces = this.object.geometry.faces;
  20930. var worldMatrix = this.object.matrixWorld;
  20931. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20932. var face = faces[ i ];
  20933. v1.copy( face.normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20934. var idx = 2 * i;
  20935. vertices[ idx ].copy( face.centroid ).applyMatrix4( worldMatrix );
  20936. vertices[ idx + 1 ].addVectors( vertices[ idx ], v1 );
  20937. }
  20938. this.geometry.verticesNeedUpdate = true;
  20939. return this;
  20940. }
  20941. }());
  20942. /**
  20943. * @author mrdoob / http://mrdoob.com/
  20944. */
  20945. THREE.GridHelper = function ( size, step ) {
  20946. var geometry = new THREE.Geometry();
  20947. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20948. this.color1 = new THREE.Color( 0x444444 );
  20949. this.color2 = new THREE.Color( 0x888888 );
  20950. for ( var i = - size; i <= size; i += step ) {
  20951. geometry.vertices.push(
  20952. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  20953. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  20954. );
  20955. var color = i === 0 ? this.color1 : this.color2;
  20956. geometry.colors.push( color, color, color, color );
  20957. }
  20958. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20959. };
  20960. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  20961. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  20962. this.color1.set( colorCenterLine );
  20963. this.color2.set( colorGrid );
  20964. this.geometry.colorsNeedUpdate = true;
  20965. }
  20966. /**
  20967. * @author alteredq / http://alteredqualia.com/
  20968. * @author mrdoob / http://mrdoob.com/
  20969. */
  20970. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20971. THREE.Object3D.call( this );
  20972. this.light = light;
  20973. this.light.updateMatrixWorld();
  20974. this.matrixWorld = light.matrixWorld;
  20975. this.matrixAutoUpdate = false;
  20976. this.colors = [ new THREE.Color(), new THREE.Color() ];
  20977. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20978. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20979. for ( var i = 0, il = 8; i < il; i ++ ) {
  20980. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  20981. }
  20982. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  20983. this.lightSphere = new THREE.Mesh( geometry, material );
  20984. this.add( this.lightSphere );
  20985. this.update();
  20986. };
  20987. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20988. THREE.HemisphereLightHelper.prototype.dispose = function () {
  20989. this.lightSphere.geometry.dispose();
  20990. this.lightSphere.material.dispose();
  20991. };
  20992. THREE.HemisphereLightHelper.prototype.update = function () {
  20993. var vector = new THREE.Vector3();
  20994. return function () {
  20995. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  20996. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  20997. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20998. this.lightSphere.geometry.colorsNeedUpdate = true;
  20999. }
  21000. }();
  21001. /**
  21002. * @author alteredq / http://alteredqualia.com/
  21003. * @author mrdoob / http://mrdoob.com/
  21004. */
  21005. THREE.PointLightHelper = function ( light, sphereSize ) {
  21006. this.light = light;
  21007. this.light.updateMatrixWorld();
  21008. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21009. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  21010. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21011. THREE.Mesh.call( this, geometry, material );
  21012. this.matrixWorld = this.light.matrixWorld;
  21013. this.matrixAutoUpdate = false;
  21014. /*
  21015. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  21016. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  21017. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  21018. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  21019. var d = light.distance;
  21020. if ( d === 0.0 ) {
  21021. this.lightDistance.visible = false;
  21022. } else {
  21023. this.lightDistance.scale.set( d, d, d );
  21024. }
  21025. this.add( this.lightDistance );
  21026. */
  21027. };
  21028. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  21029. THREE.PointLightHelper.prototype.dispose = function () {
  21030. this.geometry.dispose();
  21031. this.material.dispose();
  21032. };
  21033. THREE.PointLightHelper.prototype.update = function () {
  21034. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21035. /*
  21036. var d = this.light.distance;
  21037. if ( d === 0.0 ) {
  21038. this.lightDistance.visible = false;
  21039. } else {
  21040. this.lightDistance.visible = true;
  21041. this.lightDistance.scale.set( d, d, d );
  21042. }
  21043. */
  21044. };
  21045. /**
  21046. * @author alteredq / http://alteredqualia.com/
  21047. * @author mrdoob / http://mrdoob.com/
  21048. * @author WestLangley / http://github.com/WestLangley
  21049. */
  21050. THREE.SpotLightHelper = function ( light ) {
  21051. THREE.Object3D.call( this );
  21052. this.light = light;
  21053. this.light.updateMatrixWorld();
  21054. this.matrixWorld = light.matrixWorld;
  21055. this.matrixAutoUpdate = false;
  21056. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  21057. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  21058. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21059. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  21060. this.cone = new THREE.Mesh( geometry, material );
  21061. this.add( this.cone );
  21062. this.update();
  21063. };
  21064. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21065. THREE.SpotLightHelper.prototype.dispose = function () {
  21066. this.cone.geometry.dispose();
  21067. this.cone.material.dispose();
  21068. };
  21069. THREE.SpotLightHelper.prototype.update = function () {
  21070. var vector = new THREE.Vector3();
  21071. var vector2 = new THREE.Vector3();
  21072. return function () {
  21073. var coneLength = this.light.distance ? this.light.distance : 10000;
  21074. var coneWidth = coneLength * Math.tan( this.light.angle );
  21075. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  21076. vector.setFromMatrixPosition( this.light.matrixWorld );
  21077. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  21078. this.cone.lookAt( vector2.sub( vector ) );
  21079. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21080. };
  21081. }();
  21082. /**
  21083. * @author mrdoob / http://mrdoob.com/
  21084. * @author WestLangley / http://github.com/WestLangley
  21085. */
  21086. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  21087. this.object = object;
  21088. this.size = ( size !== undefined ) ? size : 1;
  21089. var color = ( hex !== undefined ) ? hex : 0xff0000;
  21090. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21091. var geometry = new THREE.Geometry();
  21092. var vertices = object.geometry.vertices;
  21093. var faces = object.geometry.faces;
  21094. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21095. var face = faces[ i ];
  21096. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21097. geometry.vertices.push( new THREE.Vector3() );
  21098. geometry.vertices.push( new THREE.Vector3() );
  21099. }
  21100. }
  21101. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21102. this.matrixAutoUpdate = false;
  21103. this.normalMatrix = new THREE.Matrix3();
  21104. this.update();
  21105. };
  21106. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  21107. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  21108. var v1 = new THREE.Vector3();
  21109. return function( object ) {
  21110. var keys = [ 'a', 'b', 'c', 'd' ];
  21111. this.object.updateMatrixWorld( true );
  21112. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  21113. var vertices = this.geometry.vertices;
  21114. var verts = this.object.geometry.vertices;
  21115. var faces = this.object.geometry.faces;
  21116. var worldMatrix = this.object.matrixWorld;
  21117. var idx = 0;
  21118. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21119. var face = faces[ i ];
  21120. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21121. var vertexId = face[ keys[ j ] ];
  21122. var vertex = verts[ vertexId ];
  21123. var normal = face.vertexNormals[ j ];
  21124. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21125. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  21126. v1.add( vertices[ idx ] );
  21127. idx = idx + 1;
  21128. vertices[ idx ].copy( v1 );
  21129. idx = idx + 1;
  21130. }
  21131. }
  21132. this.geometry.verticesNeedUpdate = true;
  21133. return this;
  21134. }
  21135. }());
  21136. /**
  21137. * @author mrdoob / http://mrdoob.com/
  21138. * @author WestLangley / http://github.com/WestLangley
  21139. */
  21140. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  21141. this.object = object;
  21142. this.size = ( size !== undefined ) ? size : 1;
  21143. var color = ( hex !== undefined ) ? hex : 0x0000ff;
  21144. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21145. var geometry = new THREE.Geometry();
  21146. var vertices = object.geometry.vertices;
  21147. var faces = object.geometry.faces;
  21148. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21149. var face = faces[ i ];
  21150. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21151. geometry.vertices.push( new THREE.Vector3() );
  21152. geometry.vertices.push( new THREE.Vector3() );
  21153. }
  21154. }
  21155. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21156. this.matrixAutoUpdate = false;
  21157. this.update();
  21158. };
  21159. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  21160. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  21161. var v1 = new THREE.Vector3();
  21162. return function( object ) {
  21163. var keys = [ 'a', 'b', 'c', 'd' ];
  21164. this.object.updateMatrixWorld( true );
  21165. var vertices = this.geometry.vertices;
  21166. var verts = this.object.geometry.vertices;
  21167. var faces = this.object.geometry.faces;
  21168. var worldMatrix = this.object.matrixWorld;
  21169. var idx = 0;
  21170. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21171. var face = faces[ i ];
  21172. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21173. var vertexId = face[ keys[ j ] ];
  21174. var vertex = verts[ vertexId ];
  21175. var tangent = face.vertexTangents[ j ];
  21176. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21177. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  21178. v1.add( vertices[ idx ] );
  21179. idx = idx + 1;
  21180. vertices[ idx ].copy( v1 );
  21181. idx = idx + 1;
  21182. }
  21183. }
  21184. this.geometry.verticesNeedUpdate = true;
  21185. return this;
  21186. }
  21187. }());
  21188. /**
  21189. * @author mrdoob / http://mrdoob.com/
  21190. */
  21191. THREE.WireframeHelper = function ( object, hex ) {
  21192. var color = ( hex !== undefined ) ? hex : 0xffffff;
  21193. var edge = [ 0, 0 ], hash = {};
  21194. var sortFunction = function ( a, b ) { return a - b };
  21195. var keys = [ 'a', 'b', 'c' ];
  21196. var geometry = new THREE.BufferGeometry();
  21197. if ( object.geometry instanceof THREE.Geometry ) {
  21198. var vertices = object.geometry.vertices;
  21199. var faces = object.geometry.faces;
  21200. var numEdges = 0;
  21201. // allocate maximal size
  21202. var edges = new Uint32Array( 6 * faces.length );
  21203. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21204. var face = faces[ i ];
  21205. for ( var j = 0; j < 3; j ++ ) {
  21206. edge[ 0 ] = face[ keys[ j ] ];
  21207. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  21208. edge.sort( sortFunction );
  21209. var key = edge.toString();
  21210. if ( hash[ key ] === undefined ) {
  21211. edges[ 2 * numEdges ] = edge[ 0 ];
  21212. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21213. hash[ key ] = true;
  21214. numEdges ++;
  21215. }
  21216. }
  21217. }
  21218. geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
  21219. var coords = geometry.attributes.position.array;
  21220. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21221. for ( var j = 0; j < 2; j ++ ) {
  21222. var vertex = vertices[ edges [ 2 * i + j] ];
  21223. var index = 6 * i + 3 * j;
  21224. coords[ index + 0 ] = vertex.x;
  21225. coords[ index + 1 ] = vertex.y;
  21226. coords[ index + 2 ] = vertex.z;
  21227. }
  21228. }
  21229. } else if ( object.geometry instanceof THREE.BufferGeometry && object.geometry.attributes.index !== undefined ) { // indexed BufferGeometry
  21230. var vertices = object.geometry.attributes.position.array;
  21231. var indices = object.geometry.attributes.index.array;
  21232. var offsets = object.geometry.offsets;
  21233. var numEdges = 0;
  21234. // allocate maximal size
  21235. var edges = new Uint32Array( 2 * indices.length );
  21236. for ( var o = 0, ol = offsets.length; o < ol; ++ o ) {
  21237. var start = offsets[ o ].start;
  21238. var count = offsets[ o ].count;
  21239. var index = offsets[ o ].index;
  21240. for ( var i = start, il = start + count; i < il; i += 3 ) {
  21241. for ( var j = 0; j < 3; j ++ ) {
  21242. edge[ 0 ] = index + indices[ i + j ];
  21243. edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ];
  21244. edge.sort( sortFunction );
  21245. var key = edge.toString();
  21246. if ( hash[ key ] === undefined ) {
  21247. edges[ 2 * numEdges ] = edge[ 0 ];
  21248. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21249. hash[ key ] = true;
  21250. numEdges ++;
  21251. }
  21252. }
  21253. }
  21254. }
  21255. geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
  21256. var coords = geometry.attributes.position.array;
  21257. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21258. for ( var j = 0; j < 2; j ++ ) {
  21259. var index = 6 * i + 3 * j;
  21260. var index2 = 3 * edges[ 2 * i + j];
  21261. coords[ index + 0 ] = vertices[ index2 ];
  21262. coords[ index + 1 ] = vertices[ index2 + 1 ];
  21263. coords[ index + 2 ] = vertices[ index2 + 2 ];
  21264. }
  21265. }
  21266. } else if ( object.geometry instanceof THREE.BufferGeometry ) { // non-indexed BufferGeometry
  21267. var vertices = object.geometry.attributes.position.array;
  21268. var numEdges = vertices.length / 3;
  21269. var numTris = numEdges / 3;
  21270. geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
  21271. var coords = geometry.attributes.position.array;
  21272. for ( var i = 0, l = numTris; i < l; i ++ ) {
  21273. for ( var j = 0; j < 3; j ++ ) {
  21274. var index = 18 * i + 6 * j;
  21275. var index1 = 9 * i + 3 * j;
  21276. coords[ index + 0 ] = vertices[ index1 ];
  21277. coords[ index + 1 ] = vertices[ index1 + 1 ];
  21278. coords[ index + 2 ] = vertices[ index1 + 2 ];
  21279. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  21280. coords[ index + 3 ] = vertices[ index2 ];
  21281. coords[ index + 4 ] = vertices[ index2 + 1 ];
  21282. coords[ index + 5 ] = vertices[ index2 + 2 ];
  21283. }
  21284. }
  21285. }
  21286. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  21287. this.matrixAutoUpdate = false;
  21288. this.matrixWorld = object.matrixWorld;
  21289. };
  21290. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  21291. /**
  21292. * @author alteredq / http://alteredqualia.com/
  21293. */
  21294. THREE.ImmediateRenderObject = function () {
  21295. THREE.Object3D.call( this );
  21296. this.render = function ( renderCallback ) { };
  21297. };
  21298. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  21299. /**
  21300. * @author mikael emtinger / http://gomo.se/
  21301. * @author alteredq / http://alteredqualia.com/
  21302. */
  21303. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  21304. THREE.Object3D.call( this );
  21305. this.lensFlares = [];
  21306. this.positionScreen = new THREE.Vector3();
  21307. this.customUpdateCallback = undefined;
  21308. if( texture !== undefined ) {
  21309. this.add( texture, size, distance, blending, color );
  21310. }
  21311. };
  21312. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  21313. /*
  21314. * Add: adds another flare
  21315. */
  21316. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  21317. if( size === undefined ) size = -1;
  21318. if( distance === undefined ) distance = 0;
  21319. if( opacity === undefined ) opacity = 1;
  21320. if( color === undefined ) color = new THREE.Color( 0xffffff );
  21321. if( blending === undefined ) blending = THREE.NormalBlending;
  21322. distance = Math.min( distance, Math.max( 0, distance ) );
  21323. this.lensFlares.push( { texture: texture, // THREE.Texture
  21324. size: size, // size in pixels (-1 = use texture.width)
  21325. distance: distance, // distance (0-1) from light source (0=at light source)
  21326. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  21327. scale: 1, // scale
  21328. rotation: 1, // rotation
  21329. opacity: opacity, // opacity
  21330. color: color, // color
  21331. blending: blending } ); // blending
  21332. };
  21333. /*
  21334. * Update lens flares update positions on all flares based on the screen position
  21335. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  21336. */
  21337. THREE.LensFlare.prototype.updateLensFlares = function () {
  21338. var f, fl = this.lensFlares.length;
  21339. var flare;
  21340. var vecX = -this.positionScreen.x * 2;
  21341. var vecY = -this.positionScreen.y * 2;
  21342. for( f = 0; f < fl; f ++ ) {
  21343. flare = this.lensFlares[ f ];
  21344. flare.x = this.positionScreen.x + vecX * flare.distance;
  21345. flare.y = this.positionScreen.y + vecY * flare.distance;
  21346. flare.wantedRotation = flare.x * Math.PI * 0.25;
  21347. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  21348. }
  21349. };
  21350. /**
  21351. * @author alteredq / http://alteredqualia.com/
  21352. */
  21353. THREE.MorphBlendMesh = function( geometry, material ) {
  21354. THREE.Mesh.call( this, geometry, material );
  21355. this.animationsMap = {};
  21356. this.animationsList = [];
  21357. // prepare default animation
  21358. // (all frames played together in 1 second)
  21359. var numFrames = this.geometry.morphTargets.length;
  21360. var name = "__default";
  21361. var startFrame = 0;
  21362. var endFrame = numFrames - 1;
  21363. var fps = numFrames / 1;
  21364. this.createAnimation( name, startFrame, endFrame, fps );
  21365. this.setAnimationWeight( name, 1 );
  21366. };
  21367. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  21368. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21369. var animation = {
  21370. startFrame: start,
  21371. endFrame: end,
  21372. length: end - start + 1,
  21373. fps: fps,
  21374. duration: ( end - start ) / fps,
  21375. lastFrame: 0,
  21376. currentFrame: 0,
  21377. active: false,
  21378. time: 0,
  21379. direction: 1,
  21380. weight: 1,
  21381. directionBackwards: false,
  21382. mirroredLoop: false
  21383. };
  21384. this.animationsMap[ name ] = animation;
  21385. this.animationsList.push( animation );
  21386. };
  21387. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21388. var pattern = /([a-z]+)(\d+)/;
  21389. var firstAnimation, frameRanges = {};
  21390. var geometry = this.geometry;
  21391. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21392. var morph = geometry.morphTargets[ i ];
  21393. var chunks = morph.name.match( pattern );
  21394. if ( chunks && chunks.length > 1 ) {
  21395. var name = chunks[ 1 ];
  21396. var num = chunks[ 2 ];
  21397. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  21398. var range = frameRanges[ name ];
  21399. if ( i < range.start ) range.start = i;
  21400. if ( i > range.end ) range.end = i;
  21401. if ( ! firstAnimation ) firstAnimation = name;
  21402. }
  21403. }
  21404. for ( var name in frameRanges ) {
  21405. var range = frameRanges[ name ];
  21406. this.createAnimation( name, range.start, range.end, fps );
  21407. }
  21408. this.firstAnimation = firstAnimation;
  21409. };
  21410. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21411. var animation = this.animationsMap[ name ];
  21412. if ( animation ) {
  21413. animation.direction = 1;
  21414. animation.directionBackwards = false;
  21415. }
  21416. };
  21417. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21418. var animation = this.animationsMap[ name ];
  21419. if ( animation ) {
  21420. animation.direction = -1;
  21421. animation.directionBackwards = true;
  21422. }
  21423. };
  21424. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21425. var animation = this.animationsMap[ name ];
  21426. if ( animation ) {
  21427. animation.fps = fps;
  21428. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21429. }
  21430. };
  21431. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21432. var animation = this.animationsMap[ name ];
  21433. if ( animation ) {
  21434. animation.duration = duration;
  21435. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21436. }
  21437. };
  21438. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21439. var animation = this.animationsMap[ name ];
  21440. if ( animation ) {
  21441. animation.weight = weight;
  21442. }
  21443. };
  21444. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21445. var animation = this.animationsMap[ name ];
  21446. if ( animation ) {
  21447. animation.time = time;
  21448. }
  21449. };
  21450. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21451. var time = 0;
  21452. var animation = this.animationsMap[ name ];
  21453. if ( animation ) {
  21454. time = animation.time;
  21455. }
  21456. return time;
  21457. };
  21458. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21459. var duration = -1;
  21460. var animation = this.animationsMap[ name ];
  21461. if ( animation ) {
  21462. duration = animation.duration;
  21463. }
  21464. return duration;
  21465. };
  21466. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21467. var animation = this.animationsMap[ name ];
  21468. if ( animation ) {
  21469. animation.time = 0;
  21470. animation.active = true;
  21471. } else {
  21472. console.warn( "animation[" + name + "] undefined" );
  21473. }
  21474. };
  21475. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21476. var animation = this.animationsMap[ name ];
  21477. if ( animation ) {
  21478. animation.active = false;
  21479. }
  21480. };
  21481. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21482. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21483. var animation = this.animationsList[ i ];
  21484. if ( ! animation.active ) continue;
  21485. var frameTime = animation.duration / animation.length;
  21486. animation.time += animation.direction * delta;
  21487. if ( animation.mirroredLoop ) {
  21488. if ( animation.time > animation.duration || animation.time < 0 ) {
  21489. animation.direction *= -1;
  21490. if ( animation.time > animation.duration ) {
  21491. animation.time = animation.duration;
  21492. animation.directionBackwards = true;
  21493. }
  21494. if ( animation.time < 0 ) {
  21495. animation.time = 0;
  21496. animation.directionBackwards = false;
  21497. }
  21498. }
  21499. } else {
  21500. animation.time = animation.time % animation.duration;
  21501. if ( animation.time < 0 ) animation.time += animation.duration;
  21502. }
  21503. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21504. var weight = animation.weight;
  21505. if ( keyframe !== animation.currentFrame ) {
  21506. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21507. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21508. this.morphTargetInfluences[ keyframe ] = 0;
  21509. animation.lastFrame = animation.currentFrame;
  21510. animation.currentFrame = keyframe;
  21511. }
  21512. var mix = ( animation.time % frameTime ) / frameTime;
  21513. if ( animation.directionBackwards ) mix = 1 - mix;
  21514. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21515. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21516. }
  21517. };
  21518. /**
  21519. * @author mikael emtinger / http://gomo.se/
  21520. * @author alteredq / http://alteredqualia.com/
  21521. */
  21522. THREE.LensFlarePlugin = function () {
  21523. var _gl, _renderer, _precision, _lensFlare = {};
  21524. this.init = function ( renderer ) {
  21525. _gl = renderer.context;
  21526. _renderer = renderer;
  21527. _precision = renderer.getPrecision();
  21528. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21529. _lensFlare.faces = new Uint16Array( 6 );
  21530. var i = 0;
  21531. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21532. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21533. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21534. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21535. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21536. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21537. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21538. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21539. i = 0;
  21540. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21541. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21542. // buffers
  21543. _lensFlare.vertexBuffer = _gl.createBuffer();
  21544. _lensFlare.elementBuffer = _gl.createBuffer();
  21545. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21546. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21547. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21548. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21549. // textures
  21550. _lensFlare.tempTexture = _gl.createTexture();
  21551. _lensFlare.occlusionTexture = _gl.createTexture();
  21552. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21553. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21554. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21555. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21556. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21557. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21558. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21559. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21560. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21561. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21562. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21563. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21564. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21565. _lensFlare.hasVertexTexture = false;
  21566. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21567. } else {
  21568. _lensFlare.hasVertexTexture = true;
  21569. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21570. }
  21571. _lensFlare.attributes = {};
  21572. _lensFlare.uniforms = {};
  21573. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21574. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21575. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21576. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21577. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21578. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21579. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21580. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21581. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21582. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21583. };
  21584. /*
  21585. * Render lens flares
  21586. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21587. * reads these back and calculates occlusion.
  21588. * Then _lensFlare.update_lensFlares() is called to re-position and
  21589. * update transparency of flares. Then they are rendered.
  21590. *
  21591. */
  21592. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21593. var flares = scene.__webglFlares,
  21594. nFlares = flares.length;
  21595. if ( ! nFlares ) return;
  21596. var tempPosition = new THREE.Vector3();
  21597. var invAspect = viewportHeight / viewportWidth,
  21598. halfViewportWidth = viewportWidth * 0.5,
  21599. halfViewportHeight = viewportHeight * 0.5;
  21600. var size = 16 / viewportHeight,
  21601. scale = new THREE.Vector2( size * invAspect, size );
  21602. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21603. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21604. var uniforms = _lensFlare.uniforms,
  21605. attributes = _lensFlare.attributes;
  21606. // set _lensFlare program and reset blending
  21607. _gl.useProgram( _lensFlare.program );
  21608. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21609. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21610. // loop through all lens flares to update their occlusion and positions
  21611. // setup gl and common used attribs/unforms
  21612. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21613. _gl.uniform1i( uniforms.map, 1 );
  21614. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21615. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21616. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21617. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21618. _gl.disable( _gl.CULL_FACE );
  21619. _gl.depthMask( false );
  21620. var i, j, jl, flare, sprite;
  21621. for ( i = 0; i < nFlares; i ++ ) {
  21622. size = 16 / viewportHeight;
  21623. scale.set( size * invAspect, size );
  21624. // calc object screen position
  21625. flare = flares[ i ];
  21626. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21627. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21628. tempPosition.applyProjection( camera.projectionMatrix );
  21629. // setup arrays for gl programs
  21630. screenPosition.copy( tempPosition )
  21631. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21632. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21633. // screen cull
  21634. if ( _lensFlare.hasVertexTexture || (
  21635. screenPositionPixels.x > 0 &&
  21636. screenPositionPixels.x < viewportWidth &&
  21637. screenPositionPixels.y > 0 &&
  21638. screenPositionPixels.y < viewportHeight ) ) {
  21639. // save current RGB to temp texture
  21640. _gl.activeTexture( _gl.TEXTURE1 );
  21641. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21642. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21643. // render pink quad
  21644. _gl.uniform1i( uniforms.renderType, 0 );
  21645. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21646. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21647. _gl.disable( _gl.BLEND );
  21648. _gl.enable( _gl.DEPTH_TEST );
  21649. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21650. // copy result to occlusionMap
  21651. _gl.activeTexture( _gl.TEXTURE0 );
  21652. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21653. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21654. // restore graphics
  21655. _gl.uniform1i( uniforms.renderType, 1 );
  21656. _gl.disable( _gl.DEPTH_TEST );
  21657. _gl.activeTexture( _gl.TEXTURE1 );
  21658. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21659. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21660. // update object positions
  21661. flare.positionScreen.copy( screenPosition )
  21662. if ( flare.customUpdateCallback ) {
  21663. flare.customUpdateCallback( flare );
  21664. } else {
  21665. flare.updateLensFlares();
  21666. }
  21667. // render flares
  21668. _gl.uniform1i( uniforms.renderType, 2 );
  21669. _gl.enable( _gl.BLEND );
  21670. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21671. sprite = flare.lensFlares[ j ];
  21672. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21673. screenPosition.x = sprite.x;
  21674. screenPosition.y = sprite.y;
  21675. screenPosition.z = sprite.z;
  21676. size = sprite.size * sprite.scale / viewportHeight;
  21677. scale.x = size * invAspect;
  21678. scale.y = size;
  21679. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21680. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21681. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21682. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21683. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21684. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21685. _renderer.setTexture( sprite.texture, 1 );
  21686. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21687. }
  21688. }
  21689. }
  21690. }
  21691. // restore gl
  21692. _gl.enable( _gl.CULL_FACE );
  21693. _gl.enable( _gl.DEPTH_TEST );
  21694. _gl.depthMask( true );
  21695. };
  21696. function createProgram ( shader, precision ) {
  21697. var program = _gl.createProgram();
  21698. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21699. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21700. var prefix = "precision " + precision + " float;\n";
  21701. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21702. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21703. _gl.compileShader( fragmentShader );
  21704. _gl.compileShader( vertexShader );
  21705. _gl.attachShader( program, fragmentShader );
  21706. _gl.attachShader( program, vertexShader );
  21707. _gl.linkProgram( program );
  21708. return program;
  21709. };
  21710. };
  21711. /**
  21712. * @author alteredq / http://alteredqualia.com/
  21713. */
  21714. THREE.ShadowMapPlugin = function () {
  21715. var _gl,
  21716. _renderer,
  21717. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21718. _frustum = new THREE.Frustum(),
  21719. _projScreenMatrix = new THREE.Matrix4(),
  21720. _min = new THREE.Vector3(),
  21721. _max = new THREE.Vector3(),
  21722. _matrixPosition = new THREE.Vector3();
  21723. this.init = function ( renderer ) {
  21724. _gl = renderer.context;
  21725. _renderer = renderer;
  21726. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21727. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21728. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21729. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21730. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21731. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21732. _depthMaterial._shadowPass = true;
  21733. _depthMaterialMorph._shadowPass = true;
  21734. _depthMaterialSkin._shadowPass = true;
  21735. _depthMaterialMorphSkin._shadowPass = true;
  21736. };
  21737. this.render = function ( scene, camera ) {
  21738. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21739. this.update( scene, camera );
  21740. };
  21741. this.update = function ( scene, camera ) {
  21742. var i, il, j, jl, n,
  21743. shadowMap, shadowMatrix, shadowCamera,
  21744. program, buffer, material,
  21745. webglObject, object, light,
  21746. renderList,
  21747. lights = [],
  21748. k = 0,
  21749. fog = null;
  21750. // set GL state for depth map
  21751. _gl.clearColor( 1, 1, 1, 1 );
  21752. _gl.disable( _gl.BLEND );
  21753. _gl.enable( _gl.CULL_FACE );
  21754. _gl.frontFace( _gl.CCW );
  21755. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21756. _gl.cullFace( _gl.FRONT );
  21757. } else {
  21758. _gl.cullFace( _gl.BACK );
  21759. }
  21760. _renderer.setDepthTest( true );
  21761. // preprocess lights
  21762. // - skip lights that are not casting shadows
  21763. // - create virtual lights for cascaded shadow maps
  21764. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21765. light = scene.__lights[ i ];
  21766. if ( ! light.castShadow ) continue;
  21767. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21768. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21769. var virtualLight;
  21770. if ( ! light.shadowCascadeArray[ n ] ) {
  21771. virtualLight = createVirtualLight( light, n );
  21772. virtualLight.originalCamera = camera;
  21773. var gyro = new THREE.Gyroscope();
  21774. gyro.position = light.shadowCascadeOffset;
  21775. gyro.add( virtualLight );
  21776. gyro.add( virtualLight.target );
  21777. camera.add( gyro );
  21778. light.shadowCascadeArray[ n ] = virtualLight;
  21779. console.log( "Created virtualLight", virtualLight );
  21780. } else {
  21781. virtualLight = light.shadowCascadeArray[ n ];
  21782. }
  21783. updateVirtualLight( light, n );
  21784. lights[ k ] = virtualLight;
  21785. k ++;
  21786. }
  21787. } else {
  21788. lights[ k ] = light;
  21789. k ++;
  21790. }
  21791. }
  21792. // render depth map
  21793. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21794. light = lights[ i ];
  21795. if ( ! light.shadowMap ) {
  21796. var shadowFilter = THREE.LinearFilter;
  21797. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21798. shadowFilter = THREE.NearestFilter;
  21799. }
  21800. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21801. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21802. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21803. light.shadowMatrix = new THREE.Matrix4();
  21804. }
  21805. if ( ! light.shadowCamera ) {
  21806. if ( light instanceof THREE.SpotLight ) {
  21807. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21808. } else if ( light instanceof THREE.DirectionalLight ) {
  21809. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21810. } else {
  21811. console.error( "Unsupported light type for shadow" );
  21812. continue;
  21813. }
  21814. scene.add( light.shadowCamera );
  21815. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21816. }
  21817. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21818. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21819. light.shadowCamera.add( light.cameraHelper );
  21820. }
  21821. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21822. updateShadowCamera( camera, light );
  21823. }
  21824. shadowMap = light.shadowMap;
  21825. shadowMatrix = light.shadowMatrix;
  21826. shadowCamera = light.shadowCamera;
  21827. shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
  21828. _matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
  21829. shadowCamera.lookAt( _matrixPosition );
  21830. shadowCamera.updateMatrixWorld();
  21831. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21832. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21833. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21834. // compute shadow matrix
  21835. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21836. 0.0, 0.5, 0.0, 0.5,
  21837. 0.0, 0.0, 0.5, 0.5,
  21838. 0.0, 0.0, 0.0, 1.0 );
  21839. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21840. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21841. // update camera matrices and frustum
  21842. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21843. _frustum.setFromMatrix( _projScreenMatrix );
  21844. // render shadow map
  21845. _renderer.setRenderTarget( shadowMap );
  21846. _renderer.clear();
  21847. // set object matrices & frustum culling
  21848. renderList = scene.__webglObjects;
  21849. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21850. webglObject = renderList[ j ];
  21851. object = webglObject.object;
  21852. webglObject.render = false;
  21853. if ( object.visible && object.castShadow ) {
  21854. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21855. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21856. webglObject.render = true;
  21857. }
  21858. }
  21859. }
  21860. // render regular objects
  21861. var objectMaterial, useMorphing, useSkinning;
  21862. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21863. webglObject = renderList[ j ];
  21864. if ( webglObject.render ) {
  21865. object = webglObject.object;
  21866. buffer = webglObject.buffer;
  21867. // culling is overriden globally for all objects
  21868. // while rendering depth map
  21869. // need to deal with MeshFaceMaterial somehow
  21870. // in that case just use the first of material.materials for now
  21871. // (proper solution would require to break objects by materials
  21872. // similarly to regular rendering and then set corresponding
  21873. // depth materials per each chunk instead of just once per object)
  21874. objectMaterial = getObjectMaterial( object );
  21875. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21876. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21877. if ( object.customDepthMaterial ) {
  21878. material = object.customDepthMaterial;
  21879. } else if ( useSkinning ) {
  21880. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21881. } else if ( useMorphing ) {
  21882. material = _depthMaterialMorph;
  21883. } else {
  21884. material = _depthMaterial;
  21885. }
  21886. if ( buffer instanceof THREE.BufferGeometry ) {
  21887. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21888. } else {
  21889. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21890. }
  21891. }
  21892. }
  21893. // set matrices and render immediate objects
  21894. renderList = scene.__webglObjectsImmediate;
  21895. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21896. webglObject = renderList[ j ];
  21897. object = webglObject.object;
  21898. if ( object.visible && object.castShadow ) {
  21899. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21900. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21901. }
  21902. }
  21903. }
  21904. // restore GL state
  21905. var clearColor = _renderer.getClearColor(),
  21906. clearAlpha = _renderer.getClearAlpha();
  21907. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21908. _gl.enable( _gl.BLEND );
  21909. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21910. _gl.cullFace( _gl.BACK );
  21911. }
  21912. };
  21913. function createVirtualLight( light, cascade ) {
  21914. var virtualLight = new THREE.DirectionalLight();
  21915. virtualLight.isVirtual = true;
  21916. virtualLight.onlyShadow = true;
  21917. virtualLight.castShadow = true;
  21918. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21919. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21920. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21921. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21922. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21923. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21924. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21925. virtualLight.shadowDarkness = light.shadowDarkness;
  21926. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21927. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21928. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21929. virtualLight.pointsWorld = [];
  21930. virtualLight.pointsFrustum = [];
  21931. var pointsWorld = virtualLight.pointsWorld,
  21932. pointsFrustum = virtualLight.pointsFrustum;
  21933. for ( var i = 0; i < 8; i ++ ) {
  21934. pointsWorld[ i ] = new THREE.Vector3();
  21935. pointsFrustum[ i ] = new THREE.Vector3();
  21936. }
  21937. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21938. var farZ = light.shadowCascadeFarZ[ cascade ];
  21939. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21940. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21941. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21942. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21943. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21944. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21945. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21946. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21947. return virtualLight;
  21948. }
  21949. // Synchronize virtual light with the original light
  21950. function updateVirtualLight( light, cascade ) {
  21951. var virtualLight = light.shadowCascadeArray[ cascade ];
  21952. virtualLight.position.copy( light.position );
  21953. virtualLight.target.position.copy( light.target.position );
  21954. virtualLight.lookAt( virtualLight.target );
  21955. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21956. virtualLight.shadowDarkness = light.shadowDarkness;
  21957. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21958. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21959. var farZ = light.shadowCascadeFarZ[ cascade ];
  21960. var pointsFrustum = virtualLight.pointsFrustum;
  21961. pointsFrustum[ 0 ].z = nearZ;
  21962. pointsFrustum[ 1 ].z = nearZ;
  21963. pointsFrustum[ 2 ].z = nearZ;
  21964. pointsFrustum[ 3 ].z = nearZ;
  21965. pointsFrustum[ 4 ].z = farZ;
  21966. pointsFrustum[ 5 ].z = farZ;
  21967. pointsFrustum[ 6 ].z = farZ;
  21968. pointsFrustum[ 7 ].z = farZ;
  21969. }
  21970. // Fit shadow camera's ortho frustum to camera frustum
  21971. function updateShadowCamera( camera, light ) {
  21972. var shadowCamera = light.shadowCamera,
  21973. pointsFrustum = light.pointsFrustum,
  21974. pointsWorld = light.pointsWorld;
  21975. _min.set( Infinity, Infinity, Infinity );
  21976. _max.set( -Infinity, -Infinity, -Infinity );
  21977. for ( var i = 0; i < 8; i ++ ) {
  21978. var p = pointsWorld[ i ];
  21979. p.copy( pointsFrustum[ i ] );
  21980. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21981. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21982. if ( p.x < _min.x ) _min.x = p.x;
  21983. if ( p.x > _max.x ) _max.x = p.x;
  21984. if ( p.y < _min.y ) _min.y = p.y;
  21985. if ( p.y > _max.y ) _max.y = p.y;
  21986. if ( p.z < _min.z ) _min.z = p.z;
  21987. if ( p.z > _max.z ) _max.z = p.z;
  21988. }
  21989. shadowCamera.left = _min.x;
  21990. shadowCamera.right = _max.x;
  21991. shadowCamera.top = _max.y;
  21992. shadowCamera.bottom = _min.y;
  21993. // can't really fit near/far
  21994. //shadowCamera.near = _min.z;
  21995. //shadowCamera.far = _max.z;
  21996. shadowCamera.updateProjectionMatrix();
  21997. }
  21998. // For the moment just ignore objects that have multiple materials with different animation methods
  21999. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  22000. function getObjectMaterial( object ) {
  22001. return object.material instanceof THREE.MeshFaceMaterial
  22002. ? object.material.materials[ 0 ]
  22003. : object.material;
  22004. };
  22005. };
  22006. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  22007. /**
  22008. * @author mikael emtinger / http://gomo.se/
  22009. * @author alteredq / http://alteredqualia.com/
  22010. */
  22011. THREE.SpritePlugin = function () {
  22012. var _gl, _renderer, _texture;
  22013. var vertices, faces, vertexBuffer, elementBuffer;
  22014. var program, attributes, uniforms;
  22015. this.init = function ( renderer ) {
  22016. _gl = renderer.context;
  22017. _renderer = renderer;
  22018. vertices = new Float32Array( [
  22019. - 0.5, - 0.5, 0, 0,
  22020. 0.5, - 0.5, 1, 0,
  22021. 0.5, 0.5, 1, 1,
  22022. - 0.5, 0.5, 0, 1
  22023. ] );
  22024. faces = new Uint16Array( [
  22025. 0, 1, 2,
  22026. 0, 2, 3
  22027. ] );
  22028. vertexBuffer = _gl.createBuffer();
  22029. elementBuffer = _gl.createBuffer();
  22030. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  22031. _gl.bufferData( _gl.ARRAY_BUFFER, vertices, _gl.STATIC_DRAW );
  22032. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  22033. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faces, _gl.STATIC_DRAW );
  22034. program = createProgram();
  22035. attributes = {
  22036. position: _gl.getAttribLocation ( program, 'position' ),
  22037. uv: _gl.getAttribLocation ( program, 'uv' )
  22038. };
  22039. uniforms = {
  22040. uvOffset: _gl.getUniformLocation( program, 'uvOffset' ),
  22041. uvScale: _gl.getUniformLocation( program, 'uvScale' ),
  22042. rotation: _gl.getUniformLocation( program, 'rotation' ),
  22043. scale: _gl.getUniformLocation( program, 'scale' ),
  22044. color: _gl.getUniformLocation( program, 'color' ),
  22045. map: _gl.getUniformLocation( program, 'map' ),
  22046. opacity: _gl.getUniformLocation( program, 'opacity' ),
  22047. modelViewMatrix: _gl.getUniformLocation( program, 'modelViewMatrix' ),
  22048. projectionMatrix: _gl.getUniformLocation( program, 'projectionMatrix' ),
  22049. fogType: _gl.getUniformLocation( program, 'fogType' ),
  22050. fogDensity: _gl.getUniformLocation( program, 'fogDensity' ),
  22051. fogNear: _gl.getUniformLocation( program, 'fogNear' ),
  22052. fogFar: _gl.getUniformLocation( program, 'fogFar' ),
  22053. fogColor: _gl.getUniformLocation( program, 'fogColor' ),
  22054. alphaTest: _gl.getUniformLocation( program, 'alphaTest' )
  22055. };
  22056. var canvas = document.createElement( 'canvas' );
  22057. canvas.width = 8;
  22058. canvas.height = 8;
  22059. var context = canvas.getContext( '2d' );
  22060. context.fillStyle = '#ffffff';
  22061. context.fillRect( 0, 0, canvas.width, canvas.height );
  22062. _texture = new THREE.Texture( canvas );
  22063. _texture.needsUpdate = true;
  22064. };
  22065. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  22066. var sprites = scene.__webglSprites,
  22067. nSprites = sprites.length;
  22068. if ( ! nSprites ) return;
  22069. // setup gl
  22070. _gl.useProgram( program );
  22071. _gl.enableVertexAttribArray( attributes.position );
  22072. _gl.enableVertexAttribArray( attributes.uv );
  22073. _gl.disable( _gl.CULL_FACE );
  22074. _gl.enable( _gl.BLEND );
  22075. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  22076. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  22077. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  22078. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  22079. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  22080. _gl.activeTexture( _gl.TEXTURE0 );
  22081. _gl.uniform1i( uniforms.map, 0 );
  22082. var oldFogType = 0;
  22083. var sceneFogType = 0;
  22084. var fog = scene.fog;
  22085. if ( fog ) {
  22086. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  22087. if ( fog instanceof THREE.Fog ) {
  22088. _gl.uniform1f( uniforms.fogNear, fog.near );
  22089. _gl.uniform1f( uniforms.fogFar, fog.far );
  22090. _gl.uniform1i( uniforms.fogType, 1 );
  22091. oldFogType = 1;
  22092. sceneFogType = 1;
  22093. } else if ( fog instanceof THREE.FogExp2 ) {
  22094. _gl.uniform1f( uniforms.fogDensity, fog.density );
  22095. _gl.uniform1i( uniforms.fogType, 2 );
  22096. oldFogType = 2;
  22097. sceneFogType = 2;
  22098. }
  22099. } else {
  22100. _gl.uniform1i( uniforms.fogType, 0 );
  22101. oldFogType = 0;
  22102. sceneFogType = 0;
  22103. }
  22104. // update positions and sort
  22105. var i, sprite, material, fogType, scale = [];
  22106. for( i = 0; i < nSprites; i ++ ) {
  22107. sprite = sprites[ i ];
  22108. material = sprite.material;
  22109. if ( sprite.visible === false ) continue;
  22110. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  22111. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  22112. }
  22113. sprites.sort( painterSortStable );
  22114. // render all sprites
  22115. for( i = 0; i < nSprites; i ++ ) {
  22116. sprite = sprites[ i ];
  22117. if ( sprite.visible === false ) continue;
  22118. material = sprite.material;
  22119. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  22120. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  22121. scale[ 0 ] = sprite.scale.x;
  22122. scale[ 1 ] = sprite.scale.y;
  22123. if ( scene.fog && material.fog ) {
  22124. fogType = sceneFogType;
  22125. } else {
  22126. fogType = 0;
  22127. }
  22128. if ( oldFogType !== fogType ) {
  22129. _gl.uniform1i( uniforms.fogType, fogType );
  22130. oldFogType = fogType;
  22131. }
  22132. if ( material.map !== null ) {
  22133. _gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  22134. _gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  22135. } else {
  22136. _gl.uniform2f( uniforms.uvOffset, 0, 0 );
  22137. _gl.uniform2f( uniforms.uvScale, 1, 1 );
  22138. }
  22139. _gl.uniform1f( uniforms.opacity, material.opacity );
  22140. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  22141. _gl.uniform1f( uniforms.rotation, material.rotation );
  22142. _gl.uniform2fv( uniforms.scale, scale );
  22143. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  22144. _renderer.setDepthTest( material.depthTest );
  22145. _renderer.setDepthWrite( material.depthWrite );
  22146. if ( material.map && material.map.image && material.map.image.width ) {
  22147. _renderer.setTexture( material.map, 0 );
  22148. } else {
  22149. _renderer.setTexture( _texture, 0 );
  22150. }
  22151. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22152. }
  22153. // restore gl
  22154. _gl.enable( _gl.CULL_FACE );
  22155. };
  22156. function createProgram () {
  22157. var program = _gl.createProgram();
  22158. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  22159. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  22160. _gl.shaderSource( vertexShader, [
  22161. 'precision ' + _renderer.getPrecision() + ' float;',
  22162. 'uniform mat4 modelViewMatrix;',
  22163. 'uniform mat4 projectionMatrix;',
  22164. 'uniform float rotation;',
  22165. 'uniform vec2 scale;',
  22166. 'uniform vec2 uvOffset;',
  22167. 'uniform vec2 uvScale;',
  22168. 'attribute vec2 position;',
  22169. 'attribute vec2 uv;',
  22170. 'varying vec2 vUV;',
  22171. 'void main() {',
  22172. 'vUV = uvOffset + uv * uvScale;',
  22173. 'vec2 alignedPosition = position * scale;',
  22174. 'vec2 rotatedPosition;',
  22175. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  22176. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  22177. 'vec4 finalPosition;',
  22178. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  22179. 'finalPosition.xy += rotatedPosition;',
  22180. 'finalPosition = projectionMatrix * finalPosition;',
  22181. 'gl_Position = finalPosition;',
  22182. '}'
  22183. ].join( '\n' ) );
  22184. _gl.shaderSource( fragmentShader, [
  22185. 'precision ' + _renderer.getPrecision() + ' float;',
  22186. 'uniform vec3 color;',
  22187. 'uniform sampler2D map;',
  22188. 'uniform float opacity;',
  22189. 'uniform int fogType;',
  22190. 'uniform vec3 fogColor;',
  22191. 'uniform float fogDensity;',
  22192. 'uniform float fogNear;',
  22193. 'uniform float fogFar;',
  22194. 'uniform float alphaTest;',
  22195. 'varying vec2 vUV;',
  22196. 'void main() {',
  22197. 'vec4 texture = texture2D( map, vUV );',
  22198. 'if ( texture.a < alphaTest ) discard;',
  22199. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  22200. 'if ( fogType > 0 ) {',
  22201. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  22202. 'float fogFactor = 0.0;',
  22203. 'if ( fogType == 1 ) {',
  22204. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  22205. '} else {',
  22206. 'const float LOG2 = 1.442695;',
  22207. 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  22208. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  22209. '}',
  22210. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  22211. '}',
  22212. '}'
  22213. ].join( '\n' ) );
  22214. _gl.compileShader( vertexShader );
  22215. _gl.compileShader( fragmentShader );
  22216. _gl.attachShader( program, vertexShader );
  22217. _gl.attachShader( program, fragmentShader );
  22218. _gl.linkProgram( program );
  22219. return program;
  22220. };
  22221. function painterSortStable ( a, b ) {
  22222. if ( a.z !== b.z ) {
  22223. return b.z - a.z;
  22224. } else {
  22225. return b.id - a.id;
  22226. }
  22227. };
  22228. };
  22229. /**
  22230. * @author alteredq / http://alteredqualia.com/
  22231. */
  22232. THREE.DepthPassPlugin = function () {
  22233. this.enabled = false;
  22234. this.renderTarget = null;
  22235. var _gl,
  22236. _renderer,
  22237. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  22238. _frustum = new THREE.Frustum(),
  22239. _projScreenMatrix = new THREE.Matrix4();
  22240. this.init = function ( renderer ) {
  22241. _gl = renderer.context;
  22242. _renderer = renderer;
  22243. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  22244. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  22245. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  22246. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  22247. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  22248. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  22249. _depthMaterial._shadowPass = true;
  22250. _depthMaterialMorph._shadowPass = true;
  22251. _depthMaterialSkin._shadowPass = true;
  22252. _depthMaterialMorphSkin._shadowPass = true;
  22253. };
  22254. this.render = function ( scene, camera ) {
  22255. if ( ! this.enabled ) return;
  22256. this.update( scene, camera );
  22257. };
  22258. this.update = function ( scene, camera ) {
  22259. var i, il, j, jl, n,
  22260. program, buffer, material,
  22261. webglObject, object, light,
  22262. renderList,
  22263. fog = null;
  22264. // set GL state for depth map
  22265. _gl.clearColor( 1, 1, 1, 1 );
  22266. _gl.disable( _gl.BLEND );
  22267. _renderer.setDepthTest( true );
  22268. // update scene
  22269. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  22270. // update camera matrices and frustum
  22271. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  22272. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  22273. _frustum.setFromMatrix( _projScreenMatrix );
  22274. // render depth map
  22275. _renderer.setRenderTarget( this.renderTarget );
  22276. _renderer.clear();
  22277. // set object matrices & frustum culling
  22278. renderList = scene.__webglObjects;
  22279. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22280. webglObject = renderList[ j ];
  22281. object = webglObject.object;
  22282. webglObject.render = false;
  22283. if ( object.visible ) {
  22284. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  22285. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22286. webglObject.render = true;
  22287. }
  22288. }
  22289. }
  22290. // render regular objects
  22291. var objectMaterial, useMorphing, useSkinning;
  22292. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22293. webglObject = renderList[ j ];
  22294. if ( webglObject.render ) {
  22295. object = webglObject.object;
  22296. buffer = webglObject.buffer;
  22297. // todo: create proper depth material for particles
  22298. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  22299. objectMaterial = getObjectMaterial( object );
  22300. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  22301. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  22302. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  22303. if ( object.customDepthMaterial ) {
  22304. material = object.customDepthMaterial;
  22305. } else if ( useSkinning ) {
  22306. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  22307. } else if ( useMorphing ) {
  22308. material = _depthMaterialMorph;
  22309. } else {
  22310. material = _depthMaterial;
  22311. }
  22312. if ( buffer instanceof THREE.BufferGeometry ) {
  22313. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  22314. } else {
  22315. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  22316. }
  22317. }
  22318. }
  22319. // set matrices and render immediate objects
  22320. renderList = scene.__webglObjectsImmediate;
  22321. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22322. webglObject = renderList[ j ];
  22323. object = webglObject.object;
  22324. if ( object.visible ) {
  22325. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22326. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  22327. }
  22328. }
  22329. // restore GL state
  22330. var clearColor = _renderer.getClearColor(),
  22331. clearAlpha = _renderer.getClearAlpha();
  22332. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  22333. _gl.enable( _gl.BLEND );
  22334. };
  22335. // For the moment just ignore objects that have multiple materials with different animation methods
  22336. // Only the first material will be taken into account for deciding which depth material to use
  22337. function getObjectMaterial( object ) {
  22338. return object.material instanceof THREE.MeshFaceMaterial
  22339. ? object.material.materials[ 0 ]
  22340. : object.material;
  22341. };
  22342. };
  22343. /**
  22344. * @author mikael emtinger / http://gomo.se/
  22345. */
  22346. THREE.ShaderFlares = {
  22347. 'lensFlareVertexTexture': {
  22348. vertexShader: [
  22349. "uniform lowp int renderType;",
  22350. "uniform vec3 screenPosition;",
  22351. "uniform vec2 scale;",
  22352. "uniform float rotation;",
  22353. "uniform sampler2D occlusionMap;",
  22354. "attribute vec2 position;",
  22355. "attribute vec2 uv;",
  22356. "varying vec2 vUV;",
  22357. "varying float vVisibility;",
  22358. "void main() {",
  22359. "vUV = uv;",
  22360. "vec2 pos = position;",
  22361. "if( renderType == 2 ) {",
  22362. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  22363. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  22364. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  22365. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  22366. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  22367. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  22368. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  22369. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  22370. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  22371. "vVisibility = visibility.r / 9.0;",
  22372. "vVisibility *= 1.0 - visibility.g / 9.0;",
  22373. "vVisibility *= visibility.b / 9.0;",
  22374. "vVisibility *= 1.0 - visibility.a / 9.0;",
  22375. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22376. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22377. "}",
  22378. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22379. "}"
  22380. ].join( "\n" ),
  22381. fragmentShader: [
  22382. "uniform lowp int renderType;",
  22383. "uniform sampler2D map;",
  22384. "uniform float opacity;",
  22385. "uniform vec3 color;",
  22386. "varying vec2 vUV;",
  22387. "varying float vVisibility;",
  22388. "void main() {",
  22389. // pink square
  22390. "if( renderType == 0 ) {",
  22391. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  22392. // restore
  22393. "} else if( renderType == 1 ) {",
  22394. "gl_FragColor = texture2D( map, vUV );",
  22395. // flare
  22396. "} else {",
  22397. "vec4 texture = texture2D( map, vUV );",
  22398. "texture.a *= opacity * vVisibility;",
  22399. "gl_FragColor = texture;",
  22400. "gl_FragColor.rgb *= color;",
  22401. "}",
  22402. "}"
  22403. ].join( "\n" )
  22404. },
  22405. 'lensFlare': {
  22406. vertexShader: [
  22407. "uniform lowp int renderType;",
  22408. "uniform vec3 screenPosition;",
  22409. "uniform vec2 scale;",
  22410. "uniform float rotation;",
  22411. "attribute vec2 position;",
  22412. "attribute vec2 uv;",
  22413. "varying vec2 vUV;",
  22414. "void main() {",
  22415. "vUV = uv;",
  22416. "vec2 pos = position;",
  22417. "if( renderType == 2 ) {",
  22418. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22419. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22420. "}",
  22421. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22422. "}"
  22423. ].join( "\n" ),
  22424. fragmentShader: [
  22425. "precision mediump float;",
  22426. "uniform lowp int renderType;",
  22427. "uniform sampler2D map;",
  22428. "uniform sampler2D occlusionMap;",
  22429. "uniform float opacity;",
  22430. "uniform vec3 color;",
  22431. "varying vec2 vUV;",
  22432. "void main() {",
  22433. // pink square
  22434. "if( renderType == 0 ) {",
  22435. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  22436. // restore
  22437. "} else if( renderType == 1 ) {",
  22438. "gl_FragColor = texture2D( map, vUV );",
  22439. // flare
  22440. "} else {",
  22441. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  22442. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  22443. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  22444. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  22445. "visibility = ( 1.0 - visibility / 4.0 );",
  22446. "vec4 texture = texture2D( map, vUV );",
  22447. "texture.a *= opacity * visibility;",
  22448. "gl_FragColor = texture;",
  22449. "gl_FragColor.rgb *= color;",
  22450. "}",
  22451. "}"
  22452. ].join( "\n" )
  22453. }
  22454. };