three.js 811 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. var THREE = THREE || { REVISION: '51dev' };
  5. if ( self.console === undefined ) {
  6. self.console = {
  7. info: function () {},
  8. log: function () {},
  9. debug: function () {},
  10. warn: function () {},
  11. error: function () {}
  12. };
  13. }
  14. if ( self.Int32Array === undefined ) {
  15. self.Int32Array = Array;
  16. self.Float32Array = Array;
  17. }
  18. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  19. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  20. // requestAnimationFrame polyfill by Erik Möller
  21. // fixes from Paul Irish and Tino Zijdel
  22. ( function () {
  23. var lastTime = 0;
  24. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  25. for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) {
  26. window.requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ];
  27. window.cancelAnimationFrame = window[ vendors[ x ] + 'CancelAnimationFrame' ] || window[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  28. }
  29. if ( window.requestAnimationFrame === undefined ) {
  30. window.requestAnimationFrame = function ( callback, element ) {
  31. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  32. var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  33. lastTime = currTime + timeToCall;
  34. return id;
  35. };
  36. }
  37. if ( window.cancelAnimationFrame === undefined ) {
  38. window.cancelAnimationFrame = function ( id ) { clearTimeout( id ); };
  39. }
  40. }() );
  41. // MATERIAL CONSTANTS
  42. // side
  43. THREE.FrontSide = 0;
  44. THREE.BackSide = 1;
  45. THREE.DoubleSide = 2;
  46. // shading
  47. THREE.NoShading = 0;
  48. THREE.FlatShading = 1;
  49. THREE.SmoothShading = 2;
  50. // colors
  51. THREE.NoColors = 0;
  52. THREE.FaceColors = 1;
  53. THREE.VertexColors = 2;
  54. // blending modes
  55. THREE.NoBlending = 0;
  56. THREE.NormalBlending = 1;
  57. THREE.AdditiveBlending = 2;
  58. THREE.SubtractiveBlending = 3;
  59. THREE.MultiplyBlending = 4;
  60. THREE.CustomBlending = 5;
  61. // custom blending equations
  62. // (numbers start from 100 not to clash with other
  63. // mappings to OpenGL constants defined in Texture.js)
  64. THREE.AddEquation = 100;
  65. THREE.SubtractEquation = 101;
  66. THREE.ReverseSubtractEquation = 102;
  67. // custom blending destination factors
  68. THREE.ZeroFactor = 200;
  69. THREE.OneFactor = 201;
  70. THREE.SrcColorFactor = 202;
  71. THREE.OneMinusSrcColorFactor = 203;
  72. THREE.SrcAlphaFactor = 204;
  73. THREE.OneMinusSrcAlphaFactor = 205;
  74. THREE.DstAlphaFactor = 206;
  75. THREE.OneMinusDstAlphaFactor = 207;
  76. // custom blending source factors
  77. //THREE.ZeroFactor = 200;
  78. //THREE.OneFactor = 201;
  79. //THREE.SrcAlphaFactor = 204;
  80. //THREE.OneMinusSrcAlphaFactor = 205;
  81. //THREE.DstAlphaFactor = 206;
  82. //THREE.OneMinusDstAlphaFactor = 207;
  83. THREE.DstColorFactor = 208;
  84. THREE.OneMinusDstColorFactor = 209;
  85. THREE.SrcAlphaSaturateFactor = 210;
  86. // TEXTURE CONSTANTS
  87. THREE.MultiplyOperation = 0;
  88. THREE.MixOperation = 1;
  89. // Mapping modes
  90. THREE.UVMapping = function () {};
  91. THREE.CubeReflectionMapping = function () {};
  92. THREE.CubeRefractionMapping = function () {};
  93. THREE.SphericalReflectionMapping = function () {};
  94. THREE.SphericalRefractionMapping = function () {};
  95. // Wrapping modes
  96. THREE.RepeatWrapping = 1000;
  97. THREE.ClampToEdgeWrapping = 1001;
  98. THREE.MirroredRepeatWrapping = 1002;
  99. // Filters
  100. THREE.NearestFilter = 1003;
  101. THREE.NearestMipMapNearestFilter = 1004;
  102. THREE.NearestMipMapLinearFilter = 1005;
  103. THREE.LinearFilter = 1006;
  104. THREE.LinearMipMapNearestFilter = 1007;
  105. THREE.LinearMipMapLinearFilter = 1008;
  106. // Data types
  107. THREE.UnsignedByteType = 1009;
  108. THREE.ByteType = 1010;
  109. THREE.ShortType = 1011;
  110. THREE.UnsignedShortType = 1012;
  111. THREE.IntType = 1013;
  112. THREE.UnsignedIntType = 1014;
  113. THREE.FloatType = 1015;
  114. // Pixel types
  115. //THREE.UnsignedByteType = 1009;
  116. THREE.UnsignedShort4444Type = 1016;
  117. THREE.UnsignedShort5551Type = 1017;
  118. THREE.UnsignedShort565Type = 1018;
  119. // Pixel formats
  120. THREE.AlphaFormat = 1019;
  121. THREE.RGBFormat = 1020;
  122. THREE.RGBAFormat = 1021;
  123. THREE.LuminanceFormat = 1022;
  124. THREE.LuminanceAlphaFormat = 1023;
  125. /**
  126. * @author alteredq / http://alteredqualia.com/
  127. */
  128. THREE.Clock = function ( autoStart ) {
  129. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  130. this.startTime = 0;
  131. this.oldTime = 0;
  132. this.elapsedTime = 0;
  133. this.running = false;
  134. };
  135. THREE.Clock.prototype.start = function () {
  136. this.startTime = Date.now();
  137. this.oldTime = this.startTime;
  138. this.running = true;
  139. };
  140. THREE.Clock.prototype.stop = function () {
  141. this.getElapsedTime();
  142. this.running = false;
  143. };
  144. THREE.Clock.prototype.getElapsedTime = function () {
  145. this.elapsedTime += this.getDelta();
  146. return this.elapsedTime;
  147. };
  148. THREE.Clock.prototype.getDelta = function () {
  149. var diff = 0;
  150. if ( this.autoStart && ! this.running ) {
  151. this.start();
  152. }
  153. if ( this.running ) {
  154. var newTime = Date.now();
  155. diff = 0.001 * ( newTime - this.oldTime );
  156. this.oldTime = newTime;
  157. this.elapsedTime += diff;
  158. }
  159. return diff;
  160. };/**
  161. * @author mrdoob / http://mrdoob.com/
  162. */
  163. THREE.Color = function ( hex ) {
  164. if ( hex !== undefined ) this.setHex( hex );
  165. return this;
  166. };
  167. THREE.Color.prototype = {
  168. constructor: THREE.Color,
  169. r: 1, g: 1, b: 1,
  170. copy: function ( color ) {
  171. this.r = color.r;
  172. this.g = color.g;
  173. this.b = color.b;
  174. return this;
  175. },
  176. copyGammaToLinear: function ( color ) {
  177. this.r = color.r * color.r;
  178. this.g = color.g * color.g;
  179. this.b = color.b * color.b;
  180. return this;
  181. },
  182. copyLinearToGamma: function ( color ) {
  183. this.r = Math.sqrt( color.r );
  184. this.g = Math.sqrt( color.g );
  185. this.b = Math.sqrt( color.b );
  186. return this;
  187. },
  188. convertGammaToLinear: function () {
  189. var r = this.r, g = this.g, b = this.b;
  190. this.r = r * r;
  191. this.g = g * g;
  192. this.b = b * b;
  193. return this;
  194. },
  195. convertLinearToGamma: function () {
  196. this.r = Math.sqrt( this.r );
  197. this.g = Math.sqrt( this.g );
  198. this.b = Math.sqrt( this.b );
  199. return this;
  200. },
  201. setRGB: function ( r, g, b ) {
  202. this.r = r;
  203. this.g = g;
  204. this.b = b;
  205. return this;
  206. },
  207. setHSV: function ( h, s, v ) {
  208. // based on MochiKit implementation by Bob Ippolito
  209. // h,s,v ranges are < 0.0 - 1.0 >
  210. var i, f, p, q, t;
  211. if ( v === 0 ) {
  212. this.r = this.g = this.b = 0;
  213. } else {
  214. i = Math.floor( h * 6 );
  215. f = ( h * 6 ) - i;
  216. p = v * ( 1 - s );
  217. q = v * ( 1 - ( s * f ) );
  218. t = v * ( 1 - ( s * ( 1 - f ) ) );
  219. if ( i === 0 ) {
  220. this.r = v;
  221. this.g = t;
  222. this.b = p;
  223. } else if ( i === 1 ) {
  224. this.r = q;
  225. this.g = v;
  226. this.b = p;
  227. } else if ( i === 2 ) {
  228. this.r = p;
  229. this.g = v;
  230. this.b = t;
  231. } else if ( i === 3 ) {
  232. this.r = p;
  233. this.g = q;
  234. this.b = v;
  235. } else if ( i === 4 ) {
  236. this.r = t;
  237. this.g = p;
  238. this.b = v;
  239. } else if ( i === 5 ) {
  240. this.r = v;
  241. this.g = p;
  242. this.b = q;
  243. }
  244. }
  245. return this;
  246. },
  247. setHex: function ( hex ) {
  248. hex = Math.floor( hex );
  249. this.r = ( hex >> 16 & 255 ) / 255;
  250. this.g = ( hex >> 8 & 255 ) / 255;
  251. this.b = ( hex & 255 ) / 255;
  252. return this;
  253. },
  254. lerpSelf: function ( color, alpha ) {
  255. this.r += ( color.r - this.r ) * alpha;
  256. this.g += ( color.g - this.g ) * alpha;
  257. this.b += ( color.b - this.b ) * alpha;
  258. return this;
  259. },
  260. getHex: function () {
  261. return Math.floor( this.r * 255 ) << 16 ^ Math.floor( this.g * 255 ) << 8 ^ Math.floor( this.b * 255 );
  262. },
  263. getContextStyle: function () {
  264. return 'rgb(' + Math.floor( this.r * 255 ) + ',' + Math.floor( this.g * 255 ) + ',' + Math.floor( this.b * 255 ) + ')';
  265. },
  266. clone: function () {
  267. return new THREE.Color().setRGB( this.r, this.g, this.b );
  268. }
  269. };
  270. /**
  271. * @author mrdoob / http://mrdoob.com/
  272. * @author philogb / http://blog.thejit.org/
  273. * @author egraether / http://egraether.com/
  274. * @author zz85 / http://www.lab4games.net/zz85/blog
  275. */
  276. THREE.Vector2 = function ( x, y ) {
  277. this.x = x || 0;
  278. this.y = y || 0;
  279. };
  280. THREE.Vector2.prototype = {
  281. constructor: THREE.Vector2,
  282. set: function ( x, y ) {
  283. this.x = x;
  284. this.y = y;
  285. return this;
  286. },
  287. copy: function ( v ) {
  288. this.x = v.x;
  289. this.y = v.y;
  290. return this;
  291. },
  292. add: function ( a, b ) {
  293. this.x = a.x + b.x;
  294. this.y = a.y + b.y;
  295. return this;
  296. },
  297. addSelf: function ( v ) {
  298. this.x += v.x;
  299. this.y += v.y;
  300. return this;
  301. },
  302. sub: function ( a, b ) {
  303. this.x = a.x - b.x;
  304. this.y = a.y - b.y;
  305. return this;
  306. },
  307. subSelf: function ( v ) {
  308. this.x -= v.x;
  309. this.y -= v.y;
  310. return this;
  311. },
  312. multiplyScalar: function ( s ) {
  313. this.x *= s;
  314. this.y *= s;
  315. return this;
  316. },
  317. divideScalar: function ( s ) {
  318. if ( s ) {
  319. this.x /= s;
  320. this.y /= s;
  321. } else {
  322. this.set( 0, 0 );
  323. }
  324. return this;
  325. },
  326. negate: function() {
  327. return this.multiplyScalar( - 1 );
  328. },
  329. dot: function ( v ) {
  330. return this.x * v.x + this.y * v.y;
  331. },
  332. lengthSq: function () {
  333. return this.x * this.x + this.y * this.y;
  334. },
  335. length: function () {
  336. return Math.sqrt( this.lengthSq() );
  337. },
  338. normalize: function () {
  339. return this.divideScalar( this.length() );
  340. },
  341. distanceTo: function ( v ) {
  342. return Math.sqrt( this.distanceToSquared( v ) );
  343. },
  344. distanceToSquared: function ( v ) {
  345. var dx = this.x - v.x, dy = this.y - v.y;
  346. return dx * dx + dy * dy;
  347. },
  348. setLength: function ( l ) {
  349. return this.normalize().multiplyScalar( l );
  350. },
  351. lerpSelf: function ( v, alpha ) {
  352. this.x += ( v.x - this.x ) * alpha;
  353. this.y += ( v.y - this.y ) * alpha;
  354. return this;
  355. },
  356. equals: function( v ) {
  357. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  358. },
  359. isZero: function () {
  360. return ( this.lengthSq() < 0.0001 /* almostZero */ );
  361. },
  362. clone: function () {
  363. return new THREE.Vector2( this.x, this.y );
  364. }
  365. };
  366. /**
  367. * @author mrdoob / http://mrdoob.com/
  368. * @author kile / http://kile.stravaganza.org/
  369. * @author philogb / http://blog.thejit.org/
  370. * @author mikael emtinger / http://gomo.se/
  371. * @author egraether / http://egraether.com/
  372. * @author WestLangley / http://github.com/WestLangley
  373. */
  374. THREE.Vector3 = function ( x, y, z ) {
  375. this.x = x || 0;
  376. this.y = y || 0;
  377. this.z = z || 0;
  378. };
  379. THREE.Vector3.prototype = {
  380. constructor: THREE.Vector3,
  381. set: function ( x, y, z ) {
  382. this.x = x;
  383. this.y = y;
  384. this.z = z;
  385. return this;
  386. },
  387. setX: function ( x ) {
  388. this.x = x;
  389. return this;
  390. },
  391. setY: function ( y ) {
  392. this.y = y;
  393. return this;
  394. },
  395. setZ: function ( z ) {
  396. this.z = z;
  397. return this;
  398. },
  399. copy: function ( v ) {
  400. this.x = v.x;
  401. this.y = v.y;
  402. this.z = v.z;
  403. return this;
  404. },
  405. add: function ( a, b ) {
  406. this.x = a.x + b.x;
  407. this.y = a.y + b.y;
  408. this.z = a.z + b.z;
  409. return this;
  410. },
  411. addSelf: function ( v ) {
  412. this.x += v.x;
  413. this.y += v.y;
  414. this.z += v.z;
  415. return this;
  416. },
  417. addScalar: function ( s ) {
  418. this.x += s;
  419. this.y += s;
  420. this.z += s;
  421. return this;
  422. },
  423. sub: function ( a, b ) {
  424. this.x = a.x - b.x;
  425. this.y = a.y - b.y;
  426. this.z = a.z - b.z;
  427. return this;
  428. },
  429. subSelf: function ( v ) {
  430. this.x -= v.x;
  431. this.y -= v.y;
  432. this.z -= v.z;
  433. return this;
  434. },
  435. multiply: function ( a, b ) {
  436. this.x = a.x * b.x;
  437. this.y = a.y * b.y;
  438. this.z = a.z * b.z;
  439. return this;
  440. },
  441. multiplySelf: function ( v ) {
  442. this.x *= v.x;
  443. this.y *= v.y;
  444. this.z *= v.z;
  445. return this;
  446. },
  447. multiplyScalar: function ( s ) {
  448. this.x *= s;
  449. this.y *= s;
  450. this.z *= s;
  451. return this;
  452. },
  453. divideSelf: function ( v ) {
  454. this.x /= v.x;
  455. this.y /= v.y;
  456. this.z /= v.z;
  457. return this;
  458. },
  459. divideScalar: function ( s ) {
  460. if ( s ) {
  461. this.x /= s;
  462. this.y /= s;
  463. this.z /= s;
  464. } else {
  465. this.x = 0;
  466. this.y = 0;
  467. this.z = 0;
  468. }
  469. return this;
  470. },
  471. negate: function() {
  472. return this.multiplyScalar( - 1 );
  473. },
  474. dot: function ( v ) {
  475. return this.x * v.x + this.y * v.y + this.z * v.z;
  476. },
  477. lengthSq: function () {
  478. return this.x * this.x + this.y * this.y + this.z * this.z;
  479. },
  480. length: function () {
  481. return Math.sqrt( this.lengthSq() );
  482. },
  483. lengthManhattan: function () {
  484. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  485. },
  486. normalize: function () {
  487. return this.divideScalar( this.length() );
  488. },
  489. setLength: function ( l ) {
  490. return this.normalize().multiplyScalar( l );
  491. },
  492. lerpSelf: function ( v, alpha ) {
  493. this.x += ( v.x - this.x ) * alpha;
  494. this.y += ( v.y - this.y ) * alpha;
  495. this.z += ( v.z - this.z ) * alpha;
  496. return this;
  497. },
  498. cross: function ( a, b ) {
  499. this.x = a.y * b.z - a.z * b.y;
  500. this.y = a.z * b.x - a.x * b.z;
  501. this.z = a.x * b.y - a.y * b.x;
  502. return this;
  503. },
  504. crossSelf: function ( v ) {
  505. var x = this.x, y = this.y, z = this.z;
  506. this.x = y * v.z - z * v.y;
  507. this.y = z * v.x - x * v.z;
  508. this.z = x * v.y - y * v.x;
  509. return this;
  510. },
  511. distanceTo: function ( v ) {
  512. return Math.sqrt( this.distanceToSquared( v ) );
  513. },
  514. distanceToSquared: function ( v ) {
  515. return new THREE.Vector3().sub( this, v ).lengthSq();
  516. },
  517. getPositionFromMatrix: function ( m ) {
  518. this.x = m.elements[12];
  519. this.y = m.elements[13];
  520. this.z = m.elements[14];
  521. return this;
  522. },
  523. setEulerFromRotationMatrix: function ( m, order ) {
  524. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  525. // clamp, to handle numerical problems
  526. function clamp( x ) {
  527. return Math.min( Math.max( x, -1 ), 1 );
  528. }
  529. var te = m.elements;
  530. var m11 = te[0], m12 = te[4], m13 = te[8];
  531. var m21 = te[1], m22 = te[5], m23 = te[9];
  532. var m31 = te[2], m32 = te[6], m33 = te[10];
  533. if ( order === undefined || order === 'XYZ' ) {
  534. this.y = Math.asin( clamp( m13 ) );
  535. if ( Math.abs( m13 ) < 0.99999 ) {
  536. this.x = Math.atan2( - m23, m33 );
  537. this.z = Math.atan2( - m12, m11 );
  538. } else {
  539. this.x = Math.atan2( m21, m22 );
  540. this.z = 0;
  541. }
  542. } else if ( order === 'YXZ' ) {
  543. this.x = Math.asin( - clamp( m23 ) );
  544. if ( Math.abs( m23 ) < 0.99999 ) {
  545. this.y = Math.atan2( m13, m33 );
  546. this.z = Math.atan2( m21, m22 );
  547. } else {
  548. this.y = Math.atan2( - m31, m11 );
  549. this.z = 0;
  550. }
  551. } else if ( order === 'ZXY' ) {
  552. this.x = Math.asin( clamp( m32 ) );
  553. if ( Math.abs( m32 ) < 0.99999 ) {
  554. this.y = Math.atan2( - m31, m33 );
  555. this.z = Math.atan2( - m12, m22 );
  556. } else {
  557. this.y = 0;
  558. this.z = Math.atan2( m13, m11 );
  559. }
  560. } else if ( order === 'ZYX' ) {
  561. this.y = Math.asin( - clamp( m31 ) );
  562. if ( Math.abs( m31 ) < 0.99999 ) {
  563. this.x = Math.atan2( m32, m33 );
  564. this.z = Math.atan2( m21, m11 );
  565. } else {
  566. this.x = 0;
  567. this.z = Math.atan2( - m12, m22 );
  568. }
  569. } else if ( order === 'YZX' ) {
  570. this.z = Math.asin( clamp( m21 ) );
  571. if ( Math.abs( m21 ) < 0.99999 ) {
  572. this.x = Math.atan2( - m23, m22 );
  573. this.y = Math.atan2( - m31, m11 );
  574. } else {
  575. this.x = 0;
  576. this.y = Math.atan2( m31, m33 );
  577. }
  578. } else if ( order === 'XZY' ) {
  579. this.z = Math.asin( - clamp( m12 ) );
  580. if ( Math.abs( m12 ) < 0.99999 ) {
  581. this.x = Math.atan2( m32, m22 );
  582. this.y = Math.atan2( m13, m11 );
  583. } else {
  584. this.x = Math.atan2( - m13, m33 );
  585. this.y = 0;
  586. }
  587. }
  588. return this;
  589. },
  590. setEulerFromQuaternion: function ( q, order ) {
  591. // q is assumed to be normalized
  592. // clamp, to handle numerical problems
  593. function clamp( x ) {
  594. return Math.min( Math.max( x, -1 ), 1 );
  595. }
  596. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  597. var sqx = q.x * q.x;
  598. var sqy = q.y * q.y;
  599. var sqz = q.z * q.z;
  600. var sqw = q.w * q.w;
  601. if ( order === undefined || order === 'XYZ' ) {
  602. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  603. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  604. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  605. } else if ( order === 'YXZ' ) {
  606. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  607. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  608. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  609. } else if ( order === 'ZXY' ) {
  610. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  611. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  612. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  613. } else if ( order === 'ZYX' ) {
  614. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  615. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  616. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  617. } else if ( order === 'YZX' ) {
  618. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  619. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  620. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  621. } else if ( order === 'XZY' ) {
  622. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  623. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  624. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  625. }
  626. return this;
  627. },
  628. getScaleFromMatrix: function ( m ) {
  629. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  630. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  631. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  632. this.x = sx;
  633. this.y = sy;
  634. this.z = sz;
  635. return this;
  636. },
  637. equals: function ( v ) {
  638. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  639. },
  640. isZero: function () {
  641. return ( this.lengthSq() < 0.0001 /* almostZero */ );
  642. },
  643. clone: function () {
  644. return new THREE.Vector3( this.x, this.y, this.z );
  645. }
  646. };
  647. /**
  648. * @author supereggbert / http://www.paulbrunt.co.uk/
  649. * @author philogb / http://blog.thejit.org/
  650. * @author mikael emtinger / http://gomo.se/
  651. * @author egraether / http://egraether.com/
  652. * @author WestLangley / http://github.com/WestLangley
  653. */
  654. THREE.Vector4 = function ( x, y, z, w ) {
  655. this.x = x || 0;
  656. this.y = y || 0;
  657. this.z = z || 0;
  658. this.w = ( w !== undefined ) ? w : 1;
  659. };
  660. THREE.Vector4.prototype = {
  661. constructor: THREE.Vector4,
  662. set: function ( x, y, z, w ) {
  663. this.x = x;
  664. this.y = y;
  665. this.z = z;
  666. this.w = w;
  667. return this;
  668. },
  669. copy: function ( v ) {
  670. this.x = v.x;
  671. this.y = v.y;
  672. this.z = v.z;
  673. this.w = ( v.w !== undefined ) ? v.w : 1;
  674. return this;
  675. },
  676. add: function ( a, b ) {
  677. this.x = a.x + b.x;
  678. this.y = a.y + b.y;
  679. this.z = a.z + b.z;
  680. this.w = a.w + b.w;
  681. return this;
  682. },
  683. addSelf: function ( v ) {
  684. this.x += v.x;
  685. this.y += v.y;
  686. this.z += v.z;
  687. this.w += v.w;
  688. return this;
  689. },
  690. sub: function ( a, b ) {
  691. this.x = a.x - b.x;
  692. this.y = a.y - b.y;
  693. this.z = a.z - b.z;
  694. this.w = a.w - b.w;
  695. return this;
  696. },
  697. subSelf: function ( v ) {
  698. this.x -= v.x;
  699. this.y -= v.y;
  700. this.z -= v.z;
  701. this.w -= v.w;
  702. return this;
  703. },
  704. multiplyScalar: function ( s ) {
  705. this.x *= s;
  706. this.y *= s;
  707. this.z *= s;
  708. this.w *= s;
  709. return this;
  710. },
  711. divideScalar: function ( s ) {
  712. if ( s ) {
  713. this.x /= s;
  714. this.y /= s;
  715. this.z /= s;
  716. this.w /= s;
  717. } else {
  718. this.x = 0;
  719. this.y = 0;
  720. this.z = 0;
  721. this.w = 1;
  722. }
  723. return this;
  724. },
  725. negate: function() {
  726. return this.multiplyScalar( -1 );
  727. },
  728. dot: function ( v ) {
  729. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  730. },
  731. lengthSq: function () {
  732. return this.dot( this );
  733. },
  734. length: function () {
  735. return Math.sqrt( this.lengthSq() );
  736. },
  737. lengthManhattan: function () {
  738. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  739. },
  740. normalize: function () {
  741. return this.divideScalar( this.length() );
  742. },
  743. setLength: function ( l ) {
  744. return this.normalize().multiplyScalar( l );
  745. },
  746. lerpSelf: function ( v, alpha ) {
  747. this.x += ( v.x - this.x ) * alpha;
  748. this.y += ( v.y - this.y ) * alpha;
  749. this.z += ( v.z - this.z ) * alpha;
  750. this.w += ( v.w - this.w ) * alpha;
  751. return this;
  752. },
  753. clone: function () {
  754. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  755. },
  756. setAxisAngleFromQuaternion: function ( q ) {
  757. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  758. // q is assumed to be normalized
  759. this.w = 2 * Math.acos( q.w );
  760. var s = Math.sqrt( 1 - q.w * q.w );
  761. if ( s < 0.0001 ) {
  762. this.x = 1;
  763. this.y = 0;
  764. this.z = 0;
  765. } else {
  766. this.x = q.x / s;
  767. this.y = q.y / s;
  768. this.z = q.z / s;
  769. }
  770. return this;
  771. },
  772. setAxisAngleFromRotationMatrix: function ( m ) {
  773. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  774. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  775. var angle, x, y, z, // variables for result
  776. epsilon = 0.01, // margin to allow for rounding errors
  777. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  778. te = m.elements,
  779. m11 = te[0], m12 = te[4], m13 = te[8],
  780. m21 = te[1], m22 = te[5], m23 = te[9],
  781. m31 = te[2], m32 = te[6], m33 = te[10];
  782. if ( ( Math.abs( m12 - m21 ) < epsilon )
  783. && ( Math.abs( m13 - m31 ) < epsilon )
  784. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  785. // singularity found
  786. // first check for identity matrix which must have +1 for all terms
  787. // in leading diagonal and zero in other terms
  788. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  789. && ( Math.abs( m13 + m31 ) < epsilon2 )
  790. && ( Math.abs( m23 + m32 ) < epsilon2 )
  791. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  792. // this singularity is identity matrix so angle = 0
  793. this.set( 1, 0, 0, 0 );
  794. return this; // zero angle, arbitrary axis
  795. }
  796. // otherwise this singularity is angle = 180
  797. angle = Math.PI;
  798. var xx = ( m11 + 1 ) / 2;
  799. var yy = ( m22 + 1 ) / 2;
  800. var zz = ( m33 + 1 ) / 2;
  801. var xy = ( m12 + m21 ) / 4;
  802. var xz = ( m13 + m31 ) / 4;
  803. var yz = ( m23 + m32 ) / 4;
  804. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  805. if ( xx < epsilon ) {
  806. x = 0;
  807. y = 0.707106781;
  808. z = 0.707106781;
  809. } else {
  810. x = Math.sqrt( xx );
  811. y = xy / x;
  812. z = xz / x;
  813. }
  814. } else if ( yy > zz ) { // m22 is the largest diagonal term
  815. if ( yy < epsilon ) {
  816. x = 0.707106781;
  817. y = 0;
  818. z = 0.707106781;
  819. } else {
  820. y = Math.sqrt( yy );
  821. x = xy / y;
  822. z = yz / y;
  823. }
  824. } else { // m33 is the largest diagonal term so base result on this
  825. if ( zz < epsilon ) {
  826. x = 0.707106781;
  827. y = 0.707106781;
  828. z = 0;
  829. } else {
  830. z = Math.sqrt( zz );
  831. x = xz / z;
  832. y = yz / z;
  833. }
  834. }
  835. this.set( x, y, z, angle );
  836. return this; // return 180 deg rotation
  837. }
  838. // as we have reached here there are no singularities so we can handle normally
  839. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  840. + ( m13 - m31 ) * ( m13 - m31 )
  841. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  842. if ( Math.abs( s ) < 0.001 ) s = 1;
  843. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  844. // caught by singularity test above, but I've left it in just in case
  845. this.x = ( m32 - m23 ) / s;
  846. this.y = ( m13 - m31 ) / s;
  847. this.z = ( m21 - m12 ) / s;
  848. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  849. return this;
  850. }
  851. };
  852. /**
  853. * @author alteredq / http://alteredqualia.com/
  854. */
  855. THREE.Matrix3 = function () {
  856. this.elements = new Float32Array(9);
  857. };
  858. THREE.Matrix3.prototype = {
  859. constructor: THREE.Matrix3,
  860. getInverse: function ( matrix ) {
  861. // input: THREE.Matrix4
  862. // ( based on http://code.google.com/p/webgl-mjs/ )
  863. var me = matrix.elements;
  864. var a11 = me[10] * me[5] - me[6] * me[9];
  865. var a21 = - me[10] * me[1] + me[2] * me[9];
  866. var a31 = me[6] * me[1] - me[2] * me[5];
  867. var a12 = - me[10] * me[4] + me[6] * me[8];
  868. var a22 = me[10] * me[0] - me[2] * me[8];
  869. var a32 = - me[6] * me[0] + me[2] * me[4];
  870. var a13 = me[9] * me[4] - me[5] * me[8];
  871. var a23 = - me[9] * me[0] + me[1] * me[8];
  872. var a33 = me[5] * me[0] - me[1] * me[4];
  873. var det = me[0] * a11 + me[1] * a12 + me[2] * a13;
  874. // no inverse
  875. if ( det === 0 ) {
  876. console.warn( "Matrix3.getInverse(): determinant == 0" );
  877. }
  878. var idet = 1.0 / det;
  879. var m = this.elements;
  880. m[ 0 ] = idet * a11; m[ 1 ] = idet * a21; m[ 2 ] = idet * a31;
  881. m[ 3 ] = idet * a12; m[ 4 ] = idet * a22; m[ 5 ] = idet * a32;
  882. m[ 6 ] = idet * a13; m[ 7 ] = idet * a23; m[ 8 ] = idet * a33;
  883. return this;
  884. },
  885. transpose: function () {
  886. var tmp, m = this.elements;
  887. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  888. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  889. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  890. return this;
  891. },
  892. transposeIntoArray: function ( r ) {
  893. var m = this.m;
  894. r[ 0 ] = m[ 0 ];
  895. r[ 1 ] = m[ 3 ];
  896. r[ 2 ] = m[ 6 ];
  897. r[ 3 ] = m[ 1 ];
  898. r[ 4 ] = m[ 4 ];
  899. r[ 5 ] = m[ 7 ];
  900. r[ 6 ] = m[ 2 ];
  901. r[ 7 ] = m[ 5 ];
  902. r[ 8 ] = m[ 8 ];
  903. return this;
  904. }
  905. };
  906. /**
  907. * @author mrdoob / http://mrdoob.com/
  908. * @author supereggbert / http://www.paulbrunt.co.uk/
  909. * @author philogb / http://blog.thejit.org/
  910. * @author jordi_ros / http://plattsoft.com
  911. * @author D1plo1d / http://github.com/D1plo1d
  912. * @author alteredq / http://alteredqualia.com/
  913. * @author mikael emtinger / http://gomo.se/
  914. * @author timknip / http://www.floorplanner.com/
  915. */
  916. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  917. this.elements = new Float32Array( 16 );
  918. this.set(
  919. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  920. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  921. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  922. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  923. );
  924. };
  925. THREE.Matrix4.prototype = {
  926. constructor: THREE.Matrix4,
  927. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  928. var te = this.elements;
  929. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  930. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  931. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  932. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  933. return this;
  934. },
  935. identity: function () {
  936. this.set(
  937. 1, 0, 0, 0,
  938. 0, 1, 0, 0,
  939. 0, 0, 1, 0,
  940. 0, 0, 0, 1
  941. );
  942. return this;
  943. },
  944. copy: function ( m ) {
  945. var me = m.elements;
  946. this.set(
  947. me[0], me[4], me[8], me[12],
  948. me[1], me[5], me[9], me[13],
  949. me[2], me[6], me[10], me[14],
  950. me[3], me[7], me[11], me[15]
  951. );
  952. return this;
  953. },
  954. lookAt: function ( eye, target, up ) {
  955. var te = this.elements;
  956. var x = THREE.Matrix4.__v1;
  957. var y = THREE.Matrix4.__v2;
  958. var z = THREE.Matrix4.__v3;
  959. z.sub( eye, target ).normalize();
  960. if ( z.length() === 0 ) {
  961. z.z = 1;
  962. }
  963. x.cross( up, z ).normalize();
  964. if ( x.length() === 0 ) {
  965. z.x += 0.0001;
  966. x.cross( up, z ).normalize();
  967. }
  968. y.cross( z, x );
  969. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  970. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  971. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  972. return this;
  973. },
  974. multiply: function ( a, b ) {
  975. var ae = a.elements;
  976. var be = b.elements;
  977. var te = this.elements;
  978. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  979. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  980. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  981. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  982. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  983. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  984. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  985. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  986. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  987. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  988. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  989. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  990. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  991. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  992. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  993. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  994. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  995. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  996. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  997. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  998. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  999. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1000. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1001. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1002. return this;
  1003. },
  1004. multiplySelf: function ( m ) {
  1005. return this.multiply( this, m );
  1006. },
  1007. multiplyToArray: function ( a, b, r ) {
  1008. var te = this.elements;
  1009. this.multiply( a, b );
  1010. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1011. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1012. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1013. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1014. return this;
  1015. },
  1016. multiplyScalar: function ( s ) {
  1017. var te = this.elements;
  1018. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1019. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1020. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1021. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1022. return this;
  1023. },
  1024. multiplyVector3: function ( v ) {
  1025. var te = this.elements;
  1026. var vx = v.x, vy = v.y, vz = v.z;
  1027. var d = 1 / ( te[3] * vx + te[7] * vy + te[11] * vz + te[15] );
  1028. v.x = ( te[0] * vx + te[4] * vy + te[8] * vz + te[12] ) * d;
  1029. v.y = ( te[1] * vx + te[5] * vy + te[9] * vz + te[13] ) * d;
  1030. v.z = ( te[2] * vx + te[6] * vy + te[10] * vz + te[14] ) * d;
  1031. return v;
  1032. },
  1033. multiplyVector4: function ( v ) {
  1034. var te = this.elements;
  1035. var vx = v.x, vy = v.y, vz = v.z, vw = v.w;
  1036. v.x = te[0] * vx + te[4] * vy + te[8] * vz + te[12] * vw;
  1037. v.y = te[1] * vx + te[5] * vy + te[9] * vz + te[13] * vw;
  1038. v.z = te[2] * vx + te[6] * vy + te[10] * vz + te[14] * vw;
  1039. v.w = te[3] * vx + te[7] * vy + te[11] * vz + te[15] * vw;
  1040. return v;
  1041. },
  1042. multiplyVector3Array: function ( a ) {
  1043. var tmp = THREE.Matrix4.__v1;
  1044. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1045. tmp.x = a[ i ];
  1046. tmp.y = a[ i + 1 ];
  1047. tmp.z = a[ i + 2 ];
  1048. this.multiplyVector3( tmp );
  1049. a[ i ] = tmp.x;
  1050. a[ i + 1 ] = tmp.y;
  1051. a[ i + 2 ] = tmp.z;
  1052. }
  1053. return a;
  1054. },
  1055. rotateAxis: function ( v ) {
  1056. var te = this.elements;
  1057. var vx = v.x, vy = v.y, vz = v.z;
  1058. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1059. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  1060. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  1061. v.normalize();
  1062. return v;
  1063. },
  1064. crossVector: function ( a ) {
  1065. var te = this.elements;
  1066. var v = new THREE.Vector4();
  1067. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  1068. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  1069. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  1070. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  1071. return v;
  1072. },
  1073. determinant: function () {
  1074. var te = this.elements;
  1075. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  1076. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  1077. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  1078. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  1079. //TODO: make this more efficient
  1080. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1081. return (
  1082. n14 * n23 * n32 * n41-
  1083. n13 * n24 * n32 * n41-
  1084. n14 * n22 * n33 * n41+
  1085. n12 * n24 * n33 * n41+
  1086. n13 * n22 * n34 * n41-
  1087. n12 * n23 * n34 * n41-
  1088. n14 * n23 * n31 * n42+
  1089. n13 * n24 * n31 * n42+
  1090. n14 * n21 * n33 * n42-
  1091. n11 * n24 * n33 * n42-
  1092. n13 * n21 * n34 * n42+
  1093. n11 * n23 * n34 * n42+
  1094. n14 * n22 * n31 * n43-
  1095. n12 * n24 * n31 * n43-
  1096. n14 * n21 * n32 * n43+
  1097. n11 * n24 * n32 * n43+
  1098. n12 * n21 * n34 * n43-
  1099. n11 * n22 * n34 * n43-
  1100. n13 * n22 * n31 * n44+
  1101. n12 * n23 * n31 * n44+
  1102. n13 * n21 * n32 * n44-
  1103. n11 * n23 * n32 * n44-
  1104. n12 * n21 * n33 * n44+
  1105. n11 * n22 * n33 * n44
  1106. );
  1107. },
  1108. transpose: function () {
  1109. var te = this.elements;
  1110. var tmp;
  1111. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  1112. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  1113. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  1114. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  1115. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  1116. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  1117. return this;
  1118. },
  1119. flattenToArray: function ( flat ) {
  1120. var te = this.elements;
  1121. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  1122. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  1123. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  1124. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  1125. return flat;
  1126. },
  1127. flattenToArrayOffset: function( flat, offset ) {
  1128. var te = this.elements;
  1129. flat[ offset ] = te[0];
  1130. flat[ offset + 1 ] = te[1];
  1131. flat[ offset + 2 ] = te[2];
  1132. flat[ offset + 3 ] = te[3];
  1133. flat[ offset + 4 ] = te[4];
  1134. flat[ offset + 5 ] = te[5];
  1135. flat[ offset + 6 ] = te[6];
  1136. flat[ offset + 7 ] = te[7];
  1137. flat[ offset + 8 ] = te[8];
  1138. flat[ offset + 9 ] = te[9];
  1139. flat[ offset + 10 ] = te[10];
  1140. flat[ offset + 11 ] = te[11];
  1141. flat[ offset + 12 ] = te[12];
  1142. flat[ offset + 13 ] = te[13];
  1143. flat[ offset + 14 ] = te[14];
  1144. flat[ offset + 15 ] = te[15];
  1145. return flat;
  1146. },
  1147. getPosition: function () {
  1148. var te = this.elements;
  1149. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  1150. },
  1151. setPosition: function ( v ) {
  1152. var te = this.elements;
  1153. te[12] = v.x;
  1154. te[13] = v.y;
  1155. te[14] = v.z;
  1156. return this;
  1157. },
  1158. getColumnX: function () {
  1159. var te = this.elements;
  1160. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  1161. },
  1162. getColumnY: function () {
  1163. var te = this.elements;
  1164. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  1165. },
  1166. getColumnZ: function() {
  1167. var te = this.elements;
  1168. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  1169. },
  1170. getInverse: function ( m ) {
  1171. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  1172. var te = this.elements;
  1173. var me = m.elements;
  1174. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  1175. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  1176. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  1177. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  1178. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  1179. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  1180. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  1181. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  1182. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  1183. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  1184. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  1185. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  1186. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  1187. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  1188. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  1189. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  1190. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  1191. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  1192. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  1193. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  1194. this.multiplyScalar( 1 / m.determinant() );
  1195. return this;
  1196. },
  1197. setRotationFromEuler: function ( v, order ) {
  1198. var te = this.elements;
  1199. var x = v.x, y = v.y, z = v.z;
  1200. var a = Math.cos( x ), b = Math.sin( x );
  1201. var c = Math.cos( y ), d = Math.sin( y );
  1202. var e = Math.cos( z ), f = Math.sin( z );
  1203. if ( order === undefined || order === 'XYZ' ) {
  1204. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1205. te[0] = c * e;
  1206. te[4] = - c * f;
  1207. te[8] = d;
  1208. te[1] = af + be * d;
  1209. te[5] = ae - bf * d;
  1210. te[9] = - b * c;
  1211. te[2] = bf - ae * d;
  1212. te[6] = be + af * d;
  1213. te[10] = a * c;
  1214. } else if ( order === 'YXZ' ) {
  1215. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1216. te[0] = ce + df * b;
  1217. te[4] = de * b - cf;
  1218. te[8] = a * d;
  1219. te[1] = a * f;
  1220. te[5] = a * e;
  1221. te[9] = - b;
  1222. te[2] = cf * b - de;
  1223. te[6] = df + ce * b;
  1224. te[10] = a * c;
  1225. } else if ( order === 'ZXY' ) {
  1226. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1227. te[0] = ce - df * b;
  1228. te[4] = - a * f;
  1229. te[8] = de + cf * b;
  1230. te[1] = cf + de * b;
  1231. te[5] = a * e;
  1232. te[9] = df - ce * b;
  1233. te[2] = - a * d;
  1234. te[6] = b;
  1235. te[10] = a * c;
  1236. } else if ( order === 'ZYX' ) {
  1237. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1238. te[0] = c * e;
  1239. te[4] = be * d - af;
  1240. te[8] = ae * d + bf;
  1241. te[1] = c * f;
  1242. te[5] = bf * d + ae;
  1243. te[9] = af * d - be;
  1244. te[2] = - d;
  1245. te[6] = b * c;
  1246. te[10] = a * c;
  1247. } else if ( order === 'YZX' ) {
  1248. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1249. te[0] = c * e;
  1250. te[4] = bd - ac * f;
  1251. te[8] = bc * f + ad;
  1252. te[1] = f;
  1253. te[5] = a * e;
  1254. te[9] = - b * e;
  1255. te[2] = - d * e;
  1256. te[6] = ad * f + bc;
  1257. te[10] = ac - bd * f;
  1258. } else if ( order === 'XZY' ) {
  1259. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1260. te[0] = c * e;
  1261. te[4] = - f;
  1262. te[8] = d * e;
  1263. te[1] = ac * f + bd;
  1264. te[5] = a * e;
  1265. te[9] = ad * f - bc;
  1266. te[2] = bc * f - ad;
  1267. te[6] = b * e;
  1268. te[10] = bd * f + ac;
  1269. }
  1270. return this;
  1271. },
  1272. setRotationFromQuaternion: function ( q ) {
  1273. var te = this.elements;
  1274. var x = q.x, y = q.y, z = q.z, w = q.w;
  1275. var x2 = x + x, y2 = y + y, z2 = z + z;
  1276. var xx = x * x2, xy = x * y2, xz = x * z2;
  1277. var yy = y * y2, yz = y * z2, zz = z * z2;
  1278. var wx = w * x2, wy = w * y2, wz = w * z2;
  1279. te[0] = 1 - ( yy + zz );
  1280. te[4] = xy - wz;
  1281. te[8] = xz + wy;
  1282. te[1] = xy + wz;
  1283. te[5] = 1 - ( xx + zz );
  1284. te[9] = yz - wx;
  1285. te[2] = xz - wy;
  1286. te[6] = yz + wx;
  1287. te[10] = 1 - ( xx + yy );
  1288. return this;
  1289. },
  1290. compose: function ( translation, rotation, scale ) {
  1291. var te = this.elements;
  1292. var mRotation = THREE.Matrix4.__m1;
  1293. var mScale = THREE.Matrix4.__m2;
  1294. mRotation.identity();
  1295. mRotation.setRotationFromQuaternion( rotation );
  1296. mScale.makeScale( scale.x, scale.y, scale.z );
  1297. this.multiply( mRotation, mScale );
  1298. te[12] = translation.x;
  1299. te[13] = translation.y;
  1300. te[14] = translation.z;
  1301. return this;
  1302. },
  1303. decompose: function ( translation, rotation, scale ) {
  1304. var te = this.elements;
  1305. // grab the axis vectors
  1306. var x = THREE.Matrix4.__v1;
  1307. var y = THREE.Matrix4.__v2;
  1308. var z = THREE.Matrix4.__v3;
  1309. x.set( te[0], te[1], te[2] );
  1310. y.set( te[4], te[5], te[6] );
  1311. z.set( te[8], te[9], te[10] );
  1312. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  1313. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  1314. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  1315. scale.x = x.length();
  1316. scale.y = y.length();
  1317. scale.z = z.length();
  1318. translation.x = te[12];
  1319. translation.y = te[13];
  1320. translation.z = te[14];
  1321. // scale the rotation part
  1322. var matrix = THREE.Matrix4.__m1;
  1323. matrix.copy( this );
  1324. matrix.elements[0] /= scale.x;
  1325. matrix.elements[1] /= scale.x;
  1326. matrix.elements[2] /= scale.x;
  1327. matrix.elements[4] /= scale.y;
  1328. matrix.elements[5] /= scale.y;
  1329. matrix.elements[6] /= scale.y;
  1330. matrix.elements[8] /= scale.z;
  1331. matrix.elements[9] /= scale.z;
  1332. matrix.elements[10] /= scale.z;
  1333. rotation.setFromRotationMatrix( matrix );
  1334. return [ translation, rotation, scale ];
  1335. },
  1336. extractPosition: function ( m ) {
  1337. var te = this.elements;
  1338. var me = m.elements;
  1339. te[12] = me[12];
  1340. te[13] = me[13];
  1341. te[14] = me[14];
  1342. return this;
  1343. },
  1344. extractRotation: function ( m ) {
  1345. var te = this.elements;
  1346. var me = m.elements;
  1347. var vector = THREE.Matrix4.__v1;
  1348. var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
  1349. var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
  1350. var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
  1351. te[0] = me[0] * scaleX;
  1352. te[1] = me[1] * scaleX;
  1353. te[2] = me[2] * scaleX;
  1354. te[4] = me[4] * scaleY;
  1355. te[5] = me[5] * scaleY;
  1356. te[6] = me[6] * scaleY;
  1357. te[8] = me[8] * scaleZ;
  1358. te[9] = me[9] * scaleZ;
  1359. te[10] = me[10] * scaleZ;
  1360. return this;
  1361. },
  1362. //
  1363. translate: function ( v ) {
  1364. var te = this.elements;
  1365. var x = v.x, y = v.y, z = v.z;
  1366. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  1367. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  1368. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  1369. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  1370. return this;
  1371. },
  1372. rotateX: function ( angle ) {
  1373. var te = this.elements;
  1374. var m12 = te[4];
  1375. var m22 = te[5];
  1376. var m32 = te[6];
  1377. var m42 = te[7];
  1378. var m13 = te[8];
  1379. var m23 = te[9];
  1380. var m33 = te[10];
  1381. var m43 = te[11];
  1382. var c = Math.cos( angle );
  1383. var s = Math.sin( angle );
  1384. te[4] = c * m12 + s * m13;
  1385. te[5] = c * m22 + s * m23;
  1386. te[6] = c * m32 + s * m33;
  1387. te[7] = c * m42 + s * m43;
  1388. te[8] = c * m13 - s * m12;
  1389. te[9] = c * m23 - s * m22;
  1390. te[10] = c * m33 - s * m32;
  1391. te[11] = c * m43 - s * m42;
  1392. return this;
  1393. },
  1394. rotateY: function ( angle ) {
  1395. var te = this.elements;
  1396. var m11 = te[0];
  1397. var m21 = te[1];
  1398. var m31 = te[2];
  1399. var m41 = te[3];
  1400. var m13 = te[8];
  1401. var m23 = te[9];
  1402. var m33 = te[10];
  1403. var m43 = te[11];
  1404. var c = Math.cos( angle );
  1405. var s = Math.sin( angle );
  1406. te[0] = c * m11 - s * m13;
  1407. te[1] = c * m21 - s * m23;
  1408. te[2] = c * m31 - s * m33;
  1409. te[3] = c * m41 - s * m43;
  1410. te[8] = c * m13 + s * m11;
  1411. te[9] = c * m23 + s * m21;
  1412. te[10] = c * m33 + s * m31;
  1413. te[11] = c * m43 + s * m41;
  1414. return this;
  1415. },
  1416. rotateZ: function ( angle ) {
  1417. var te = this.elements;
  1418. var m11 = te[0];
  1419. var m21 = te[1];
  1420. var m31 = te[2];
  1421. var m41 = te[3];
  1422. var m12 = te[4];
  1423. var m22 = te[5];
  1424. var m32 = te[6];
  1425. var m42 = te[7];
  1426. var c = Math.cos( angle );
  1427. var s = Math.sin( angle );
  1428. te[0] = c * m11 + s * m12;
  1429. te[1] = c * m21 + s * m22;
  1430. te[2] = c * m31 + s * m32;
  1431. te[3] = c * m41 + s * m42;
  1432. te[4] = c * m12 - s * m11;
  1433. te[5] = c * m22 - s * m21;
  1434. te[6] = c * m32 - s * m31;
  1435. te[7] = c * m42 - s * m41;
  1436. return this;
  1437. },
  1438. rotateByAxis: function ( axis, angle ) {
  1439. var te = this.elements;
  1440. // optimize by checking axis
  1441. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  1442. return this.rotateX( angle );
  1443. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  1444. return this.rotateY( angle );
  1445. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  1446. return this.rotateZ( angle );
  1447. }
  1448. var x = axis.x, y = axis.y, z = axis.z;
  1449. var n = Math.sqrt(x * x + y * y + z * z);
  1450. x /= n;
  1451. y /= n;
  1452. z /= n;
  1453. var xx = x * x, yy = y * y, zz = z * z;
  1454. var c = Math.cos( angle );
  1455. var s = Math.sin( angle );
  1456. var oneMinusCosine = 1 - c;
  1457. var xy = x * y * oneMinusCosine;
  1458. var xz = x * z * oneMinusCosine;
  1459. var yz = y * z * oneMinusCosine;
  1460. var xs = x * s;
  1461. var ys = y * s;
  1462. var zs = z * s;
  1463. var r11 = xx + (1 - xx) * c;
  1464. var r21 = xy + zs;
  1465. var r31 = xz - ys;
  1466. var r12 = xy - zs;
  1467. var r22 = yy + (1 - yy) * c;
  1468. var r32 = yz + xs;
  1469. var r13 = xz + ys;
  1470. var r23 = yz - xs;
  1471. var r33 = zz + (1 - zz) * c;
  1472. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  1473. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  1474. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  1475. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  1476. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  1477. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  1478. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  1479. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  1480. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  1481. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  1482. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  1483. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  1484. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  1485. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  1486. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  1487. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  1488. return this;
  1489. },
  1490. scale: function ( v ) {
  1491. var te = this.elements;
  1492. var x = v.x, y = v.y, z = v.z;
  1493. te[0] *= x; te[4] *= y; te[8] *= z;
  1494. te[1] *= x; te[5] *= y; te[9] *= z;
  1495. te[2] *= x; te[6] *= y; te[10] *= z;
  1496. te[3] *= x; te[7] *= y; te[11] *= z;
  1497. return this;
  1498. },
  1499. getMaxScaleOnAxis: function () {
  1500. var te = this.elements;
  1501. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  1502. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  1503. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  1504. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  1505. },
  1506. //
  1507. makeTranslation: function ( x, y, z ) {
  1508. this.set(
  1509. 1, 0, 0, x,
  1510. 0, 1, 0, y,
  1511. 0, 0, 1, z,
  1512. 0, 0, 0, 1
  1513. );
  1514. return this;
  1515. },
  1516. makeRotationX: function ( theta ) {
  1517. var c = Math.cos( theta ), s = Math.sin( theta );
  1518. this.set(
  1519. 1, 0, 0, 0,
  1520. 0, c, -s, 0,
  1521. 0, s, c, 0,
  1522. 0, 0, 0, 1
  1523. );
  1524. return this;
  1525. },
  1526. makeRotationY: function ( theta ) {
  1527. var c = Math.cos( theta ), s = Math.sin( theta );
  1528. this.set(
  1529. c, 0, s, 0,
  1530. 0, 1, 0, 0,
  1531. -s, 0, c, 0,
  1532. 0, 0, 0, 1
  1533. );
  1534. return this;
  1535. },
  1536. makeRotationZ: function ( theta ) {
  1537. var c = Math.cos( theta ), s = Math.sin( theta );
  1538. this.set(
  1539. c, -s, 0, 0,
  1540. s, c, 0, 0,
  1541. 0, 0, 1, 0,
  1542. 0, 0, 0, 1
  1543. );
  1544. return this;
  1545. },
  1546. makeRotationAxis: function ( axis, angle ) {
  1547. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  1548. var c = Math.cos( angle );
  1549. var s = Math.sin( angle );
  1550. var t = 1 - c;
  1551. var x = axis.x, y = axis.y, z = axis.z;
  1552. var tx = t * x, ty = t * y;
  1553. this.set(
  1554. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  1555. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  1556. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  1557. 0, 0, 0, 1
  1558. );
  1559. return this;
  1560. },
  1561. makeScale: function ( x, y, z ) {
  1562. this.set(
  1563. x, 0, 0, 0,
  1564. 0, y, 0, 0,
  1565. 0, 0, z, 0,
  1566. 0, 0, 0, 1
  1567. );
  1568. return this;
  1569. },
  1570. makeFrustum: function ( left, right, bottom, top, near, far ) {
  1571. var te = this.elements;
  1572. var x = 2 * near / ( right - left );
  1573. var y = 2 * near / ( top - bottom );
  1574. var a = ( right + left ) / ( right - left );
  1575. var b = ( top + bottom ) / ( top - bottom );
  1576. var c = - ( far + near ) / ( far - near );
  1577. var d = - 2 * far * near / ( far - near );
  1578. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  1579. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  1580. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  1581. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  1582. return this;
  1583. },
  1584. makePerspective: function ( fov, aspect, near, far ) {
  1585. var ymax = near * Math.tan( fov * Math.PI / 360 );
  1586. var ymin = - ymax;
  1587. var xmin = ymin * aspect;
  1588. var xmax = ymax * aspect;
  1589. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  1590. },
  1591. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  1592. var te = this.elements;
  1593. var w = right - left;
  1594. var h = top - bottom;
  1595. var p = far - near;
  1596. var x = ( right + left ) / w;
  1597. var y = ( top + bottom ) / h;
  1598. var z = ( far + near ) / p;
  1599. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  1600. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  1601. te[2] = 0; te[6] = 0; te[10] = -2 / p; te[14] = -z;
  1602. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  1603. return this;
  1604. },
  1605. clone: function () {
  1606. var te = this.elements;
  1607. return new THREE.Matrix4(
  1608. te[0], te[4], te[8], te[12],
  1609. te[1], te[5], te[9], te[13],
  1610. te[2], te[6], te[10], te[14],
  1611. te[3], te[7], te[11], te[15]
  1612. );
  1613. }
  1614. };
  1615. THREE.Matrix4.__v1 = new THREE.Vector3();
  1616. THREE.Matrix4.__v2 = new THREE.Vector3();
  1617. THREE.Matrix4.__v3 = new THREE.Vector3();
  1618. THREE.Matrix4.__m1 = new THREE.Matrix4();
  1619. THREE.Matrix4.__m2 = new THREE.Matrix4();
  1620. /**
  1621. * https://github.com/mrdoob/eventtarget.js/
  1622. */
  1623. THREE.EventTarget = function () {
  1624. var listeners = {};
  1625. this.addEventListener = function ( type, listener ) {
  1626. if ( listeners[ type ] === undefined ) {
  1627. listeners[ type ] = [];
  1628. }
  1629. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  1630. listeners[ type ].push( listener );
  1631. }
  1632. };
  1633. this.dispatchEvent = function ( event ) {
  1634. for ( var listener in listeners[ event.type ] ) {
  1635. listeners[ event.type ][ listener ]( event );
  1636. }
  1637. };
  1638. this.removeEventListener = function ( type, listener ) {
  1639. var index = listeners[ type ].indexOf( listener );
  1640. if ( index !== - 1 ) {
  1641. listeners[ type ].splice( index, 1 );
  1642. }
  1643. };
  1644. };
  1645. /**
  1646. * @author mrdoob / http://mrdoob.com/
  1647. * @author alteredq / http://alteredqualia.com/
  1648. */
  1649. THREE.Frustum = function ( ) {
  1650. this.planes = [
  1651. new THREE.Vector4(),
  1652. new THREE.Vector4(),
  1653. new THREE.Vector4(),
  1654. new THREE.Vector4(),
  1655. new THREE.Vector4(),
  1656. new THREE.Vector4()
  1657. ];
  1658. };
  1659. THREE.Frustum.prototype.setFromMatrix = function ( m ) {
  1660. var plane;
  1661. var planes = this.planes;
  1662. var me = m.elements;
  1663. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  1664. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  1665. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  1666. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  1667. planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
  1668. planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
  1669. planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
  1670. planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
  1671. planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
  1672. planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
  1673. for ( var i = 0; i < 6; i ++ ) {
  1674. plane = planes[ i ];
  1675. plane.divideScalar( Math.sqrt( plane.x * plane.x + plane.y * plane.y + plane.z * plane.z ) );
  1676. }
  1677. };
  1678. THREE.Frustum.prototype.contains = function ( object ) {
  1679. var distance = 0.0;
  1680. var planes = this.planes;
  1681. var matrix = object.matrixWorld;
  1682. var me = matrix.elements;
  1683. var radius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  1684. for ( var i = 0; i < 6; i ++ ) {
  1685. distance = planes[ i ].x * me[12] + planes[ i ].y * me[13] + planes[ i ].z * me[14] + planes[ i ].w;
  1686. if ( distance <= radius ) return false;
  1687. }
  1688. return true;
  1689. };
  1690. THREE.Frustum.__v1 = new THREE.Vector3();
  1691. /**
  1692. * @author mrdoob / http://mrdoob.com/
  1693. */
  1694. ( function ( THREE ) {
  1695. THREE.Ray = function ( origin, direction, near, far ) {
  1696. this.origin = origin || new THREE.Vector3();
  1697. this.direction = direction || new THREE.Vector3();
  1698. this.near = near || 0;
  1699. this.far = far || Infinity;
  1700. };
  1701. var originCopy = new THREE.Vector3();
  1702. var localOriginCopy = new THREE.Vector3();
  1703. var localDirectionCopy = new THREE.Vector3();
  1704. var vector = new THREE.Vector3();
  1705. var normal = new THREE.Vector3();
  1706. var intersectPoint = new THREE.Vector3();
  1707. var inverseMatrix = new THREE.Matrix4();
  1708. var descSort = function ( a, b ) {
  1709. return a.distance - b.distance;
  1710. };
  1711. var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
  1712. var distanceFromIntersection = function ( origin, direction, position ) {
  1713. v0.sub( position, origin );
  1714. var dot = v0.dot( direction );
  1715. var intersect = v1.add( origin, v2.copy( direction ).multiplyScalar( dot ) );
  1716. var distance = position.distanceTo( intersect );
  1717. return distance;
  1718. };
  1719. // http://www.blackpawn.com/texts/pointinpoly/default.html
  1720. var pointInFace3 = function ( p, a, b, c ) {
  1721. v0.sub( c, a );
  1722. v1.sub( b, a );
  1723. v2.sub( p, a );
  1724. var dot00 = v0.dot( v0 );
  1725. var dot01 = v0.dot( v1 );
  1726. var dot02 = v0.dot( v2 );
  1727. var dot11 = v1.dot( v1 );
  1728. var dot12 = v1.dot( v2 );
  1729. var invDenom = 1 / ( dot00 * dot11 - dot01 * dot01 );
  1730. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  1731. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  1732. return ( u >= 0 ) && ( v >= 0 ) && ( u + v < 1 );
  1733. };
  1734. var intersectObject = function ( object, ray, intersects ) {
  1735. var distance,intersect;
  1736. if ( object instanceof THREE.Particle ) {
  1737. distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  1738. if ( distance > object.scale.x ) {
  1739. return intersects;
  1740. }
  1741. intersect = {
  1742. distance: distance,
  1743. point: object.position,
  1744. face: null,
  1745. object: object
  1746. };
  1747. intersects.push( intersect );
  1748. } else if ( object instanceof THREE.Mesh ) {
  1749. // Checking boundingSphere
  1750. var scaledRadius = object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis();
  1751. // Checking distance to ray
  1752. distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  1753. if ( distance > scaledRadius) {
  1754. return intersects;
  1755. }
  1756. // Checking faces
  1757. var f, fl, face, dot, scalar,
  1758. geometry = object.geometry,
  1759. vertices = geometry.vertices,
  1760. objMatrix, geometryMaterials,
  1761. isFaceMaterial, material, side, point;
  1762. geometryMaterials = object.geometry.materials;
  1763. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  1764. side = object.material.side;
  1765. var a, b, c, d;
  1766. var precision = ray.precision;
  1767. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  1768. originCopy.copy( ray.origin );
  1769. objMatrix = object.matrixWorld;
  1770. inverseMatrix.getInverse( objMatrix );
  1771. localOriginCopy.copy( originCopy );
  1772. inverseMatrix.multiplyVector3( localOriginCopy );
  1773. localDirectionCopy.copy( ray.direction );
  1774. inverseMatrix.rotateAxis( localDirectionCopy ).normalize();
  1775. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  1776. face = geometry.faces[ f ];
  1777. material = isFaceMaterial === true ? geometryMaterials[ face.materialIndex ] : object.material;
  1778. if ( material === undefined ) continue;
  1779. side = material.side;
  1780. vector.sub( face.centroid, localOriginCopy );
  1781. normal = face.normal;
  1782. dot = localDirectionCopy.dot( normal );
  1783. // bail if ray and plane are parallel
  1784. if ( Math.abs( dot ) < precision ) continue;
  1785. // calc distance to plane
  1786. scalar = normal.dot( vector ) / dot;
  1787. // if negative distance, then plane is behind ray
  1788. if ( scalar < 0 ) continue;
  1789. if ( side === THREE.DoubleSide || ( side === THREE.FrontSide ? dot < 0 : dot > 0 ) ) {
  1790. intersectPoint.add( localOriginCopy, localDirectionCopy.multiplyScalar( scalar ) );
  1791. if ( face instanceof THREE.Face3 ) {
  1792. a = vertices[ face.a ];
  1793. b = vertices[ face.b ];
  1794. c = vertices[ face.c ];
  1795. if ( pointInFace3( intersectPoint, a, b, c ) ) {
  1796. point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  1797. distance = originCopy.distanceTo( point );
  1798. if ( distance < ray.near || distance > ray.far ) continue;
  1799. intersect = {
  1800. distance: distance,
  1801. point: point,
  1802. face: face,
  1803. faceIndex: f,
  1804. object: object
  1805. };
  1806. intersects.push( intersect );
  1807. }
  1808. } else if ( face instanceof THREE.Face4 ) {
  1809. a = vertices[ face.a ];
  1810. b = vertices[ face.b ];
  1811. c = vertices[ face.c ];
  1812. d = vertices[ face.d ];
  1813. if ( pointInFace3( intersectPoint, a, b, d ) || pointInFace3( intersectPoint, b, c, d ) ) {
  1814. point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  1815. distance = originCopy.distanceTo( point );
  1816. if ( distance < ray.near || distance > ray.far ) continue;
  1817. intersect = {
  1818. distance: distance,
  1819. point: point,
  1820. face: face,
  1821. faceIndex: f,
  1822. object: object
  1823. };
  1824. intersects.push( intersect );
  1825. }
  1826. }
  1827. }
  1828. }
  1829. }
  1830. };
  1831. var intersectDescendants= function ( object, ray, intersects ) {
  1832. var descendants = object.getDescendants();
  1833. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  1834. intersectObject( descendants[ i ], this, intersects );
  1835. }
  1836. };
  1837. //
  1838. THREE.Ray.prototype.precision = 0.0001;
  1839. THREE.Ray.prototype.intersectObject = function ( object, recursive ) {
  1840. var intersects = [];
  1841. if ( recursive === true ) {
  1842. intersectDescendants( object, this, intersects );
  1843. }
  1844. intersectObject(object,this,intersects);
  1845. intersects.sort( descSort );
  1846. return intersects;
  1847. };
  1848. THREE.Ray.prototype.intersectObjects = function ( objects, recursive ) {
  1849. var intersects = [];
  1850. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  1851. intersectObject( objects[ i ], this, intersects );
  1852. if ( recursive === true ) {
  1853. intersectDescendants( objects[ i ], this, intersects );
  1854. }
  1855. }
  1856. intersects.sort( descSort );
  1857. return intersects;
  1858. };
  1859. }( THREE ) );
  1860. /**
  1861. * @author mrdoob / http://mrdoob.com/
  1862. */
  1863. THREE.Rectangle = function () {
  1864. var _left = 0;
  1865. var _top = 0;
  1866. var _right = 0;
  1867. var _bottom = 0;
  1868. var _width = 0;
  1869. var _height = 0;
  1870. var _isEmpty = true;
  1871. function resize() {
  1872. _width = _right - _left;
  1873. _height = _bottom - _top;
  1874. }
  1875. this.getX = function () {
  1876. return _left;
  1877. };
  1878. this.getY = function () {
  1879. return _top;
  1880. };
  1881. this.getWidth = function () {
  1882. return _width;
  1883. };
  1884. this.getHeight = function () {
  1885. return _height;
  1886. };
  1887. this.getLeft = function() {
  1888. return _left;
  1889. };
  1890. this.getTop = function() {
  1891. return _top;
  1892. };
  1893. this.getRight = function() {
  1894. return _right;
  1895. };
  1896. this.getBottom = function() {
  1897. return _bottom;
  1898. };
  1899. this.set = function ( left, top, right, bottom ) {
  1900. _isEmpty = false;
  1901. _left = left; _top = top;
  1902. _right = right; _bottom = bottom;
  1903. resize();
  1904. };
  1905. this.addPoint = function ( x, y ) {
  1906. if ( _isEmpty === true ) {
  1907. _isEmpty = false;
  1908. _left = x; _top = y;
  1909. _right = x; _bottom = y;
  1910. resize();
  1911. } else {
  1912. _left = _left < x ? _left : x; // Math.min( _left, x );
  1913. _top = _top < y ? _top : y; // Math.min( _top, y );
  1914. _right = _right > x ? _right : x; // Math.max( _right, x );
  1915. _bottom = _bottom > y ? _bottom : y; // Math.max( _bottom, y );
  1916. resize();
  1917. }
  1918. };
  1919. this.add3Points = function ( x1, y1, x2, y2, x3, y3 ) {
  1920. if ( _isEmpty === true ) {
  1921. _isEmpty = false;
  1922. _left = x1 < x2 ? ( x1 < x3 ? x1 : x3 ) : ( x2 < x3 ? x2 : x3 );
  1923. _top = y1 < y2 ? ( y1 < y3 ? y1 : y3 ) : ( y2 < y3 ? y2 : y3 );
  1924. _right = x1 > x2 ? ( x1 > x3 ? x1 : x3 ) : ( x2 > x3 ? x2 : x3 );
  1925. _bottom = y1 > y2 ? ( y1 > y3 ? y1 : y3 ) : ( y2 > y3 ? y2 : y3 );
  1926. resize();
  1927. } else {
  1928. _left = x1 < x2 ? ( x1 < x3 ? ( x1 < _left ? x1 : _left ) : ( x3 < _left ? x3 : _left ) ) : ( x2 < x3 ? ( x2 < _left ? x2 : _left ) : ( x3 < _left ? x3 : _left ) );
  1929. _top = y1 < y2 ? ( y1 < y3 ? ( y1 < _top ? y1 : _top ) : ( y3 < _top ? y3 : _top ) ) : ( y2 < y3 ? ( y2 < _top ? y2 : _top ) : ( y3 < _top ? y3 : _top ) );
  1930. _right = x1 > x2 ? ( x1 > x3 ? ( x1 > _right ? x1 : _right ) : ( x3 > _right ? x3 : _right ) ) : ( x2 > x3 ? ( x2 > _right ? x2 : _right ) : ( x3 > _right ? x3 : _right ) );
  1931. _bottom = y1 > y2 ? ( y1 > y3 ? ( y1 > _bottom ? y1 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) ) : ( y2 > y3 ? ( y2 > _bottom ? y2 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) );
  1932. resize();
  1933. };
  1934. };
  1935. this.addRectangle = function ( r ) {
  1936. if ( _isEmpty === true ) {
  1937. _isEmpty = false;
  1938. _left = r.getLeft(); _top = r.getTop();
  1939. _right = r.getRight(); _bottom = r.getBottom();
  1940. resize();
  1941. } else {
  1942. _left = _left < r.getLeft() ? _left : r.getLeft(); // Math.min(_left, r.getLeft() );
  1943. _top = _top < r.getTop() ? _top : r.getTop(); // Math.min(_top, r.getTop() );
  1944. _right = _right > r.getRight() ? _right : r.getRight(); // Math.max(_right, r.getRight() );
  1945. _bottom = _bottom > r.getBottom() ? _bottom : r.getBottom(); // Math.max(_bottom, r.getBottom() );
  1946. resize();
  1947. }
  1948. };
  1949. this.inflate = function ( v ) {
  1950. _left -= v; _top -= v;
  1951. _right += v; _bottom += v;
  1952. resize();
  1953. };
  1954. this.minSelf = function ( r ) {
  1955. _left = _left > r.getLeft() ? _left : r.getLeft(); // Math.max( _left, r.getLeft() );
  1956. _top = _top > r.getTop() ? _top : r.getTop(); // Math.max( _top, r.getTop() );
  1957. _right = _right < r.getRight() ? _right : r.getRight(); // Math.min( _right, r.getRight() );
  1958. _bottom = _bottom < r.getBottom() ? _bottom : r.getBottom(); // Math.min( _bottom, r.getBottom() );
  1959. resize();
  1960. };
  1961. this.intersects = function ( r ) {
  1962. // http://gamemath.com/2011/09/detecting-whether-two-boxes-overlap/
  1963. if ( _right < r.getLeft() ) return false;
  1964. if ( _left > r.getRight() ) return false;
  1965. if ( _bottom < r.getTop() ) return false;
  1966. if ( _top > r.getBottom() ) return false;
  1967. return true;
  1968. };
  1969. this.empty = function () {
  1970. _isEmpty = true;
  1971. _left = 0; _top = 0;
  1972. _right = 0; _bottom = 0;
  1973. resize();
  1974. };
  1975. this.isEmpty = function () {
  1976. return _isEmpty;
  1977. };
  1978. };
  1979. /**
  1980. * @author alteredq / http://alteredqualia.com/
  1981. */
  1982. THREE.Math = {
  1983. // Clamp value to range <a, b>
  1984. clamp: function ( x, a, b ) {
  1985. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  1986. },
  1987. // Clamp value to range <a, inf)
  1988. clampBottom: function ( x, a ) {
  1989. return x < a ? a : x;
  1990. },
  1991. // Linear mapping from range <a1, a2> to range <b1, b2>
  1992. mapLinear: function ( x, a1, a2, b1, b2 ) {
  1993. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1994. },
  1995. // Random float from <0, 1> with 16 bits of randomness
  1996. // (standard Math.random() creates repetitive patterns when applied over larger space)
  1997. random16: function () {
  1998. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  1999. },
  2000. // Random integer from <low, high> interval
  2001. randInt: function ( low, high ) {
  2002. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2003. },
  2004. // Random float from <low, high> interval
  2005. randFloat: function ( low, high ) {
  2006. return low + Math.random() * ( high - low );
  2007. },
  2008. // Random float from <-range/2, range/2> interval
  2009. randFloatSpread: function ( range ) {
  2010. return range * ( 0.5 - Math.random() );
  2011. },
  2012. sign: function ( x ) {
  2013. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  2014. }
  2015. };
  2016. /**
  2017. * @author mrdoob / http://mrdoob.com/
  2018. * @author mikael emtinger / http://gomo.se/
  2019. * @author alteredq / http://alteredqualia.com/
  2020. */
  2021. THREE.Object3D = function () {
  2022. this.id = THREE.Object3DCount ++;
  2023. this.name = '';
  2024. this.properties = {};
  2025. this.parent = undefined;
  2026. this.children = [];
  2027. this.up = new THREE.Vector3( 0, 1, 0 );
  2028. this.position = new THREE.Vector3();
  2029. this.rotation = new THREE.Vector3();
  2030. this.eulerOrder = 'XYZ';
  2031. this.scale = new THREE.Vector3( 1, 1, 1 );
  2032. this.renderDepth = null;
  2033. this.rotationAutoUpdate = true;
  2034. this.matrix = new THREE.Matrix4();
  2035. this.matrixWorld = new THREE.Matrix4();
  2036. this.matrixRotationWorld = new THREE.Matrix4();
  2037. this.matrixAutoUpdate = true;
  2038. this.matrixWorldNeedsUpdate = true;
  2039. this.quaternion = new THREE.Quaternion();
  2040. this.useQuaternion = false;
  2041. this.boundRadius = 0.0;
  2042. this.boundRadiusScale = 1.0;
  2043. this.visible = true;
  2044. this.castShadow = false;
  2045. this.receiveShadow = false;
  2046. this.frustumCulled = true;
  2047. this._vector = new THREE.Vector3();
  2048. };
  2049. THREE.Object3D.prototype = {
  2050. constructor: THREE.Object3D,
  2051. applyMatrix: function ( matrix ) {
  2052. this.matrix.multiply( matrix, this.matrix );
  2053. this.scale.getScaleFromMatrix( this.matrix );
  2054. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  2055. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  2056. this.position.getPositionFromMatrix( this.matrix );
  2057. },
  2058. translate: function ( distance, axis ) {
  2059. this.matrix.rotateAxis( axis );
  2060. this.position.addSelf( axis.multiplyScalar( distance ) );
  2061. },
  2062. translateX: function ( distance ) {
  2063. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  2064. },
  2065. translateY: function ( distance ) {
  2066. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  2067. },
  2068. translateZ: function ( distance ) {
  2069. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  2070. },
  2071. localToWorld: function ( vector ) {
  2072. return this.matrixWorld.multiplyVector3( vector );
  2073. },
  2074. worldToLocal: function ( vector ) {
  2075. return THREE.Object3D.__m1.getInverse( this.matrixWorld ).multiplyVector3( vector );
  2076. },
  2077. lookAt: function ( vector ) {
  2078. // TODO: Add hierarchy support.
  2079. this.matrix.lookAt( vector, this.position, this.up );
  2080. if ( this.rotationAutoUpdate ) {
  2081. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  2082. }
  2083. },
  2084. add: function ( object ) {
  2085. if ( object === this ) {
  2086. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  2087. return;
  2088. }
  2089. if ( object instanceof THREE.Object3D ) {
  2090. if ( object.parent !== undefined ) {
  2091. object.parent.remove( object );
  2092. }
  2093. object.parent = this;
  2094. this.children.push( object );
  2095. // add to scene
  2096. var scene = this;
  2097. while ( scene.parent !== undefined ) {
  2098. scene = scene.parent;
  2099. }
  2100. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2101. scene.__addObject( object );
  2102. }
  2103. }
  2104. },
  2105. remove: function ( object ) {
  2106. var index = this.children.indexOf( object );
  2107. if ( index !== - 1 ) {
  2108. object.parent = undefined;
  2109. this.children.splice( index, 1 );
  2110. // remove from scene
  2111. var scene = this;
  2112. while ( scene.parent !== undefined ) {
  2113. scene = scene.parent;
  2114. }
  2115. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2116. scene.__removeObject( object );
  2117. }
  2118. }
  2119. },
  2120. getChildByName: function ( name, recursive ) {
  2121. var c, cl, child;
  2122. for ( c = 0, cl = this.children.length; c < cl; c ++ ) {
  2123. child = this.children[ c ];
  2124. if ( child.name === name ) {
  2125. return child;
  2126. }
  2127. if ( recursive ) {
  2128. child = child.getChildByName( name, recursive );
  2129. if ( child !== undefined ) {
  2130. return child;
  2131. }
  2132. }
  2133. }
  2134. return undefined;
  2135. },
  2136. getDescendants: function ( array ) {
  2137. if ( array === undefined ) array = [];
  2138. Array.prototype.push.apply( array, this.children );
  2139. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2140. this.children[ i ].getDescendants( array );
  2141. };
  2142. return array;
  2143. },
  2144. updateMatrix: function () {
  2145. this.matrix.setPosition( this.position );
  2146. if ( this.useQuaternion === false ) {
  2147. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  2148. } else {
  2149. this.matrix.setRotationFromQuaternion( this.quaternion );
  2150. }
  2151. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  2152. this.matrix.scale( this.scale );
  2153. this.boundRadiusScale = Math.max( this.scale.x, Math.max( this.scale.y, this.scale.z ) );
  2154. }
  2155. this.matrixWorldNeedsUpdate = true;
  2156. },
  2157. updateMatrixWorld: function ( force ) {
  2158. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  2159. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  2160. if ( this.parent === undefined ) {
  2161. this.matrixWorld.copy( this.matrix );
  2162. } else {
  2163. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  2164. }
  2165. this.matrixWorldNeedsUpdate = false;
  2166. force = true;
  2167. }
  2168. // update children
  2169. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2170. this.children[ i ].updateMatrixWorld( force );
  2171. }
  2172. },
  2173. clone: function () {
  2174. // TODO
  2175. }
  2176. };
  2177. THREE.Object3D.__m1 = new THREE.Matrix4();
  2178. THREE.Object3DCount = 0;
  2179. /**
  2180. * @author mrdoob / http://mrdoob.com/
  2181. * @author supereggbert / http://www.paulbrunt.co.uk/
  2182. * @author julianwa / https://github.com/julianwa
  2183. */
  2184. THREE.Projector = function() {
  2185. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  2186. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  2187. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  2188. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  2189. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  2190. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  2191. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  2192. _vector3 = new THREE.Vector3(),
  2193. _vector4 = new THREE.Vector4(),
  2194. _viewProjectionMatrix = new THREE.Matrix4(),
  2195. _modelViewProjectionMatrix = new THREE.Matrix4(),
  2196. _frustum = new THREE.Frustum(),
  2197. _clippedVertex1PositionScreen = new THREE.Vector4(),
  2198. _clippedVertex2PositionScreen = new THREE.Vector4(),
  2199. _face3VertexNormals;
  2200. this.projectVector = function ( vector, camera ) {
  2201. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2202. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2203. _viewProjectionMatrix.multiplyVector3( vector );
  2204. return vector;
  2205. };
  2206. this.unprojectVector = function ( vector, camera ) {
  2207. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  2208. _viewProjectionMatrix.multiply( camera.matrixWorld, camera.projectionMatrixInverse );
  2209. _viewProjectionMatrix.multiplyVector3( vector );
  2210. return vector;
  2211. };
  2212. this.pickingRay = function ( vector, camera ) {
  2213. var end, ray, t;
  2214. // set two vectors with opposing z values
  2215. vector.z = -1.0;
  2216. end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  2217. this.unprojectVector( vector, camera );
  2218. this.unprojectVector( end, camera );
  2219. // find direction from vector to end
  2220. end.subSelf( vector ).normalize();
  2221. return new THREE.Ray( vector, end );
  2222. };
  2223. var projectGraph = function ( root, sort ) {
  2224. _objectCount = 0;
  2225. _renderData.objects.length = 0;
  2226. _renderData.sprites.length = 0;
  2227. _renderData.lights.length = 0;
  2228. var projectObject = function ( object ) {
  2229. if ( object.visible === false ) return;
  2230. if ( ( object instanceof THREE.Mesh || object instanceof THREE.Line ) &&
  2231. ( object.frustumCulled === false || _frustum.contains( object ) === true ) ) {
  2232. _vector3.copy( object.matrixWorld.getPosition() );
  2233. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2234. _object = getNextObjectInPool();
  2235. _object.object = object;
  2236. _object.z = _vector3.z;
  2237. _renderData.objects.push( _object );
  2238. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  2239. _vector3.copy( object.matrixWorld.getPosition() );
  2240. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2241. _object = getNextObjectInPool();
  2242. _object.object = object;
  2243. _object.z = _vector3.z;
  2244. _renderData.sprites.push( _object );
  2245. } else if ( object instanceof THREE.Light ) {
  2246. _renderData.lights.push( object );
  2247. }
  2248. for ( var c = 0, cl = object.children.length; c < cl; c ++ ) {
  2249. projectObject( object.children[ c ] );
  2250. }
  2251. };
  2252. projectObject( root );
  2253. if ( sort === true ) _renderData.objects.sort( painterSort );
  2254. return _renderData;
  2255. };
  2256. this.projectScene = function ( scene, camera, sort ) {
  2257. var near = camera.near, far = camera.far, visible = false,
  2258. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  2259. modelMatrix, rotationMatrix,
  2260. geometry, geometryMaterials, vertices, vertex, vertexPositionScreen,
  2261. faces, face, faceVertexNormals, normal, faceVertexUvs, uvs,
  2262. v1, v2, v3, v4, isFaceMaterial, material, side;
  2263. _face3Count = 0;
  2264. _face4Count = 0;
  2265. _lineCount = 0;
  2266. _particleCount = 0;
  2267. _renderData.elements.length = 0;
  2268. scene.updateMatrixWorld();
  2269. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  2270. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2271. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2272. _frustum.setFromMatrix( _viewProjectionMatrix );
  2273. _renderData = projectGraph( scene, false );
  2274. for ( o = 0, ol = _renderData.objects.length; o < ol; o++ ) {
  2275. object = _renderData.objects[ o ].object;
  2276. modelMatrix = object.matrixWorld;
  2277. _vertexCount = 0;
  2278. if ( object instanceof THREE.Mesh ) {
  2279. geometry = object.geometry;
  2280. geometryMaterials = object.geometry.materials;
  2281. vertices = geometry.vertices;
  2282. faces = geometry.faces;
  2283. faceVertexUvs = geometry.faceVertexUvs;
  2284. rotationMatrix = object.matrixRotationWorld.extractRotation( modelMatrix );
  2285. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  2286. side = object.material.side;
  2287. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  2288. _vertex = getNextVertexInPool();
  2289. _vertex.positionWorld.copy( vertices[ v ] );
  2290. modelMatrix.multiplyVector3( _vertex.positionWorld );
  2291. _vertex.positionScreen.copy( _vertex.positionWorld );
  2292. _viewProjectionMatrix.multiplyVector4( _vertex.positionScreen );
  2293. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  2294. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  2295. _vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;
  2296. }
  2297. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  2298. face = faces[ f ];
  2299. material = isFaceMaterial === true ? geometryMaterials[ face.materialIndex ] : object.material;
  2300. if ( material === undefined ) continue;
  2301. side = material.side;
  2302. if ( face instanceof THREE.Face3 ) {
  2303. v1 = _vertexPool[ face.a ];
  2304. v2 = _vertexPool[ face.b ];
  2305. v3 = _vertexPool[ face.c ];
  2306. if ( v1.visible === true && v2.visible === true && v3.visible === true ) {
  2307. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2308. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  2309. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2310. _face = getNextFace3InPool();
  2311. _face.v1.copy( v1 );
  2312. _face.v2.copy( v2 );
  2313. _face.v3.copy( v3 );
  2314. } else {
  2315. continue;
  2316. }
  2317. } else {
  2318. continue;
  2319. }
  2320. } else if ( face instanceof THREE.Face4 ) {
  2321. v1 = _vertexPool[ face.a ];
  2322. v2 = _vertexPool[ face.b ];
  2323. v3 = _vertexPool[ face.c ];
  2324. v4 = _vertexPool[ face.d ];
  2325. if ( v1.visible === true && v2.visible === true && v3.visible === true && v4.visible === true ) {
  2326. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2327. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  2328. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  2329. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  2330. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2331. _face = getNextFace4InPool();
  2332. _face.v1.copy( v1 );
  2333. _face.v2.copy( v2 );
  2334. _face.v3.copy( v3 );
  2335. _face.v4.copy( v4 );
  2336. } else {
  2337. continue;
  2338. }
  2339. } else {
  2340. continue;
  2341. }
  2342. }
  2343. _face.normalWorld.copy( face.normal );
  2344. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) _face.normalWorld.negate();
  2345. rotationMatrix.multiplyVector3( _face.normalWorld );
  2346. _face.centroidWorld.copy( face.centroid );
  2347. modelMatrix.multiplyVector3( _face.centroidWorld );
  2348. _face.centroidScreen.copy( _face.centroidWorld );
  2349. _viewProjectionMatrix.multiplyVector3( _face.centroidScreen );
  2350. faceVertexNormals = face.vertexNormals;
  2351. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  2352. normal = _face.vertexNormalsWorld[ n ];
  2353. normal.copy( faceVertexNormals[ n ] );
  2354. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) normal.negate();
  2355. rotationMatrix.multiplyVector3( normal );
  2356. }
  2357. _face.vertexNormalsLength = faceVertexNormals.length;
  2358. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  2359. uvs = faceVertexUvs[ c ][ f ];
  2360. if ( uvs === undefined ) continue;
  2361. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  2362. _face.uvs[ c ][ u ] = uvs[ u ];
  2363. }
  2364. }
  2365. _face.material = material;
  2366. _face.z = _face.centroidScreen.z;
  2367. _renderData.elements.push( _face );
  2368. }
  2369. } else if ( object instanceof THREE.Line ) {
  2370. _modelViewProjectionMatrix.multiply( _viewProjectionMatrix, modelMatrix );
  2371. vertices = object.geometry.vertices;
  2372. v1 = getNextVertexInPool();
  2373. v1.positionScreen.copy( vertices[ 0 ] );
  2374. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2375. // Handle LineStrip and LinePieces
  2376. var step = object.type === THREE.LinePieces ? 2 : 1;
  2377. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  2378. v1 = getNextVertexInPool();
  2379. v1.positionScreen.copy( vertices[ v ] );
  2380. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2381. if ( ( v + 1 ) % step > 0 ) continue;
  2382. v2 = _vertexPool[ _vertexCount - 2 ];
  2383. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  2384. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  2385. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  2386. // Perform the perspective divide
  2387. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  2388. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  2389. _line = getNextLineInPool();
  2390. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  2391. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  2392. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  2393. _line.material = object.material;
  2394. _renderData.elements.push( _line );
  2395. }
  2396. }
  2397. }
  2398. }
  2399. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  2400. object = _renderData.sprites[ o ].object;
  2401. modelMatrix = object.matrixWorld;
  2402. if ( object instanceof THREE.Particle ) {
  2403. _vector4.set( modelMatrix.elements[12], modelMatrix.elements[13], modelMatrix.elements[14], 1 );
  2404. _viewProjectionMatrix.multiplyVector4( _vector4 );
  2405. _vector4.z /= _vector4.w;
  2406. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  2407. _particle = getNextParticleInPool();
  2408. _particle.object = object;
  2409. _particle.x = _vector4.x / _vector4.w;
  2410. _particle.y = _vector4.y / _vector4.w;
  2411. _particle.z = _vector4.z;
  2412. _particle.rotation = object.rotation.z;
  2413. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  2414. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  2415. _particle.material = object.material;
  2416. _renderData.elements.push( _particle );
  2417. }
  2418. }
  2419. }
  2420. sort && _renderData.elements.sort( painterSort );
  2421. return _renderData;
  2422. };
  2423. // Pools
  2424. function getNextObjectInPool() {
  2425. if ( _objectCount === _objectPoolLength ) {
  2426. var object = new THREE.RenderableObject();
  2427. _objectPool.push( object );
  2428. _objectPoolLength ++;
  2429. _objectCount ++;
  2430. return object;
  2431. }
  2432. return _objectPool[ _objectCount ++ ];
  2433. }
  2434. function getNextVertexInPool() {
  2435. if ( _vertexCount === _vertexPoolLength ) {
  2436. var vertex = new THREE.RenderableVertex();
  2437. _vertexPool.push( vertex );
  2438. _vertexPoolLength ++;
  2439. _vertexCount ++;
  2440. return vertex;
  2441. }
  2442. return _vertexPool[ _vertexCount ++ ];
  2443. }
  2444. function getNextFace3InPool() {
  2445. if ( _face3Count === _face3PoolLength ) {
  2446. var face = new THREE.RenderableFace3();
  2447. _face3Pool.push( face );
  2448. _face3PoolLength ++;
  2449. _face3Count ++;
  2450. return face;
  2451. }
  2452. return _face3Pool[ _face3Count ++ ];
  2453. }
  2454. function getNextFace4InPool() {
  2455. if ( _face4Count === _face4PoolLength ) {
  2456. var face = new THREE.RenderableFace4();
  2457. _face4Pool.push( face );
  2458. _face4PoolLength ++;
  2459. _face4Count ++;
  2460. return face;
  2461. }
  2462. return _face4Pool[ _face4Count ++ ];
  2463. }
  2464. function getNextLineInPool() {
  2465. if ( _lineCount === _linePoolLength ) {
  2466. var line = new THREE.RenderableLine();
  2467. _linePool.push( line );
  2468. _linePoolLength ++;
  2469. _lineCount ++
  2470. return line;
  2471. }
  2472. return _linePool[ _lineCount ++ ];
  2473. }
  2474. function getNextParticleInPool() {
  2475. if ( _particleCount === _particlePoolLength ) {
  2476. var particle = new THREE.RenderableParticle();
  2477. _particlePool.push( particle );
  2478. _particlePoolLength ++;
  2479. _particleCount ++
  2480. return particle;
  2481. }
  2482. return _particlePool[ _particleCount ++ ];
  2483. }
  2484. //
  2485. function painterSort( a, b ) {
  2486. return b.z - a.z;
  2487. }
  2488. function clipLine( s1, s2 ) {
  2489. var alpha1 = 0, alpha2 = 1,
  2490. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  2491. // Z = -1 and Z = +1, respectively.
  2492. bc1near = s1.z + s1.w,
  2493. bc2near = s2.z + s2.w,
  2494. bc1far = - s1.z + s1.w,
  2495. bc2far = - s2.z + s2.w;
  2496. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  2497. // Both vertices lie entirely within all clip planes.
  2498. return true;
  2499. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  2500. // Both vertices lie entirely outside one of the clip planes.
  2501. return false;
  2502. } else {
  2503. // The line segment spans at least one clip plane.
  2504. if ( bc1near < 0 ) {
  2505. // v1 lies outside the near plane, v2 inside
  2506. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  2507. } else if ( bc2near < 0 ) {
  2508. // v2 lies outside the near plane, v1 inside
  2509. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  2510. }
  2511. if ( bc1far < 0 ) {
  2512. // v1 lies outside the far plane, v2 inside
  2513. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  2514. } else if ( bc2far < 0 ) {
  2515. // v2 lies outside the far plane, v2 inside
  2516. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  2517. }
  2518. if ( alpha2 < alpha1 ) {
  2519. // The line segment spans two boundaries, but is outside both of them.
  2520. // (This can't happen when we're only clipping against just near/far but good
  2521. // to leave the check here for future usage if other clip planes are added.)
  2522. return false;
  2523. } else {
  2524. // Update the s1 and s2 vertices to match the clipped line segment.
  2525. s1.lerpSelf( s2, alpha1 );
  2526. s2.lerpSelf( s1, 1 - alpha2 );
  2527. return true;
  2528. }
  2529. }
  2530. }
  2531. };
  2532. /**
  2533. * @author mikael emtinger / http://gomo.se/
  2534. * @author alteredq / http://alteredqualia.com/
  2535. * @author WestLangley / http://github.com/WestLangley
  2536. */
  2537. THREE.Quaternion = function( x, y, z, w ) {
  2538. this.x = x || 0;
  2539. this.y = y || 0;
  2540. this.z = z || 0;
  2541. this.w = ( w !== undefined ) ? w : 1;
  2542. };
  2543. THREE.Quaternion.prototype = {
  2544. constructor: THREE.Quaternion,
  2545. set: function ( x, y, z, w ) {
  2546. this.x = x;
  2547. this.y = y;
  2548. this.z = z;
  2549. this.w = w;
  2550. return this;
  2551. },
  2552. copy: function ( q ) {
  2553. this.x = q.x;
  2554. this.y = q.y;
  2555. this.z = q.z;
  2556. this.w = q.w;
  2557. return this;
  2558. },
  2559. setFromEuler: function ( v, order ) {
  2560. // http://www.mathworks.com/matlabcentral/fileexchange/
  2561. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2562. // content/SpinCalc.m
  2563. var c1 = Math.cos( v.x / 2 );
  2564. var c2 = Math.cos( v.y / 2 );
  2565. var c3 = Math.cos( v.z / 2 );
  2566. var s1 = Math.sin( v.x / 2 );
  2567. var s2 = Math.sin( v.y / 2 );
  2568. var s3 = Math.sin( v.z / 2 );
  2569. if ( order === undefined || order === 'XYZ' ) {
  2570. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2571. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2572. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2573. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2574. } else if ( order === 'YXZ' ) {
  2575. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2576. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2577. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2578. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2579. } else if ( order === 'ZXY' ) {
  2580. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2581. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2582. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2583. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2584. } else if ( order === 'ZYX' ) {
  2585. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2586. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2587. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2588. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2589. } else if ( order === 'YZX' ) {
  2590. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2591. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2592. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2593. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2594. } else if ( order === 'XZY' ) {
  2595. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2596. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2597. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2598. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2599. }
  2600. return this;
  2601. },
  2602. setFromAxisAngle: function ( axis, angle ) {
  2603. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2604. // axis have to be normalized
  2605. var halfAngle = angle / 2,
  2606. s = Math.sin( halfAngle );
  2607. this.x = axis.x * s;
  2608. this.y = axis.y * s;
  2609. this.z = axis.z * s;
  2610. this.w = Math.cos( halfAngle );
  2611. return this;
  2612. },
  2613. setFromRotationMatrix: function ( m ) {
  2614. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2615. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2616. var te = m.elements,
  2617. m11 = te[0], m12 = te[4], m13 = te[8],
  2618. m21 = te[1], m22 = te[5], m23 = te[9],
  2619. m31 = te[2], m32 = te[6], m33 = te[10],
  2620. trace = m11 + m22 + m33,
  2621. s;
  2622. if( trace > 0 ) {
  2623. s = 0.5 / Math.sqrt( trace + 1.0 );
  2624. this.w = 0.25 / s;
  2625. this.x = ( m32 - m23 ) * s;
  2626. this.y = ( m13 - m31 ) * s;
  2627. this.z = ( m21 - m12 ) * s;
  2628. } else if ( m11 > m22 && m11 > m33 ) {
  2629. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2630. this.w = (m32 - m23 ) / s;
  2631. this.x = 0.25 * s;
  2632. this.y = (m12 + m21 ) / s;
  2633. this.z = (m13 + m31 ) / s;
  2634. } else if (m22 > m33) {
  2635. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2636. this.w = (m13 - m31 ) / s;
  2637. this.x = (m12 + m21 ) / s;
  2638. this.y = 0.25 * s;
  2639. this.z = (m23 + m32 ) / s;
  2640. } else {
  2641. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2642. this.w = ( m21 - m12 ) / s;
  2643. this.x = ( m13 + m31 ) / s;
  2644. this.y = ( m23 + m32 ) / s;
  2645. this.z = 0.25 * s;
  2646. }
  2647. return this;
  2648. },
  2649. calculateW : function () {
  2650. this.w = - Math.sqrt( Math.abs( 1.0 - this.x * this.x - this.y * this.y - this.z * this.z ) );
  2651. return this;
  2652. },
  2653. inverse: function () {
  2654. this.x *= -1;
  2655. this.y *= -1;
  2656. this.z *= -1;
  2657. return this;
  2658. },
  2659. length: function () {
  2660. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2661. },
  2662. normalize: function () {
  2663. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2664. if ( l === 0 ) {
  2665. this.x = 0;
  2666. this.y = 0;
  2667. this.z = 0;
  2668. this.w = 0;
  2669. } else {
  2670. l = 1 / l;
  2671. this.x = this.x * l;
  2672. this.y = this.y * l;
  2673. this.z = this.z * l;
  2674. this.w = this.w * l;
  2675. }
  2676. return this;
  2677. },
  2678. multiply: function ( a, b ) {
  2679. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2680. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w,
  2681. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2682. this.x = qax * qbw + qay * qbz - qaz * qby + qaw * qbx;
  2683. this.y = -qax * qbz + qay * qbw + qaz * qbx + qaw * qby;
  2684. this.z = qax * qby - qay * qbx + qaz * qbw + qaw * qbz;
  2685. this.w = -qax * qbx - qay * qby - qaz * qbz + qaw * qbw;
  2686. return this;
  2687. },
  2688. multiplySelf: function ( b ) {
  2689. var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
  2690. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2691. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2692. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2693. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2694. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2695. return this;
  2696. },
  2697. multiplyVector3: function ( vector, dest ) {
  2698. if ( !dest ) { dest = vector; }
  2699. var x = vector.x, y = vector.y, z = vector.z,
  2700. qx = this.x, qy = this.y, qz = this.z, qw = this.w;
  2701. // calculate quat * vector
  2702. var ix = qw * x + qy * z - qz * y,
  2703. iy = qw * y + qz * x - qx * z,
  2704. iz = qw * z + qx * y - qy * x,
  2705. iw = -qx * x - qy * y - qz * z;
  2706. // calculate result * inverse quat
  2707. dest.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2708. dest.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2709. dest.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2710. return dest;
  2711. },
  2712. slerpSelf: function ( qb, t ) {
  2713. var x = this.x, y = this.y, z = this.z, w = this.w;
  2714. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2715. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  2716. if ( cosHalfTheta < 0 ) {
  2717. this.w = -qb.w;
  2718. this.x = -qb.x;
  2719. this.y = -qb.y;
  2720. this.z = -qb.z;
  2721. cosHalfTheta = -cosHalfTheta;
  2722. } else {
  2723. this.copy( qb );
  2724. }
  2725. if ( cosHalfTheta >= 1.0 ) {
  2726. this.w = w;
  2727. this.x = x;
  2728. this.y = y;
  2729. this.z = z;
  2730. return this;
  2731. }
  2732. var halfTheta = Math.acos( cosHalfTheta );
  2733. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2734. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2735. this.w = 0.5 * ( w + this.w );
  2736. this.x = 0.5 * ( x + this.x );
  2737. this.y = 0.5 * ( y + this.y );
  2738. this.z = 0.5 * ( z + this.z );
  2739. return this;
  2740. }
  2741. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2742. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2743. this.w = ( w * ratioA + this.w * ratioB );
  2744. this.x = ( x * ratioA + this.x * ratioB );
  2745. this.y = ( y * ratioA + this.y * ratioB );
  2746. this.z = ( z * ratioA + this.z * ratioB );
  2747. return this;
  2748. },
  2749. clone: function () {
  2750. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  2751. }
  2752. }
  2753. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  2754. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2755. var cosHalfTheta = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z;
  2756. if ( cosHalfTheta < 0 ) {
  2757. qm.w = -qb.w;
  2758. qm.x = -qb.x;
  2759. qm.y = -qb.y;
  2760. qm.z = -qb.z;
  2761. cosHalfTheta = -cosHalfTheta;
  2762. } else {
  2763. qm.copy( qb );
  2764. }
  2765. if ( Math.abs( cosHalfTheta ) >= 1.0 ) {
  2766. qm.w = qa.w;
  2767. qm.x = qa.x;
  2768. qm.y = qa.y;
  2769. qm.z = qa.z;
  2770. return qm;
  2771. }
  2772. var halfTheta = Math.acos( cosHalfTheta );
  2773. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2774. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2775. qm.w = 0.5 * ( qa.w + qm.w );
  2776. qm.x = 0.5 * ( qa.x + qm.x );
  2777. qm.y = 0.5 * ( qa.y + qm.y );
  2778. qm.z = 0.5 * ( qa.z + qm.z );
  2779. return qm;
  2780. }
  2781. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta;
  2782. var ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2783. qm.w = ( qa.w * ratioA + qm.w * ratioB );
  2784. qm.x = ( qa.x * ratioA + qm.x * ratioB );
  2785. qm.y = ( qa.y * ratioA + qm.y * ratioB );
  2786. qm.z = ( qa.z * ratioA + qm.z * ratioB );
  2787. return qm;
  2788. }
  2789. /**
  2790. * @author mrdoob / http://mrdoob.com/
  2791. */
  2792. THREE.Vertex = function ( v ) {
  2793. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  2794. return v;
  2795. };
  2796. /**
  2797. * @author mrdoob / http://mrdoob.com/
  2798. * @author alteredq / http://alteredqualia.com/
  2799. */
  2800. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  2801. this.a = a;
  2802. this.b = b;
  2803. this.c = c;
  2804. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2805. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2806. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2807. this.vertexColors = color instanceof Array ? color : [];
  2808. this.vertexTangents = [];
  2809. this.materialIndex = materialIndex;
  2810. this.centroid = new THREE.Vector3();
  2811. };
  2812. THREE.Face3.prototype = {
  2813. constructor: THREE.Face3,
  2814. clone: function () {
  2815. var face = new THREE.Face3( this.a, this.b, this.c );
  2816. face.normal.copy( this.normal );
  2817. face.color.copy( this.color );
  2818. face.centroid.copy( this.centroid );
  2819. face.materialIndex = this.materialIndex;
  2820. var i, il;
  2821. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2822. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2823. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2824. return face;
  2825. }
  2826. };
  2827. /**
  2828. * @author mrdoob / http://mrdoob.com/
  2829. * @author alteredq / http://alteredqualia.com/
  2830. */
  2831. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  2832. this.a = a;
  2833. this.b = b;
  2834. this.c = c;
  2835. this.d = d;
  2836. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2837. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2838. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2839. this.vertexColors = color instanceof Array ? color : [];
  2840. this.vertexTangents = [];
  2841. this.materialIndex = materialIndex;
  2842. this.centroid = new THREE.Vector3();
  2843. };
  2844. THREE.Face4.prototype = {
  2845. constructor: THREE.Face4,
  2846. clone: function () {
  2847. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  2848. face.normal.copy( this.normal );
  2849. face.color.copy( this.color );
  2850. face.centroid.copy( this.centroid );
  2851. face.materialIndex = this.materialIndex;
  2852. var i, il;
  2853. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2854. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2855. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2856. return face;
  2857. }
  2858. };
  2859. /**
  2860. * @author mrdoob / http://mrdoob.com/
  2861. */
  2862. THREE.UV = function ( u, v ) {
  2863. this.u = u || 0;
  2864. this.v = v || 0;
  2865. };
  2866. THREE.UV.prototype = {
  2867. constructor: THREE.UV,
  2868. set: function ( u, v ) {
  2869. this.u = u;
  2870. this.v = v;
  2871. return this;
  2872. },
  2873. copy: function ( uv ) {
  2874. this.u = uv.u;
  2875. this.v = uv.v;
  2876. return this;
  2877. },
  2878. lerpSelf: function ( uv, alpha ) {
  2879. this.u += ( uv.u - this.u ) * alpha;
  2880. this.v += ( uv.v - this.v ) * alpha;
  2881. return this;
  2882. },
  2883. clone: function () {
  2884. return new THREE.UV( this.u, this.v );
  2885. }
  2886. };
  2887. /**
  2888. * @author mrdoob / http://mrdoob.com/
  2889. * @author kile / http://kile.stravaganza.org/
  2890. * @author alteredq / http://alteredqualia.com/
  2891. * @author mikael emtinger / http://gomo.se/
  2892. * @author zz85 / http://www.lab4games.net/zz85/blog
  2893. */
  2894. THREE.Geometry = function () {
  2895. this.id = THREE.GeometryCount ++;
  2896. this.name = '';
  2897. this.vertices = [];
  2898. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  2899. this.materials = [];
  2900. this.faces = [];
  2901. this.faceUvs = [[]];
  2902. this.faceVertexUvs = [[]];
  2903. this.morphTargets = [];
  2904. this.morphColors = [];
  2905. this.morphNormals = [];
  2906. this.skinWeights = [];
  2907. this.skinIndices = [];
  2908. this.boundingBox = null;
  2909. this.boundingSphere = null;
  2910. this.hasTangents = false;
  2911. this.dynamic = true; // the intermediate typearrays will be deleted when set to false
  2912. };
  2913. THREE.Geometry.prototype = {
  2914. constructor : THREE.Geometry,
  2915. applyMatrix: function ( matrix ) {
  2916. var matrixRotation = new THREE.Matrix4();
  2917. matrixRotation.extractRotation( matrix );
  2918. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  2919. var vertex = this.vertices[ i ];
  2920. matrix.multiplyVector3( vertex );
  2921. }
  2922. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  2923. var face = this.faces[ i ];
  2924. matrixRotation.multiplyVector3( face.normal );
  2925. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  2926. matrixRotation.multiplyVector3( face.vertexNormals[ j ] );
  2927. }
  2928. matrix.multiplyVector3( face.centroid );
  2929. }
  2930. },
  2931. computeCentroids: function () {
  2932. var f, fl, face;
  2933. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2934. face = this.faces[ f ];
  2935. face.centroid.set( 0, 0, 0 );
  2936. if ( face instanceof THREE.Face3 ) {
  2937. face.centroid.addSelf( this.vertices[ face.a ] );
  2938. face.centroid.addSelf( this.vertices[ face.b ] );
  2939. face.centroid.addSelf( this.vertices[ face.c ] );
  2940. face.centroid.divideScalar( 3 );
  2941. } else if ( face instanceof THREE.Face4 ) {
  2942. face.centroid.addSelf( this.vertices[ face.a ] );
  2943. face.centroid.addSelf( this.vertices[ face.b ] );
  2944. face.centroid.addSelf( this.vertices[ face.c ] );
  2945. face.centroid.addSelf( this.vertices[ face.d ] );
  2946. face.centroid.divideScalar( 4 );
  2947. }
  2948. }
  2949. },
  2950. computeFaceNormals: function () {
  2951. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  2952. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  2953. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2954. face = this.faces[ f ];
  2955. vA = this.vertices[ face.a ];
  2956. vB = this.vertices[ face.b ];
  2957. vC = this.vertices[ face.c ];
  2958. cb.sub( vC, vB );
  2959. ab.sub( vA, vB );
  2960. cb.crossSelf( ab );
  2961. if ( !cb.isZero() ) {
  2962. cb.normalize();
  2963. }
  2964. face.normal.copy( cb );
  2965. }
  2966. },
  2967. computeVertexNormals: function () {
  2968. var v, vl, f, fl, face, vertices;
  2969. // create internal buffers for reuse when calling this method repeatedly
  2970. // (otherwise memory allocation / deallocation every frame is big resource hog)
  2971. if ( this.__tmpVertices === undefined ) {
  2972. this.__tmpVertices = new Array( this.vertices.length );
  2973. vertices = this.__tmpVertices;
  2974. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2975. vertices[ v ] = new THREE.Vector3();
  2976. }
  2977. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2978. face = this.faces[ f ];
  2979. if ( face instanceof THREE.Face3 ) {
  2980. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  2981. } else if ( face instanceof THREE.Face4 ) {
  2982. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  2983. }
  2984. }
  2985. } else {
  2986. vertices = this.__tmpVertices;
  2987. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2988. vertices[ v ].set( 0, 0, 0 );
  2989. }
  2990. }
  2991. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2992. face = this.faces[ f ];
  2993. if ( face instanceof THREE.Face3 ) {
  2994. vertices[ face.a ].addSelf( face.normal );
  2995. vertices[ face.b ].addSelf( face.normal );
  2996. vertices[ face.c ].addSelf( face.normal );
  2997. } else if ( face instanceof THREE.Face4 ) {
  2998. vertices[ face.a ].addSelf( face.normal );
  2999. vertices[ face.b ].addSelf( face.normal );
  3000. vertices[ face.c ].addSelf( face.normal );
  3001. vertices[ face.d ].addSelf( face.normal );
  3002. }
  3003. }
  3004. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3005. vertices[ v ].normalize();
  3006. }
  3007. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3008. face = this.faces[ f ];
  3009. if ( face instanceof THREE.Face3 ) {
  3010. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3011. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3012. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3013. } else if ( face instanceof THREE.Face4 ) {
  3014. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3015. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3016. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3017. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  3018. }
  3019. }
  3020. },
  3021. computeMorphNormals: function () {
  3022. var i, il, f, fl, face;
  3023. // save original normals
  3024. // - create temp variables on first access
  3025. // otherwise just copy (for faster repeated calls)
  3026. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3027. face = this.faces[ f ];
  3028. if ( ! face.__originalFaceNormal ) {
  3029. face.__originalFaceNormal = face.normal.clone();
  3030. } else {
  3031. face.__originalFaceNormal.copy( face.normal );
  3032. }
  3033. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  3034. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  3035. if ( ! face.__originalVertexNormals[ i ] ) {
  3036. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  3037. } else {
  3038. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  3039. }
  3040. }
  3041. }
  3042. // use temp geometry to compute face and vertex normals for each morph
  3043. var tmpGeo = new THREE.Geometry();
  3044. tmpGeo.faces = this.faces;
  3045. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  3046. // create on first access
  3047. if ( ! this.morphNormals[ i ] ) {
  3048. this.morphNormals[ i ] = {};
  3049. this.morphNormals[ i ].faceNormals = [];
  3050. this.morphNormals[ i ].vertexNormals = [];
  3051. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  3052. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  3053. var faceNormal, vertexNormals;
  3054. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3055. face = this.faces[ f ];
  3056. faceNormal = new THREE.Vector3();
  3057. if ( face instanceof THREE.Face3 ) {
  3058. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  3059. } else {
  3060. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  3061. }
  3062. dstNormalsFace.push( faceNormal );
  3063. dstNormalsVertex.push( vertexNormals );
  3064. }
  3065. }
  3066. var morphNormals = this.morphNormals[ i ];
  3067. // set vertices to morph target
  3068. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  3069. // compute morph normals
  3070. tmpGeo.computeFaceNormals();
  3071. tmpGeo.computeVertexNormals();
  3072. // store morph normals
  3073. var faceNormal, vertexNormals;
  3074. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3075. face = this.faces[ f ];
  3076. faceNormal = morphNormals.faceNormals[ f ];
  3077. vertexNormals = morphNormals.vertexNormals[ f ];
  3078. faceNormal.copy( face.normal );
  3079. if ( face instanceof THREE.Face3 ) {
  3080. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3081. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3082. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3083. } else {
  3084. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3085. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3086. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3087. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  3088. }
  3089. }
  3090. }
  3091. // restore original normals
  3092. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3093. face = this.faces[ f ];
  3094. face.normal = face.__originalFaceNormal;
  3095. face.vertexNormals = face.__originalVertexNormals;
  3096. }
  3097. },
  3098. computeTangents: function () {
  3099. // based on http://www.terathon.com/code/tangent.html
  3100. // tangents go to vertices
  3101. var f, fl, v, vl, i, il, vertexIndex,
  3102. face, uv, vA, vB, vC, uvA, uvB, uvC,
  3103. x1, x2, y1, y2, z1, z2,
  3104. s1, s2, t1, t2, r, t, test,
  3105. tan1 = [], tan2 = [],
  3106. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  3107. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  3108. n = new THREE.Vector3(), w;
  3109. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3110. tan1[ v ] = new THREE.Vector3();
  3111. tan2[ v ] = new THREE.Vector3();
  3112. }
  3113. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  3114. vA = context.vertices[ a ];
  3115. vB = context.vertices[ b ];
  3116. vC = context.vertices[ c ];
  3117. uvA = uv[ ua ];
  3118. uvB = uv[ ub ];
  3119. uvC = uv[ uc ];
  3120. x1 = vB.x - vA.x;
  3121. x2 = vC.x - vA.x;
  3122. y1 = vB.y - vA.y;
  3123. y2 = vC.y - vA.y;
  3124. z1 = vB.z - vA.z;
  3125. z2 = vC.z - vA.z;
  3126. s1 = uvB.u - uvA.u;
  3127. s2 = uvC.u - uvA.u;
  3128. t1 = uvB.v - uvA.v;
  3129. t2 = uvC.v - uvA.v;
  3130. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3131. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  3132. ( t2 * y1 - t1 * y2 ) * r,
  3133. ( t2 * z1 - t1 * z2 ) * r );
  3134. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  3135. ( s1 * y2 - s2 * y1 ) * r,
  3136. ( s1 * z2 - s2 * z1 ) * r );
  3137. tan1[ a ].addSelf( sdir );
  3138. tan1[ b ].addSelf( sdir );
  3139. tan1[ c ].addSelf( sdir );
  3140. tan2[ a ].addSelf( tdir );
  3141. tan2[ b ].addSelf( tdir );
  3142. tan2[ c ].addSelf( tdir );
  3143. }
  3144. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3145. face = this.faces[ f ];
  3146. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  3147. if ( face instanceof THREE.Face3 ) {
  3148. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  3149. } else if ( face instanceof THREE.Face4 ) {
  3150. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  3151. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  3152. }
  3153. }
  3154. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  3155. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3156. face = this.faces[ f ];
  3157. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  3158. n.copy( face.vertexNormals[ i ] );
  3159. vertexIndex = face[ faceIndex[ i ] ];
  3160. t = tan1[ vertexIndex ];
  3161. // Gram-Schmidt orthogonalize
  3162. tmp.copy( t );
  3163. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3164. // Calculate handedness
  3165. tmp2.cross( face.vertexNormals[ i ], t );
  3166. test = tmp2.dot( tan2[ vertexIndex ] );
  3167. w = (test < 0.0) ? -1.0 : 1.0;
  3168. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  3169. }
  3170. }
  3171. this.hasTangents = true;
  3172. },
  3173. computeBoundingBox: function () {
  3174. if ( ! this.boundingBox ) {
  3175. this.boundingBox = { min: new THREE.Vector3(), max: new THREE.Vector3() };
  3176. }
  3177. if ( this.vertices.length > 0 ) {
  3178. var position, firstPosition = this.vertices[ 0 ];
  3179. this.boundingBox.min.copy( firstPosition );
  3180. this.boundingBox.max.copy( firstPosition );
  3181. var min = this.boundingBox.min,
  3182. max = this.boundingBox.max;
  3183. for ( var v = 1, vl = this.vertices.length; v < vl; v ++ ) {
  3184. position = this.vertices[ v ];
  3185. if ( position.x < min.x ) {
  3186. min.x = position.x;
  3187. } else if ( position.x > max.x ) {
  3188. max.x = position.x;
  3189. }
  3190. if ( position.y < min.y ) {
  3191. min.y = position.y;
  3192. } else if ( position.y > max.y ) {
  3193. max.y = position.y;
  3194. }
  3195. if ( position.z < min.z ) {
  3196. min.z = position.z;
  3197. } else if ( position.z > max.z ) {
  3198. max.z = position.z;
  3199. }
  3200. }
  3201. } else {
  3202. this.boundingBox.min.set( 0, 0, 0 );
  3203. this.boundingBox.max.set( 0, 0, 0 );
  3204. }
  3205. },
  3206. computeBoundingSphere: function () {
  3207. var maxRadiusSq = 0;
  3208. if ( this.boundingSphere === null ) this.boundingSphere = { radius: 0 };
  3209. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  3210. var radiusSq = this.vertices[ i ].lengthSq();
  3211. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3212. }
  3213. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3214. },
  3215. /*
  3216. * Checks for duplicate vertices with hashmap.
  3217. * Duplicated vertices are removed
  3218. * and faces' vertices are updated.
  3219. */
  3220. mergeVertices: function () {
  3221. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  3222. var unique = [], changes = [];
  3223. var v, key;
  3224. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  3225. var precision = Math.pow( 10, precisionPoints );
  3226. var i,il, face;
  3227. var abcd = 'abcd', o, k, j, jl, u;
  3228. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  3229. v = this.vertices[ i ];
  3230. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  3231. if ( verticesMap[ key ] === undefined ) {
  3232. verticesMap[ key ] = i;
  3233. unique.push( this.vertices[ i ] );
  3234. changes[ i ] = unique.length - 1;
  3235. } else {
  3236. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  3237. changes[ i ] = changes[ verticesMap[ key ] ];
  3238. }
  3239. };
  3240. // Start to patch face indices
  3241. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  3242. face = this.faces[ i ];
  3243. if ( face instanceof THREE.Face3 ) {
  3244. face.a = changes[ face.a ];
  3245. face.b = changes[ face.b ];
  3246. face.c = changes[ face.c ];
  3247. } else if ( face instanceof THREE.Face4 ) {
  3248. face.a = changes[ face.a ];
  3249. face.b = changes[ face.b ];
  3250. face.c = changes[ face.c ];
  3251. face.d = changes[ face.d ];
  3252. // check dups in (a, b, c, d) and convert to -> face3
  3253. o = [ face.a, face.b, face.c, face.d ];
  3254. for ( k = 3; k > 0; k -- ) {
  3255. if ( o.indexOf( face[ abcd[ k ] ] ) !== k ) {
  3256. // console.log('faces', face.a, face.b, face.c, face.d, 'dup at', k);
  3257. o.splice( k, 1 );
  3258. this.faces[ i ] = new THREE.Face3( o[0], o[1], o[2], face.normal, face.color, face.materialIndex );
  3259. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  3260. u = this.faceVertexUvs[ j ][ i ];
  3261. if ( u ) u.splice( k, 1 );
  3262. }
  3263. this.faces[ i ].vertexColors = face.vertexColors;
  3264. break;
  3265. }
  3266. }
  3267. }
  3268. }
  3269. // Use unique set of vertices
  3270. var diff = this.vertices.length - unique.length;
  3271. this.vertices = unique;
  3272. return diff;
  3273. },
  3274. clone: function () {
  3275. // TODO
  3276. }
  3277. };
  3278. THREE.GeometryCount = 0;
  3279. /**
  3280. * @author alteredq / http://alteredqualia.com/
  3281. */
  3282. THREE.BufferGeometry = function () {
  3283. this.id = THREE.GeometryCount ++;
  3284. // attributes
  3285. this.attributes = {};
  3286. // attributes typed arrays are kept only if dynamic flag is set
  3287. this.dynamic = false;
  3288. // boundings
  3289. this.boundingBox = null;
  3290. this.boundingSphere = null;
  3291. this.hasTangents = false;
  3292. // for compatibility
  3293. this.morphTargets = [];
  3294. };
  3295. THREE.BufferGeometry.prototype = {
  3296. constructor : THREE.BufferGeometry,
  3297. applyMatrix: function ( matrix ) {
  3298. var positionArray;
  3299. var normalArray;
  3300. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  3301. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  3302. if ( positionArray !== undefined ) {
  3303. matrix.multiplyVector3Array( positionArray );
  3304. this.verticesNeedUpdate = true;
  3305. }
  3306. if ( normalArray !== undefined ) {
  3307. var matrixRotation = new THREE.Matrix4();
  3308. matrixRotation.extractRotation( matrix );
  3309. matrixRotation.multiplyVector3Array( normalArray );
  3310. this.normalsNeedUpdate = true;
  3311. }
  3312. },
  3313. computeBoundingBox: function () {
  3314. if ( ! this.boundingBox ) {
  3315. this.boundingBox = {
  3316. min: new THREE.Vector3( Infinity, Infinity, Infinity ),
  3317. max: new THREE.Vector3( -Infinity, -Infinity, -Infinity )
  3318. };
  3319. }
  3320. var positions = this.attributes[ "position" ].array;
  3321. if ( positions ) {
  3322. var bb = this.boundingBox;
  3323. var x, y, z;
  3324. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3325. x = positions[ i ];
  3326. y = positions[ i + 1 ];
  3327. z = positions[ i + 2 ];
  3328. // bounding box
  3329. if ( x < bb.min.x ) {
  3330. bb.min.x = x;
  3331. } else if ( x > bb.max.x ) {
  3332. bb.max.x = x;
  3333. }
  3334. if ( y < bb.min.y ) {
  3335. bb.min.y = y;
  3336. } else if ( y > bb.max.y ) {
  3337. bb.max.y = y;
  3338. }
  3339. if ( z < bb.min.z ) {
  3340. bb.min.z = z;
  3341. } else if ( z > bb.max.z ) {
  3342. bb.max.z = z;
  3343. }
  3344. }
  3345. }
  3346. if ( positions === undefined || positions.length === 0 ) {
  3347. this.boundingBox.min.set( 0, 0, 0 );
  3348. this.boundingBox.max.set( 0, 0, 0 );
  3349. }
  3350. },
  3351. computeBoundingSphere: function () {
  3352. if ( ! this.boundingSphere ) this.boundingSphere = { radius: 0 };
  3353. var positions = this.attributes[ "position" ].array;
  3354. if ( positions ) {
  3355. var radiusSq, maxRadiusSq = 0;
  3356. var x, y, z;
  3357. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3358. x = positions[ i ];
  3359. y = positions[ i + 1 ];
  3360. z = positions[ i + 2 ];
  3361. radiusSq = x * x + y * y + z * z;
  3362. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3363. }
  3364. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3365. }
  3366. },
  3367. computeVertexNormals: function () {
  3368. if ( this.attributes[ "position" ] && this.attributes[ "index" ] ) {
  3369. var i, il;
  3370. var j, jl;
  3371. var nVertexElements = this.attributes[ "position" ].array.length;
  3372. if ( this.attributes[ "normal" ] === undefined ) {
  3373. this.attributes[ "normal" ] = {
  3374. itemSize: 3,
  3375. array: new Float32Array( nVertexElements ),
  3376. numItems: nVertexElements
  3377. };
  3378. } else {
  3379. // reset existing normals to zero
  3380. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  3381. this.attributes[ "normal" ].array[ i ] = 0;
  3382. }
  3383. }
  3384. var offsets = this.offsets;
  3385. var indices = this.attributes[ "index" ].array;
  3386. var positions = this.attributes[ "position" ].array;
  3387. var normals = this.attributes[ "normal" ].array;
  3388. var vA, vB, vC, x, y, z,
  3389. pA = new THREE.Vector3(),
  3390. pB = new THREE.Vector3(),
  3391. pC = new THREE.Vector3(),
  3392. cb = new THREE.Vector3(),
  3393. ab = new THREE.Vector3();
  3394. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3395. var start = offsets[ j ].start;
  3396. var count = offsets[ j ].count;
  3397. var index = offsets[ j ].index;
  3398. for ( i = start, il = start + count; i < il; i += 3 ) {
  3399. vA = index + indices[ i ];
  3400. vB = index + indices[ i + 1 ];
  3401. vC = index + indices[ i + 2 ];
  3402. x = positions[ vA * 3 ];
  3403. y = positions[ vA * 3 + 1 ];
  3404. z = positions[ vA * 3 + 2 ];
  3405. pA.set( x, y, z );
  3406. x = positions[ vB * 3 ];
  3407. y = positions[ vB * 3 + 1 ];
  3408. z = positions[ vB * 3 + 2 ];
  3409. pB.set( x, y, z );
  3410. x = positions[ vC * 3 ];
  3411. y = positions[ vC * 3 + 1 ];
  3412. z = positions[ vC * 3 + 2 ];
  3413. pC.set( x, y, z );
  3414. cb.sub( pC, pB );
  3415. ab.sub( pA, pB );
  3416. cb.crossSelf( ab );
  3417. normals[ vA * 3 ] += cb.x;
  3418. normals[ vA * 3 + 1 ] += cb.y;
  3419. normals[ vA * 3 + 2 ] += cb.z;
  3420. normals[ vB * 3 ] += cb.x;
  3421. normals[ vB * 3 + 1 ] += cb.y;
  3422. normals[ vB * 3 + 2 ] += cb.z;
  3423. normals[ vC * 3 ] += cb.x;
  3424. normals[ vC * 3 + 1 ] += cb.y;
  3425. normals[ vC * 3 + 2 ] += cb.z;
  3426. }
  3427. }
  3428. // normalize normals
  3429. for ( i = 0, il = normals.length; i < il; i += 3 ) {
  3430. x = normals[ i ];
  3431. y = normals[ i + 1 ];
  3432. z = normals[ i + 2 ];
  3433. var n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  3434. normals[ i ] *= n;
  3435. normals[ i + 1 ] *= n;
  3436. normals[ i + 2 ] *= n;
  3437. }
  3438. this.normalsNeedUpdate = true;
  3439. }
  3440. },
  3441. computeTangents: function () {
  3442. // based on http://www.terathon.com/code/tangent.html
  3443. // (per vertex tangents)
  3444. if ( this.attributes[ "index" ] === undefined ||
  3445. this.attributes[ "position" ] === undefined ||
  3446. this.attributes[ "normal" ] === undefined ||
  3447. this.attributes[ "uv" ] === undefined ) {
  3448. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  3449. return;
  3450. }
  3451. var indices = this.attributes[ "index" ].array;
  3452. var positions = this.attributes[ "position" ].array;
  3453. var normals = this.attributes[ "normal" ].array;
  3454. var uvs = this.attributes[ "uv" ].array;
  3455. var nVertices = positions.length / 3;
  3456. if ( this.attributes[ "tangent" ] === undefined ) {
  3457. var nTangentElements = 4 * nVertices;
  3458. this.attributes[ "tangent" ] = {
  3459. itemSize: 4,
  3460. array: new Float32Array( nTangentElements ),
  3461. numItems: nTangentElements
  3462. };
  3463. }
  3464. var tangents = this.attributes[ "tangent" ].array;
  3465. var tan1 = [], tan2 = [];
  3466. for ( var k = 0; k < nVertices; k ++ ) {
  3467. tan1[ k ] = new THREE.Vector3();
  3468. tan2[ k ] = new THREE.Vector3();
  3469. }
  3470. var xA, yA, zA,
  3471. xB, yB, zB,
  3472. xC, yC, zC,
  3473. uA, vA,
  3474. uB, vB,
  3475. uC, vC,
  3476. x1, x2, y1, y2, z1, z2,
  3477. s1, s2, t1, t2, r;
  3478. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  3479. function handleTriangle( a, b, c ) {
  3480. xA = positions[ a * 3 ];
  3481. yA = positions[ a * 3 + 1 ];
  3482. zA = positions[ a * 3 + 2 ];
  3483. xB = positions[ b * 3 ];
  3484. yB = positions[ b * 3 + 1 ];
  3485. zB = positions[ b * 3 + 2 ];
  3486. xC = positions[ c * 3 ];
  3487. yC = positions[ c * 3 + 1 ];
  3488. zC = positions[ c * 3 + 2 ];
  3489. uA = uvs[ a * 2 ];
  3490. vA = uvs[ a * 2 + 1 ];
  3491. uB = uvs[ b * 2 ];
  3492. vB = uvs[ b * 2 + 1 ];
  3493. uC = uvs[ c * 2 ];
  3494. vC = uvs[ c * 2 + 1 ];
  3495. x1 = xB - xA;
  3496. x2 = xC - xA;
  3497. y1 = yB - yA;
  3498. y2 = yC - yA;
  3499. z1 = zB - zA;
  3500. z2 = zC - zA;
  3501. s1 = uB - uA;
  3502. s2 = uC - uA;
  3503. t1 = vB - vA;
  3504. t2 = vC - vA;
  3505. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3506. sdir.set(
  3507. ( t2 * x1 - t1 * x2 ) * r,
  3508. ( t2 * y1 - t1 * y2 ) * r,
  3509. ( t2 * z1 - t1 * z2 ) * r
  3510. );
  3511. tdir.set(
  3512. ( s1 * x2 - s2 * x1 ) * r,
  3513. ( s1 * y2 - s2 * y1 ) * r,
  3514. ( s1 * z2 - s2 * z1 ) * r
  3515. );
  3516. tan1[ a ].addSelf( sdir );
  3517. tan1[ b ].addSelf( sdir );
  3518. tan1[ c ].addSelf( sdir );
  3519. tan2[ a ].addSelf( tdir );
  3520. tan2[ b ].addSelf( tdir );
  3521. tan2[ c ].addSelf( tdir );
  3522. }
  3523. var i, il;
  3524. var j, jl;
  3525. var iA, iB, iC;
  3526. var offsets = this.offsets;
  3527. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3528. var start = offsets[ j ].start;
  3529. var count = offsets[ j ].count;
  3530. var index = offsets[ j ].index;
  3531. for ( i = start, il = start + count; i < il; i += 3 ) {
  3532. iA = index + indices[ i ];
  3533. iB = index + indices[ i + 1 ];
  3534. iC = index + indices[ i + 2 ];
  3535. handleTriangle( iA, iB, iC );
  3536. }
  3537. }
  3538. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  3539. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  3540. var w, t, test;
  3541. var nx, ny, nz;
  3542. function handleVertex( v ) {
  3543. n.x = normals[ v * 3 ];
  3544. n.y = normals[ v * 3 + 1 ];
  3545. n.z = normals[ v * 3 + 2 ];
  3546. n2.copy( n );
  3547. t = tan1[ v ];
  3548. // Gram-Schmidt orthogonalize
  3549. tmp.copy( t );
  3550. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3551. // Calculate handedness
  3552. tmp2.cross( n2, t );
  3553. test = tmp2.dot( tan2[ v ] );
  3554. w = ( test < 0.0 ) ? -1.0 : 1.0;
  3555. tangents[ v * 4 ] = tmp.x;
  3556. tangents[ v * 4 + 1 ] = tmp.y;
  3557. tangents[ v * 4 + 2 ] = tmp.z;
  3558. tangents[ v * 4 + 3 ] = w;
  3559. }
  3560. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3561. var start = offsets[ j ].start;
  3562. var count = offsets[ j ].count;
  3563. var index = offsets[ j ].index;
  3564. for ( i = start, il = start + count; i < il; i += 3 ) {
  3565. iA = index + indices[ i ];
  3566. iB = index + indices[ i + 1 ];
  3567. iC = index + indices[ i + 2 ];
  3568. handleVertex( iA );
  3569. handleVertex( iB );
  3570. handleVertex( iC );
  3571. }
  3572. }
  3573. this.hasTangents = true;
  3574. this.tangentsNeedUpdate = true;
  3575. }
  3576. };
  3577. /**
  3578. * Spline from Tween.js, slightly optimized (and trashed)
  3579. * http://sole.github.com/tween.js/examples/05_spline.html
  3580. *
  3581. * @author mrdoob / http://mrdoob.com/
  3582. * @author alteredq / http://alteredqualia.com/
  3583. */
  3584. THREE.Spline = function ( points ) {
  3585. this.points = points;
  3586. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3587. point, intPoint, weight, w2, w3,
  3588. pa, pb, pc, pd;
  3589. this.initFromArray = function( a ) {
  3590. this.points = [];
  3591. for ( var i = 0; i < a.length; i++ ) {
  3592. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3593. }
  3594. };
  3595. this.getPoint = function ( k ) {
  3596. point = ( this.points.length - 1 ) * k;
  3597. intPoint = Math.floor( point );
  3598. weight = point - intPoint;
  3599. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3600. c[ 1 ] = intPoint;
  3601. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3602. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3603. pa = this.points[ c[ 0 ] ];
  3604. pb = this.points[ c[ 1 ] ];
  3605. pc = this.points[ c[ 2 ] ];
  3606. pd = this.points[ c[ 3 ] ];
  3607. w2 = weight * weight;
  3608. w3 = weight * w2;
  3609. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3610. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3611. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3612. return v3;
  3613. };
  3614. this.getControlPointsArray = function () {
  3615. var i, p, l = this.points.length,
  3616. coords = [];
  3617. for ( i = 0; i < l; i ++ ) {
  3618. p = this.points[ i ];
  3619. coords[ i ] = [ p.x, p.y, p.z ];
  3620. }
  3621. return coords;
  3622. };
  3623. // approximate length by summing linear segments
  3624. this.getLength = function ( nSubDivisions ) {
  3625. var i, index, nSamples, position,
  3626. point = 0, intPoint = 0, oldIntPoint = 0,
  3627. oldPosition = new THREE.Vector3(),
  3628. tmpVec = new THREE.Vector3(),
  3629. chunkLengths = [],
  3630. totalLength = 0;
  3631. // first point has 0 length
  3632. chunkLengths[ 0 ] = 0;
  3633. if ( !nSubDivisions ) nSubDivisions = 100;
  3634. nSamples = this.points.length * nSubDivisions;
  3635. oldPosition.copy( this.points[ 0 ] );
  3636. for ( i = 1; i < nSamples; i ++ ) {
  3637. index = i / nSamples;
  3638. position = this.getPoint( index );
  3639. tmpVec.copy( position );
  3640. totalLength += tmpVec.distanceTo( oldPosition );
  3641. oldPosition.copy( position );
  3642. point = ( this.points.length - 1 ) * index;
  3643. intPoint = Math.floor( point );
  3644. if ( intPoint != oldIntPoint ) {
  3645. chunkLengths[ intPoint ] = totalLength;
  3646. oldIntPoint = intPoint;
  3647. }
  3648. }
  3649. // last point ends with total length
  3650. chunkLengths[ chunkLengths.length ] = totalLength;
  3651. return { chunks: chunkLengths, total: totalLength };
  3652. };
  3653. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3654. var i, j,
  3655. index, indexCurrent, indexNext,
  3656. linearDistance, realDistance,
  3657. sampling, position,
  3658. newpoints = [],
  3659. tmpVec = new THREE.Vector3(),
  3660. sl = this.getLength();
  3661. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3662. for ( i = 1; i < this.points.length; i++ ) {
  3663. //tmpVec.copy( this.points[ i - 1 ] );
  3664. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3665. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3666. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3667. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3668. indexNext = i / ( this.points.length - 1 );
  3669. for ( j = 1; j < sampling - 1; j++ ) {
  3670. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3671. position = this.getPoint( index );
  3672. newpoints.push( tmpVec.copy( position ).clone() );
  3673. }
  3674. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3675. }
  3676. this.points = newpoints;
  3677. };
  3678. // Catmull-Rom
  3679. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3680. var v0 = ( p2 - p0 ) * 0.5,
  3681. v1 = ( p3 - p1 ) * 0.5;
  3682. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3683. };
  3684. };
  3685. /**
  3686. * @author mrdoob / http://mrdoob.com/
  3687. * @author mikael emtinger / http://gomo.se/
  3688. */
  3689. THREE.Camera = function () {
  3690. THREE.Object3D.call( this );
  3691. this.matrixWorldInverse = new THREE.Matrix4();
  3692. this.projectionMatrix = new THREE.Matrix4();
  3693. this.projectionMatrixInverse = new THREE.Matrix4();
  3694. };
  3695. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  3696. THREE.Camera.prototype.lookAt = function ( vector ) {
  3697. // TODO: Add hierarchy support.
  3698. this.matrix.lookAt( this.position, vector, this.up );
  3699. if ( this.rotationAutoUpdate === true ) {
  3700. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  3701. }
  3702. };
  3703. /**
  3704. * @author alteredq / http://alteredqualia.com/
  3705. */
  3706. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  3707. THREE.Camera.call( this );
  3708. this.left = left;
  3709. this.right = right;
  3710. this.top = top;
  3711. this.bottom = bottom;
  3712. this.near = ( near !== undefined ) ? near : 0.1;
  3713. this.far = ( far !== undefined ) ? far : 2000;
  3714. this.updateProjectionMatrix();
  3715. };
  3716. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  3717. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  3718. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  3719. };
  3720. /**
  3721. * @author mrdoob / http://mrdoob.com/
  3722. * @author greggman / http://games.greggman.com/
  3723. * @author zz85 / http://www.lab4games.net/zz85/blog
  3724. */
  3725. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  3726. THREE.Camera.call( this );
  3727. this.fov = fov !== undefined ? fov : 50;
  3728. this.aspect = aspect !== undefined ? aspect : 1;
  3729. this.near = near !== undefined ? near : 0.1;
  3730. this.far = far !== undefined ? far : 2000;
  3731. this.updateProjectionMatrix();
  3732. };
  3733. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  3734. /**
  3735. * Uses Focal Length (in mm) to estimate and set FOV
  3736. * 35mm (fullframe) camera is used if frame size is not specified;
  3737. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  3738. */
  3739. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  3740. if ( frameHeight === undefined ) frameHeight = 24;
  3741. this.fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  3742. this.updateProjectionMatrix();
  3743. }
  3744. /**
  3745. * Sets an offset in a larger frustum. This is useful for multi-window or
  3746. * multi-monitor/multi-machine setups.
  3747. *
  3748. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  3749. * the monitors are in grid like this
  3750. *
  3751. * +---+---+---+
  3752. * | A | B | C |
  3753. * +---+---+---+
  3754. * | D | E | F |
  3755. * +---+---+---+
  3756. *
  3757. * then for each monitor you would call it like this
  3758. *
  3759. * var w = 1920;
  3760. * var h = 1080;
  3761. * var fullWidth = w * 3;
  3762. * var fullHeight = h * 2;
  3763. *
  3764. * --A--
  3765. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  3766. * --B--
  3767. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  3768. * --C--
  3769. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  3770. * --D--
  3771. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  3772. * --E--
  3773. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  3774. * --F--
  3775. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  3776. *
  3777. * Note there is no reason monitors have to be the same size or in a grid.
  3778. */
  3779. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  3780. this.fullWidth = fullWidth;
  3781. this.fullHeight = fullHeight;
  3782. this.x = x;
  3783. this.y = y;
  3784. this.width = width;
  3785. this.height = height;
  3786. this.updateProjectionMatrix();
  3787. };
  3788. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  3789. if ( this.fullWidth ) {
  3790. var aspect = this.fullWidth / this.fullHeight;
  3791. var top = Math.tan( this.fov * Math.PI / 360 ) * this.near;
  3792. var bottom = -top;
  3793. var left = aspect * bottom;
  3794. var right = aspect * top;
  3795. var width = Math.abs( right - left );
  3796. var height = Math.abs( top - bottom );
  3797. this.projectionMatrix.makeFrustum(
  3798. left + this.x * width / this.fullWidth,
  3799. left + ( this.x + this.width ) * width / this.fullWidth,
  3800. top - ( this.y + this.height ) * height / this.fullHeight,
  3801. top - this.y * height / this.fullHeight,
  3802. this.near,
  3803. this.far
  3804. );
  3805. } else {
  3806. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  3807. }
  3808. };
  3809. /**
  3810. * @author mrdoob / http://mrdoob.com/
  3811. * @author alteredq / http://alteredqualia.com/
  3812. */
  3813. THREE.Light = function ( hex ) {
  3814. THREE.Object3D.call( this );
  3815. this.color = new THREE.Color( hex );
  3816. };
  3817. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  3818. /**
  3819. * @author mrdoob / http://mrdoob.com/
  3820. */
  3821. THREE.AmbientLight = function ( hex ) {
  3822. THREE.Light.call( this, hex );
  3823. };
  3824. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  3825. /**
  3826. * @author mrdoob / http://mrdoob.com/
  3827. * @author alteredq / http://alteredqualia.com/
  3828. */
  3829. THREE.DirectionalLight = function ( hex, intensity, distance ) {
  3830. THREE.Light.call( this, hex );
  3831. this.position = new THREE.Vector3( 0, 1, 0 );
  3832. this.target = new THREE.Object3D();
  3833. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3834. this.distance = ( distance !== undefined ) ? distance : 0;
  3835. this.castShadow = false;
  3836. this.onlyShadow = false;
  3837. //
  3838. this.shadowCameraNear = 50;
  3839. this.shadowCameraFar = 5000;
  3840. this.shadowCameraLeft = -500;
  3841. this.shadowCameraRight = 500;
  3842. this.shadowCameraTop = 500;
  3843. this.shadowCameraBottom = -500;
  3844. this.shadowCameraVisible = false;
  3845. this.shadowBias = 0;
  3846. this.shadowDarkness = 0.5;
  3847. this.shadowMapWidth = 512;
  3848. this.shadowMapHeight = 512;
  3849. //
  3850. this.shadowCascade = false;
  3851. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  3852. this.shadowCascadeCount = 2;
  3853. this.shadowCascadeBias = [ 0, 0, 0 ];
  3854. this.shadowCascadeWidth = [ 512, 512, 512 ];
  3855. this.shadowCascadeHeight = [ 512, 512, 512 ];
  3856. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  3857. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  3858. this.shadowCascadeArray = [];
  3859. //
  3860. this.shadowMap = null;
  3861. this.shadowMapSize = null;
  3862. this.shadowCamera = null;
  3863. this.shadowMatrix = null;
  3864. };
  3865. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  3866. /**
  3867. * @author alteredq / http://alteredqualia.com/
  3868. */
  3869. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  3870. THREE.Light.call( this, skyColorHex );
  3871. this.groundColor = new THREE.Color( groundColorHex );
  3872. this.position = new THREE.Vector3( 0, 100, 0 );
  3873. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3874. };
  3875. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  3876. /**
  3877. * @author mrdoob / http://mrdoob.com/
  3878. */
  3879. THREE.PointLight = function ( hex, intensity, distance ) {
  3880. THREE.Light.call( this, hex );
  3881. this.position = new THREE.Vector3( 0, 0, 0 );
  3882. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3883. this.distance = ( distance !== undefined ) ? distance : 0;
  3884. };
  3885. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  3886. /**
  3887. * @author alteredq / http://alteredqualia.com/
  3888. */
  3889. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  3890. THREE.Light.call( this, hex );
  3891. this.position = new THREE.Vector3( 0, 1, 0 );
  3892. this.target = new THREE.Object3D();
  3893. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3894. this.distance = ( distance !== undefined ) ? distance : 0;
  3895. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  3896. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  3897. this.castShadow = false;
  3898. this.onlyShadow = false;
  3899. //
  3900. this.shadowCameraNear = 50;
  3901. this.shadowCameraFar = 5000;
  3902. this.shadowCameraFov = 50;
  3903. this.shadowCameraVisible = false;
  3904. this.shadowBias = 0;
  3905. this.shadowDarkness = 0.5;
  3906. this.shadowMapWidth = 512;
  3907. this.shadowMapHeight = 512;
  3908. //
  3909. this.shadowMap = null;
  3910. this.shadowMapSize = null;
  3911. this.shadowCamera = null;
  3912. this.shadowMatrix = null;
  3913. };
  3914. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  3915. /**
  3916. * @author alteredq / http://alteredqualia.com/
  3917. */
  3918. THREE.Loader = function ( showStatus ) {
  3919. this.showStatus = showStatus;
  3920. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  3921. this.onLoadStart = function () {};
  3922. this.onLoadProgress = function () {};
  3923. this.onLoadComplete = function () {};
  3924. };
  3925. THREE.Loader.prototype = {
  3926. constructor: THREE.Loader,
  3927. crossOrigin: 'anonymous',
  3928. addStatusElement: function () {
  3929. var e = document.createElement( "div" );
  3930. e.style.position = "absolute";
  3931. e.style.right = "0px";
  3932. e.style.top = "0px";
  3933. e.style.fontSize = "0.8em";
  3934. e.style.textAlign = "left";
  3935. e.style.background = "rgba(0,0,0,0.25)";
  3936. e.style.color = "#fff";
  3937. e.style.width = "120px";
  3938. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  3939. e.style.zIndex = 1000;
  3940. e.innerHTML = "Loading ...";
  3941. return e;
  3942. },
  3943. updateProgress: function ( progress ) {
  3944. var message = "Loaded ";
  3945. if ( progress.total ) {
  3946. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  3947. } else {
  3948. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  3949. }
  3950. this.statusDomElement.innerHTML = message;
  3951. },
  3952. extractUrlBase: function ( url ) {
  3953. var parts = url.split( '/' );
  3954. parts.pop();
  3955. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  3956. },
  3957. initMaterials: function ( scope, materials, texturePath ) {
  3958. scope.materials = [];
  3959. for ( var i = 0; i < materials.length; ++ i ) {
  3960. scope.materials[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  3961. }
  3962. },
  3963. hasNormals: function ( scope ) {
  3964. var m, i, il = scope.materials.length;
  3965. for( i = 0; i < il; i ++ ) {
  3966. m = scope.materials[ i ];
  3967. if ( m instanceof THREE.ShaderMaterial ) return true;
  3968. }
  3969. return false;
  3970. },
  3971. createMaterial: function ( m, texturePath ) {
  3972. var _this = this;
  3973. function is_pow2( n ) {
  3974. var l = Math.log( n ) / Math.LN2;
  3975. return Math.floor( l ) == l;
  3976. }
  3977. function nearest_pow2( n ) {
  3978. var l = Math.log( n ) / Math.LN2;
  3979. return Math.pow( 2, Math.round( l ) );
  3980. }
  3981. function load_image( where, url ) {
  3982. var image = new Image();
  3983. image.onload = function () {
  3984. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  3985. var width = nearest_pow2( this.width );
  3986. var height = nearest_pow2( this.height );
  3987. where.image.width = width;
  3988. where.image.height = height;
  3989. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  3990. } else {
  3991. where.image = this;
  3992. }
  3993. where.needsUpdate = true;
  3994. };
  3995. image.crossOrigin = _this.crossOrigin;
  3996. image.src = url;
  3997. }
  3998. function create_texture( where, name, sourceFile, repeat, offset, wrap ) {
  3999. var texture = document.createElement( 'canvas' );
  4000. where[ name ] = new THREE.Texture( texture );
  4001. where[ name ].sourceFile = sourceFile;
  4002. if( repeat ) {
  4003. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  4004. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  4005. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  4006. }
  4007. if ( offset ) {
  4008. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  4009. }
  4010. if ( wrap ) {
  4011. var wrapMap = {
  4012. "repeat": THREE.RepeatWrapping,
  4013. "mirror": THREE.MirroredRepeatWrapping
  4014. }
  4015. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  4016. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  4017. }
  4018. load_image( where[ name ], texturePath + "/" + sourceFile );
  4019. }
  4020. function rgb2hex( rgb ) {
  4021. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  4022. }
  4023. // defaults
  4024. var mtype = "MeshLambertMaterial";
  4025. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  4026. // parameters from model file
  4027. if ( m.shading ) {
  4028. var shading = m.shading.toLowerCase();
  4029. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  4030. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  4031. }
  4032. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  4033. mpars.blending = THREE[ m.blending ];
  4034. }
  4035. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  4036. mpars.transparent = m.transparent;
  4037. }
  4038. if ( m.depthTest !== undefined ) {
  4039. mpars.depthTest = m.depthTest;
  4040. }
  4041. if ( m.depthWrite !== undefined ) {
  4042. mpars.depthWrite = m.depthWrite;
  4043. }
  4044. if ( m.visible !== undefined ) {
  4045. mpars.visible = m.visible;
  4046. }
  4047. if ( m.flipSided !== undefined ) {
  4048. mpars.side = THREE.BackSide;
  4049. }
  4050. if ( m.doubleSided !== undefined ) {
  4051. mpars.side = THREE.DoubleSide;
  4052. }
  4053. if ( m.wireframe !== undefined ) {
  4054. mpars.wireframe = m.wireframe;
  4055. }
  4056. if ( m.vertexColors !== undefined ) {
  4057. if ( m.vertexColors == "face" ) {
  4058. mpars.vertexColors = THREE.FaceColors;
  4059. } else if ( m.vertexColors ) {
  4060. mpars.vertexColors = THREE.VertexColors;
  4061. }
  4062. }
  4063. // colors
  4064. if ( m.colorDiffuse ) {
  4065. mpars.color = rgb2hex( m.colorDiffuse );
  4066. } else if ( m.DbgColor ) {
  4067. mpars.color = m.DbgColor;
  4068. }
  4069. if ( m.colorSpecular ) {
  4070. mpars.specular = rgb2hex( m.colorSpecular );
  4071. }
  4072. if ( m.colorAmbient ) {
  4073. mpars.ambient = rgb2hex( m.colorAmbient );
  4074. }
  4075. // modifiers
  4076. if ( m.transparency ) {
  4077. mpars.opacity = m.transparency;
  4078. }
  4079. if ( m.specularCoef ) {
  4080. mpars.shininess = m.specularCoef;
  4081. }
  4082. // textures
  4083. if ( m.mapDiffuse && texturePath ) {
  4084. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap );
  4085. }
  4086. if ( m.mapLight && texturePath ) {
  4087. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap );
  4088. }
  4089. if ( m.mapBump && texturePath ) {
  4090. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap );
  4091. }
  4092. if ( m.mapNormal && texturePath ) {
  4093. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap );
  4094. }
  4095. if ( m.mapSpecular && texturePath ) {
  4096. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap );
  4097. }
  4098. // special case for normal mapped material
  4099. if ( m.mapNormal ) {
  4100. var shader = THREE.ShaderUtils.lib[ "normal" ];
  4101. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  4102. uniforms[ "tNormal" ].value = mpars.normalMap;
  4103. if ( m.mapNormalFactor ) {
  4104. uniforms[ "uNormalScale" ].value = m.mapNormalFactor;
  4105. }
  4106. if ( mpars.map ) {
  4107. uniforms[ "tDiffuse" ].value = mpars.map;
  4108. uniforms[ "enableDiffuse" ].value = true;
  4109. }
  4110. if ( mpars.specularMap ) {
  4111. uniforms[ "tSpecular" ].value = mpars.specularMap;
  4112. uniforms[ "enableSpecular" ].value = true;
  4113. }
  4114. if ( mpars.lightMap ) {
  4115. uniforms[ "tAO" ].value = mpars.lightMap;
  4116. uniforms[ "enableAO" ].value = true;
  4117. }
  4118. // for the moment don't handle displacement texture
  4119. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  4120. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  4121. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  4122. uniforms[ "uShininess" ].value = mpars.shininess;
  4123. if ( mpars.opacity !== undefined ) {
  4124. uniforms[ "uOpacity" ].value = mpars.opacity;
  4125. }
  4126. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  4127. var material = new THREE.ShaderMaterial( parameters );
  4128. } else {
  4129. var material = new THREE[ mtype ]( mpars );
  4130. }
  4131. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  4132. return material;
  4133. }
  4134. };
  4135. /**
  4136. * @author alteredq / http://alteredqualia.com/
  4137. */
  4138. THREE.BinaryLoader = function ( showStatus ) {
  4139. THREE.Loader.call( this, showStatus );
  4140. };
  4141. THREE.BinaryLoader.prototype = Object.create( THREE.Loader.prototype );
  4142. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  4143. // - binary models consist of two files: JS and BIN
  4144. // - parameters
  4145. // - url (required)
  4146. // - callback (required)
  4147. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  4148. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  4149. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  4150. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  4151. binaryPath = binaryPath ? binaryPath : this.extractUrlBase( url );
  4152. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  4153. this.onLoadStart();
  4154. // #1 load JS part via web worker
  4155. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  4156. };
  4157. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  4158. var xhr = new XMLHttpRequest();
  4159. xhr.onreadystatechange = function () {
  4160. if ( xhr.readyState == 4 ) {
  4161. if ( xhr.status == 200 || xhr.status == 0 ) {
  4162. var json = JSON.parse( xhr.responseText );
  4163. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  4164. } else {
  4165. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4166. }
  4167. }
  4168. };
  4169. xhr.open( "GET", url, true );
  4170. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  4171. xhr.setRequestHeader( "Content-Type", "text/plain" );
  4172. xhr.send( null );
  4173. };
  4174. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  4175. var xhr = new XMLHttpRequest(),
  4176. url = binaryPath + "/" + json.buffers;
  4177. var length = 0;
  4178. xhr.onreadystatechange = function () {
  4179. if ( xhr.readyState == 4 ) {
  4180. if ( xhr.status == 200 || xhr.status == 0 ) {
  4181. var buffer = xhr.response;
  4182. if ( buffer === undefined ) buffer = ( new Uint8Array( xhr.responseBody ) ).buffer; // IEWEBGL needs this
  4183. THREE.BinaryLoader.prototype.createBinModel( buffer, callback, texturePath, json.materials );
  4184. } else {
  4185. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4186. }
  4187. } else if ( xhr.readyState == 3 ) {
  4188. if ( callbackProgress ) {
  4189. if ( length == 0 ) {
  4190. length = xhr.getResponseHeader( "Content-Length" );
  4191. }
  4192. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4193. }
  4194. } else if ( xhr.readyState == 2 ) {
  4195. length = xhr.getResponseHeader( "Content-Length" );
  4196. }
  4197. };
  4198. xhr.open( "GET", url, true );
  4199. xhr.responseType = "arraybuffer";
  4200. xhr.send( null );
  4201. };
  4202. // Binary AJAX parser
  4203. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, materials ) {
  4204. var Model = function ( texturePath ) {
  4205. var scope = this,
  4206. currentOffset = 0,
  4207. md,
  4208. normals = [],
  4209. uvs = [],
  4210. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  4211. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  4212. tri_size, quad_size,
  4213. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  4214. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  4215. THREE.Geometry.call( this );
  4216. THREE.Loader.prototype.initMaterials( scope, materials, texturePath );
  4217. md = parseMetaData( data, currentOffset );
  4218. currentOffset += md.header_bytes;
  4219. /*
  4220. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4221. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  4222. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4223. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4224. */
  4225. // buffers sizes
  4226. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  4227. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  4228. len_tri_flat = md.ntri_flat * ( tri_size );
  4229. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  4230. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  4231. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  4232. len_quad_flat = md.nquad_flat * ( quad_size );
  4233. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  4234. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  4235. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  4236. // read buffers
  4237. currentOffset += init_vertices( currentOffset );
  4238. currentOffset += init_normals( currentOffset );
  4239. currentOffset += handlePadding( md.nnormals * 3 );
  4240. currentOffset += init_uvs( currentOffset );
  4241. start_tri_flat = currentOffset;
  4242. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  4243. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  4244. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  4245. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  4246. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  4247. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  4248. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  4249. // have to first process faces with uvs
  4250. // so that face and uv indices match
  4251. init_triangles_flat_uv( start_tri_flat_uv );
  4252. init_triangles_smooth_uv( start_tri_smooth_uv );
  4253. init_quads_flat_uv( start_quad_flat_uv );
  4254. init_quads_smooth_uv( start_quad_smooth_uv );
  4255. // now we can process untextured faces
  4256. init_triangles_flat( start_tri_flat );
  4257. init_triangles_smooth( start_tri_smooth );
  4258. init_quads_flat( start_quad_flat );
  4259. init_quads_smooth( start_quad_smooth );
  4260. this.computeCentroids();
  4261. this.computeFaceNormals();
  4262. if ( THREE.Loader.prototype.hasNormals( this ) ) this.computeTangents();
  4263. function handlePadding( n ) {
  4264. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  4265. };
  4266. function parseMetaData( data, offset ) {
  4267. var metaData = {
  4268. 'signature' :parseString( data, offset, 12 ),
  4269. 'header_bytes' :parseUChar8( data, offset + 12 ),
  4270. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  4271. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  4272. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  4273. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  4274. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  4275. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  4276. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  4277. 'nvertices' :parseUInt32( data, offset + 20 ),
  4278. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  4279. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  4280. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  4281. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  4282. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  4283. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  4284. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  4285. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  4286. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  4287. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  4288. };
  4289. /*
  4290. console.log( "signature: " + metaData.signature );
  4291. console.log( "header_bytes: " + metaData.header_bytes );
  4292. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  4293. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  4294. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  4295. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  4296. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  4297. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  4298. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  4299. console.log( "nvertices: " + metaData.nvertices );
  4300. console.log( "nnormals: " + metaData.nnormals );
  4301. console.log( "nuvs: " + metaData.nuvs );
  4302. console.log( "ntri_flat: " + metaData.ntri_flat );
  4303. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  4304. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  4305. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  4306. console.log( "nquad_flat: " + metaData.nquad_flat );
  4307. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  4308. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  4309. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  4310. var total = metaData.header_bytes
  4311. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  4312. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  4313. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  4314. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  4315. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  4316. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  4317. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  4318. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  4319. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  4320. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  4321. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  4322. console.log( "total bytes: " + total );
  4323. */
  4324. return metaData;
  4325. };
  4326. function parseString( data, offset, length ) {
  4327. var charArray = new Uint8Array( data, offset, length );
  4328. var text = "";
  4329. for ( var i = 0; i < length; i ++ ) {
  4330. text += String.fromCharCode( charArray[ offset + i ] );
  4331. }
  4332. return text;
  4333. };
  4334. function parseUChar8( data, offset ) {
  4335. var charArray = new Uint8Array( data, offset, 1 );
  4336. return charArray[ 0 ];
  4337. };
  4338. function parseUInt32( data, offset ) {
  4339. var intArray = new Uint32Array( data, offset, 1 );
  4340. return intArray[ 0 ];
  4341. };
  4342. function init_vertices( start ) {
  4343. var nElements = md.nvertices;
  4344. var coordArray = new Float32Array( data, start, nElements * 3 );
  4345. var i, x, y, z;
  4346. for( i = 0; i < nElements; i ++ ) {
  4347. x = coordArray[ i * 3 ];
  4348. y = coordArray[ i * 3 + 1 ];
  4349. z = coordArray[ i * 3 + 2 ];
  4350. vertex( scope, x, y, z );
  4351. }
  4352. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  4353. };
  4354. function init_normals( start ) {
  4355. var nElements = md.nnormals;
  4356. if ( nElements ) {
  4357. var normalArray = new Int8Array( data, start, nElements * 3 );
  4358. var i, x, y, z;
  4359. for( i = 0; i < nElements; i ++ ) {
  4360. x = normalArray[ i * 3 ];
  4361. y = normalArray[ i * 3 + 1 ];
  4362. z = normalArray[ i * 3 + 2 ];
  4363. normals.push( x/127, y/127, z/127 );
  4364. }
  4365. }
  4366. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  4367. };
  4368. function init_uvs( start ) {
  4369. var nElements = md.nuvs;
  4370. if ( nElements ) {
  4371. var uvArray = new Float32Array( data, start, nElements * 2 );
  4372. var i, u, v;
  4373. for( i = 0; i < nElements; i ++ ) {
  4374. u = uvArray[ i * 2 ];
  4375. v = uvArray[ i * 2 + 1 ];
  4376. uvs.push( u, v );
  4377. }
  4378. }
  4379. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  4380. };
  4381. function init_uvs3( nElements, offset ) {
  4382. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  4383. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  4384. for( i = 0; i < nElements; i ++ ) {
  4385. uva = uvIndexBuffer[ i * 3 ];
  4386. uvb = uvIndexBuffer[ i * 3 + 1 ];
  4387. uvc = uvIndexBuffer[ i * 3 + 2 ];
  4388. u1 = uvs[ uva*2 ];
  4389. v1 = uvs[ uva*2 + 1 ];
  4390. u2 = uvs[ uvb*2 ];
  4391. v2 = uvs[ uvb*2 + 1 ];
  4392. u3 = uvs[ uvc*2 ];
  4393. v3 = uvs[ uvc*2 + 1 ];
  4394. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  4395. }
  4396. };
  4397. function init_uvs4( nElements, offset ) {
  4398. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  4399. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  4400. for( i = 0; i < nElements; i ++ ) {
  4401. uva = uvIndexBuffer[ i * 4 ];
  4402. uvb = uvIndexBuffer[ i * 4 + 1 ];
  4403. uvc = uvIndexBuffer[ i * 4 + 2 ];
  4404. uvd = uvIndexBuffer[ i * 4 + 3 ];
  4405. u1 = uvs[ uva*2 ];
  4406. v1 = uvs[ uva*2 + 1 ];
  4407. u2 = uvs[ uvb*2 ];
  4408. v2 = uvs[ uvb*2 + 1 ];
  4409. u3 = uvs[ uvc*2 ];
  4410. v3 = uvs[ uvc*2 + 1 ];
  4411. u4 = uvs[ uvd*2 ];
  4412. v4 = uvs[ uvd*2 + 1 ];
  4413. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  4414. }
  4415. };
  4416. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  4417. var i, a, b, c, m;
  4418. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4419. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4420. for( i = 0; i < nElements; i ++ ) {
  4421. a = vertexIndexBuffer[ i * 3 ];
  4422. b = vertexIndexBuffer[ i * 3 + 1 ];
  4423. c = vertexIndexBuffer[ i * 3 + 2 ];
  4424. m = materialIndexBuffer[ i ];
  4425. f3( scope, a, b, c, m );
  4426. }
  4427. };
  4428. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  4429. var i, a, b, c, d, m;
  4430. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4431. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4432. for( i = 0; i < nElements; i ++ ) {
  4433. a = vertexIndexBuffer[ i * 4 ];
  4434. b = vertexIndexBuffer[ i * 4 + 1 ];
  4435. c = vertexIndexBuffer[ i * 4 + 2 ];
  4436. d = vertexIndexBuffer[ i * 4 + 3 ];
  4437. m = materialIndexBuffer[ i ];
  4438. f4( scope, a, b, c, d, m );
  4439. }
  4440. };
  4441. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4442. var i, a, b, c, m;
  4443. var na, nb, nc;
  4444. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4445. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  4446. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4447. for( i = 0; i < nElements; i ++ ) {
  4448. a = vertexIndexBuffer[ i * 3 ];
  4449. b = vertexIndexBuffer[ i * 3 + 1 ];
  4450. c = vertexIndexBuffer[ i * 3 + 2 ];
  4451. na = normalIndexBuffer[ i * 3 ];
  4452. nb = normalIndexBuffer[ i * 3 + 1 ];
  4453. nc = normalIndexBuffer[ i * 3 + 2 ];
  4454. m = materialIndexBuffer[ i ];
  4455. f3n( scope, normals, a, b, c, m, na, nb, nc );
  4456. }
  4457. };
  4458. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4459. var i, a, b, c, d, m;
  4460. var na, nb, nc, nd;
  4461. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4462. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  4463. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4464. for( i = 0; i < nElements; i ++ ) {
  4465. a = vertexIndexBuffer[ i * 4 ];
  4466. b = vertexIndexBuffer[ i * 4 + 1 ];
  4467. c = vertexIndexBuffer[ i * 4 + 2 ];
  4468. d = vertexIndexBuffer[ i * 4 + 3 ];
  4469. na = normalIndexBuffer[ i * 4 ];
  4470. nb = normalIndexBuffer[ i * 4 + 1 ];
  4471. nc = normalIndexBuffer[ i * 4 + 2 ];
  4472. nd = normalIndexBuffer[ i * 4 + 3 ];
  4473. m = materialIndexBuffer[ i ];
  4474. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  4475. }
  4476. };
  4477. function init_triangles_flat( start ) {
  4478. var nElements = md.ntri_flat;
  4479. if ( nElements ) {
  4480. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4481. init_faces3_flat( nElements, start, offsetMaterials );
  4482. }
  4483. };
  4484. function init_triangles_flat_uv( start ) {
  4485. var nElements = md.ntri_flat_uv;
  4486. if ( nElements ) {
  4487. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4488. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4489. init_faces3_flat( nElements, start, offsetMaterials );
  4490. init_uvs3( nElements, offsetUvs );
  4491. }
  4492. };
  4493. function init_triangles_smooth( start ) {
  4494. var nElements = md.ntri_smooth;
  4495. if ( nElements ) {
  4496. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4497. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4498. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4499. }
  4500. };
  4501. function init_triangles_smooth_uv( start ) {
  4502. var nElements = md.ntri_smooth_uv;
  4503. if ( nElements ) {
  4504. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4505. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4506. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4507. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4508. init_uvs3( nElements, offsetUvs );
  4509. }
  4510. };
  4511. function init_quads_flat( start ) {
  4512. var nElements = md.nquad_flat;
  4513. if ( nElements ) {
  4514. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4515. init_faces4_flat( nElements, start, offsetMaterials );
  4516. }
  4517. };
  4518. function init_quads_flat_uv( start ) {
  4519. var nElements = md.nquad_flat_uv;
  4520. if ( nElements ) {
  4521. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4522. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4523. init_faces4_flat( nElements, start, offsetMaterials );
  4524. init_uvs4( nElements, offsetUvs );
  4525. }
  4526. };
  4527. function init_quads_smooth( start ) {
  4528. var nElements = md.nquad_smooth;
  4529. if ( nElements ) {
  4530. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4531. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4532. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4533. }
  4534. };
  4535. function init_quads_smooth_uv( start ) {
  4536. var nElements = md.nquad_smooth_uv;
  4537. if ( nElements ) {
  4538. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4539. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4540. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4541. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4542. init_uvs4( nElements, offsetUvs );
  4543. }
  4544. };
  4545. };
  4546. function vertex ( scope, x, y, z ) {
  4547. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  4548. };
  4549. function f3 ( scope, a, b, c, mi ) {
  4550. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  4551. };
  4552. function f4 ( scope, a, b, c, d, mi ) {
  4553. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  4554. };
  4555. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  4556. var nax = normals[ na*3 ],
  4557. nay = normals[ na*3 + 1 ],
  4558. naz = normals[ na*3 + 2 ],
  4559. nbx = normals[ nb*3 ],
  4560. nby = normals[ nb*3 + 1 ],
  4561. nbz = normals[ nb*3 + 2 ],
  4562. ncx = normals[ nc*3 ],
  4563. ncy = normals[ nc*3 + 1 ],
  4564. ncz = normals[ nc*3 + 2 ];
  4565. scope.faces.push( new THREE.Face3( a, b, c,
  4566. [new THREE.Vector3( nax, nay, naz ),
  4567. new THREE.Vector3( nbx, nby, nbz ),
  4568. new THREE.Vector3( ncx, ncy, ncz )],
  4569. null,
  4570. mi ) );
  4571. };
  4572. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  4573. var nax = normals[ na*3 ],
  4574. nay = normals[ na*3 + 1 ],
  4575. naz = normals[ na*3 + 2 ],
  4576. nbx = normals[ nb*3 ],
  4577. nby = normals[ nb*3 + 1 ],
  4578. nbz = normals[ nb*3 + 2 ],
  4579. ncx = normals[ nc*3 ],
  4580. ncy = normals[ nc*3 + 1 ],
  4581. ncz = normals[ nc*3 + 2 ],
  4582. ndx = normals[ nd*3 ],
  4583. ndy = normals[ nd*3 + 1 ],
  4584. ndz = normals[ nd*3 + 2 ];
  4585. scope.faces.push( new THREE.Face4( a, b, c, d,
  4586. [new THREE.Vector3( nax, nay, naz ),
  4587. new THREE.Vector3( nbx, nby, nbz ),
  4588. new THREE.Vector3( ncx, ncy, ncz ),
  4589. new THREE.Vector3( ndx, ndy, ndz )],
  4590. null,
  4591. mi ) );
  4592. };
  4593. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  4594. var uv = [];
  4595. uv.push( new THREE.UV( u1, v1 ) );
  4596. uv.push( new THREE.UV( u2, v2 ) );
  4597. uv.push( new THREE.UV( u3, v3 ) );
  4598. where.push( uv );
  4599. };
  4600. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  4601. var uv = [];
  4602. uv.push( new THREE.UV( u1, v1 ) );
  4603. uv.push( new THREE.UV( u2, v2 ) );
  4604. uv.push( new THREE.UV( u3, v3 ) );
  4605. uv.push( new THREE.UV( u4, v4 ) );
  4606. where.push( uv );
  4607. };
  4608. Model.prototype = Object.create( THREE.Geometry.prototype );
  4609. callback( new Model( texturePath ) );
  4610. };
  4611. /**
  4612. * @author mrdoob / http://mrdoob.com/
  4613. */
  4614. THREE.ImageLoader = function () {
  4615. THREE.EventTarget.call( this );
  4616. this.crossOrigin = null;
  4617. };
  4618. THREE.ImageLoader.prototype = {
  4619. constructor: THREE.ImageLoader,
  4620. load: function ( url, image ) {
  4621. var scope = this;
  4622. if ( image === undefined ) image = new Image();
  4623. image.addEventListener( 'load', function () {
  4624. scope.dispatchEvent( { type: 'load', content: image } );
  4625. }, false );
  4626. image.addEventListener( 'error', function () {
  4627. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  4628. }, false );
  4629. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  4630. image.src = url;
  4631. }
  4632. }
  4633. /**
  4634. * @author mrdoob / http://mrdoob.com/
  4635. * @author alteredq / http://alteredqualia.com/
  4636. */
  4637. THREE.JSONLoader = function ( showStatus ) {
  4638. THREE.Loader.call( this, showStatus );
  4639. };
  4640. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  4641. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  4642. var scope = this;
  4643. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  4644. this.onLoadStart();
  4645. this.loadAjaxJSON( this, url, callback, texturePath );
  4646. };
  4647. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  4648. var xhr = new XMLHttpRequest();
  4649. var length = 0;
  4650. xhr.onreadystatechange = function () {
  4651. if ( xhr.readyState === xhr.DONE ) {
  4652. if ( xhr.status === 200 || xhr.status === 0 ) {
  4653. if ( xhr.responseText ) {
  4654. var json = JSON.parse( xhr.responseText );
  4655. context.createModel( json, callback, texturePath );
  4656. } else {
  4657. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  4658. }
  4659. // in context of more complex asset initialization
  4660. // do not block on single failed file
  4661. // maybe should go even one more level up
  4662. context.onLoadComplete();
  4663. } else {
  4664. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4665. }
  4666. } else if ( xhr.readyState === xhr.LOADING ) {
  4667. if ( callbackProgress ) {
  4668. if ( length === 0 ) {
  4669. length = xhr.getResponseHeader( "Content-Length" );
  4670. }
  4671. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4672. }
  4673. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  4674. length = xhr.getResponseHeader( "Content-Length" );
  4675. }
  4676. };
  4677. xhr.open( "GET", url, true );
  4678. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "application/json; charset=x-user-defined" );
  4679. xhr.setRequestHeader( "Content-Type", "application/json" );
  4680. xhr.send( null );
  4681. };
  4682. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  4683. var scope = this,
  4684. geometry = new THREE.Geometry(),
  4685. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  4686. this.initMaterials( geometry, json.materials, texturePath );
  4687. parseModel( scale );
  4688. parseSkin();
  4689. parseMorphing( scale );
  4690. geometry.computeCentroids();
  4691. geometry.computeFaceNormals();
  4692. if ( this.hasNormals( geometry ) ) geometry.computeTangents();
  4693. function parseModel( scale ) {
  4694. function isBitSet( value, position ) {
  4695. return value & ( 1 << position );
  4696. }
  4697. var i, j, fi,
  4698. offset, zLength, nVertices,
  4699. colorIndex, normalIndex, uvIndex, materialIndex,
  4700. type,
  4701. isQuad,
  4702. hasMaterial,
  4703. hasFaceUv, hasFaceVertexUv,
  4704. hasFaceNormal, hasFaceVertexNormal,
  4705. hasFaceColor, hasFaceVertexColor,
  4706. vertex, face, color, normal,
  4707. uvLayer, uvs, u, v,
  4708. faces = json.faces,
  4709. vertices = json.vertices,
  4710. normals = json.normals,
  4711. colors = json.colors,
  4712. nUvLayers = 0;
  4713. // disregard empty arrays
  4714. for ( i = 0; i < json.uvs.length; i++ ) {
  4715. if ( json.uvs[ i ].length ) nUvLayers ++;
  4716. }
  4717. for ( i = 0; i < nUvLayers; i++ ) {
  4718. geometry.faceUvs[ i ] = [];
  4719. geometry.faceVertexUvs[ i ] = [];
  4720. }
  4721. offset = 0;
  4722. zLength = vertices.length;
  4723. while ( offset < zLength ) {
  4724. vertex = new THREE.Vector3();
  4725. vertex.x = vertices[ offset ++ ] * scale;
  4726. vertex.y = vertices[ offset ++ ] * scale;
  4727. vertex.z = vertices[ offset ++ ] * scale;
  4728. geometry.vertices.push( vertex );
  4729. }
  4730. offset = 0;
  4731. zLength = faces.length;
  4732. while ( offset < zLength ) {
  4733. type = faces[ offset ++ ];
  4734. isQuad = isBitSet( type, 0 );
  4735. hasMaterial = isBitSet( type, 1 );
  4736. hasFaceUv = isBitSet( type, 2 );
  4737. hasFaceVertexUv = isBitSet( type, 3 );
  4738. hasFaceNormal = isBitSet( type, 4 );
  4739. hasFaceVertexNormal = isBitSet( type, 5 );
  4740. hasFaceColor = isBitSet( type, 6 );
  4741. hasFaceVertexColor = isBitSet( type, 7 );
  4742. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  4743. if ( isQuad ) {
  4744. face = new THREE.Face4();
  4745. face.a = faces[ offset ++ ];
  4746. face.b = faces[ offset ++ ];
  4747. face.c = faces[ offset ++ ];
  4748. face.d = faces[ offset ++ ];
  4749. nVertices = 4;
  4750. } else {
  4751. face = new THREE.Face3();
  4752. face.a = faces[ offset ++ ];
  4753. face.b = faces[ offset ++ ];
  4754. face.c = faces[ offset ++ ];
  4755. nVertices = 3;
  4756. }
  4757. if ( hasMaterial ) {
  4758. materialIndex = faces[ offset ++ ];
  4759. face.materialIndex = materialIndex;
  4760. }
  4761. // to get face <=> uv index correspondence
  4762. fi = geometry.faces.length;
  4763. if ( hasFaceUv ) {
  4764. for ( i = 0; i < nUvLayers; i++ ) {
  4765. uvLayer = json.uvs[ i ];
  4766. uvIndex = faces[ offset ++ ];
  4767. u = uvLayer[ uvIndex * 2 ];
  4768. v = uvLayer[ uvIndex * 2 + 1 ];
  4769. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  4770. }
  4771. }
  4772. if ( hasFaceVertexUv ) {
  4773. for ( i = 0; i < nUvLayers; i++ ) {
  4774. uvLayer = json.uvs[ i ];
  4775. uvs = [];
  4776. for ( j = 0; j < nVertices; j ++ ) {
  4777. uvIndex = faces[ offset ++ ];
  4778. u = uvLayer[ uvIndex * 2 ];
  4779. v = uvLayer[ uvIndex * 2 + 1 ];
  4780. uvs[ j ] = new THREE.UV( u, v );
  4781. }
  4782. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  4783. }
  4784. }
  4785. if ( hasFaceNormal ) {
  4786. normalIndex = faces[ offset ++ ] * 3;
  4787. normal = new THREE.Vector3();
  4788. normal.x = normals[ normalIndex ++ ];
  4789. normal.y = normals[ normalIndex ++ ];
  4790. normal.z = normals[ normalIndex ];
  4791. face.normal = normal;
  4792. }
  4793. if ( hasFaceVertexNormal ) {
  4794. for ( i = 0; i < nVertices; i++ ) {
  4795. normalIndex = faces[ offset ++ ] * 3;
  4796. normal = new THREE.Vector3();
  4797. normal.x = normals[ normalIndex ++ ];
  4798. normal.y = normals[ normalIndex ++ ];
  4799. normal.z = normals[ normalIndex ];
  4800. face.vertexNormals.push( normal );
  4801. }
  4802. }
  4803. if ( hasFaceColor ) {
  4804. colorIndex = faces[ offset ++ ];
  4805. color = new THREE.Color( colors[ colorIndex ] );
  4806. face.color = color;
  4807. }
  4808. if ( hasFaceVertexColor ) {
  4809. for ( i = 0; i < nVertices; i++ ) {
  4810. colorIndex = faces[ offset ++ ];
  4811. color = new THREE.Color( colors[ colorIndex ] );
  4812. face.vertexColors.push( color );
  4813. }
  4814. }
  4815. geometry.faces.push( face );
  4816. }
  4817. };
  4818. function parseSkin() {
  4819. var i, l, x, y, z, w, a, b, c, d;
  4820. if ( json.skinWeights ) {
  4821. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  4822. x = json.skinWeights[ i ];
  4823. y = json.skinWeights[ i + 1 ];
  4824. z = 0;
  4825. w = 0;
  4826. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  4827. }
  4828. }
  4829. if ( json.skinIndices ) {
  4830. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  4831. a = json.skinIndices[ i ];
  4832. b = json.skinIndices[ i + 1 ];
  4833. c = 0;
  4834. d = 0;
  4835. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  4836. }
  4837. }
  4838. geometry.bones = json.bones;
  4839. geometry.animation = json.animation;
  4840. };
  4841. function parseMorphing( scale ) {
  4842. if ( json.morphTargets !== undefined ) {
  4843. var i, l, v, vl, dstVertices, srcVertices;
  4844. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  4845. geometry.morphTargets[ i ] = {};
  4846. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  4847. geometry.morphTargets[ i ].vertices = [];
  4848. dstVertices = geometry.morphTargets[ i ].vertices;
  4849. srcVertices = json.morphTargets [ i ].vertices;
  4850. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  4851. var vertex = new THREE.Vector3();
  4852. vertex.x = srcVertices[ v ] * scale;
  4853. vertex.y = srcVertices[ v + 1 ] * scale;
  4854. vertex.z = srcVertices[ v + 2 ] * scale;
  4855. dstVertices.push( vertex );
  4856. }
  4857. }
  4858. }
  4859. if ( json.morphColors !== undefined ) {
  4860. var i, l, c, cl, dstColors, srcColors, color;
  4861. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  4862. geometry.morphColors[ i ] = {};
  4863. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  4864. geometry.morphColors[ i ].colors = [];
  4865. dstColors = geometry.morphColors[ i ].colors;
  4866. srcColors = json.morphColors [ i ].colors;
  4867. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  4868. color = new THREE.Color( 0xffaa00 );
  4869. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  4870. dstColors.push( color );
  4871. }
  4872. }
  4873. }
  4874. };
  4875. callback( geometry );
  4876. };
  4877. /**
  4878. * @author mrdoob / http://mrdoob.com/
  4879. * @author alteredq / http://alteredqualia.com/
  4880. */
  4881. THREE.GeometryLoader = function () {
  4882. THREE.EventTarget.call( this );
  4883. this.crossOrigin = null;
  4884. this.path = null;
  4885. };
  4886. THREE.GeometryLoader.prototype = {
  4887. constructor: THREE.GeometryLoader,
  4888. load: function ( url ) {
  4889. var scope = this;
  4890. var geometry = null;
  4891. if ( scope.path === null ) {
  4892. var parts = url.split( '/' ); parts.pop();
  4893. scope.path = ( parts.length < 1 ? '.' : parts.join( '/' ) );
  4894. }
  4895. //
  4896. var xhr = new XMLHttpRequest();
  4897. xhr.addEventListener( 'load', function ( event ) {
  4898. if ( event.target.responseText ) {
  4899. geometry = scope.parse( JSON.parse( event.target.responseText ), monitor );
  4900. } else {
  4901. scope.dispatchEvent( { type: 'error', message: 'Invalid file [' + url + ']' } );
  4902. }
  4903. }, false );
  4904. xhr.addEventListener( 'error', function () {
  4905. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  4906. }, false );
  4907. xhr.open( 'GET', url, true );
  4908. xhr.setRequestHeader( "Content-Type", "application/json" );
  4909. xhr.send( null );
  4910. //
  4911. var monitor = new THREE.LoadingMonitor();
  4912. monitor.addEventListener( 'load', function ( event ) {
  4913. scope.dispatchEvent( { type: 'load', content: geometry } );
  4914. } );
  4915. monitor.add( xhr );
  4916. },
  4917. parse: function ( data, monitor ) {
  4918. var scope = this;
  4919. var geometry = new THREE.Geometry();
  4920. var scale = ( data.scale !== undefined ) ? 1 / data.scale : 1;
  4921. // materials
  4922. if ( data.materials ) {
  4923. geometry.materials = [];
  4924. for ( var i = 0; i < data.materials.length; ++ i ) {
  4925. var m = data.materials[ i ];
  4926. function isPow2( n ) {
  4927. var l = Math.log( n ) / Math.LN2;
  4928. return Math.floor( l ) == l;
  4929. }
  4930. function nearestPow2( n ) {
  4931. var l = Math.log( n ) / Math.LN2;
  4932. return Math.pow( 2, Math.round( l ) );
  4933. }
  4934. function createTexture( where, name, sourceFile, repeat, offset, wrap ) {
  4935. where[ name ] = new THREE.Texture();
  4936. where[ name ].sourceFile = sourceFile;
  4937. if ( repeat ) {
  4938. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  4939. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  4940. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  4941. }
  4942. if ( offset ) {
  4943. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  4944. }
  4945. if ( wrap ) {
  4946. var wrapMap = {
  4947. "repeat": THREE.RepeatWrapping,
  4948. "mirror": THREE.MirroredRepeatWrapping
  4949. }
  4950. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  4951. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  4952. }
  4953. // load image
  4954. var texture = where[ name ];
  4955. var loader = new THREE.ImageLoader();
  4956. loader.addEventListener( 'load', function ( event ) {
  4957. var image = event.content;
  4958. if ( !isPow2( image.width ) || !isPow2( image.height ) ) {
  4959. var width = nearestPow2( image.width );
  4960. var height = nearestPow2( image.height );
  4961. texture.image = document.createElement( 'canvas' );
  4962. texture.image.width = width;
  4963. texture.image.height = height;
  4964. texture.image.getContext( '2d' ).drawImage( image, 0, 0, width, height );
  4965. } else {
  4966. texture.image = image;
  4967. }
  4968. texture.needsUpdate = true;
  4969. } );
  4970. loader.crossOrigin = scope.crossOrigin;
  4971. loader.load( scope.path + '/' + sourceFile );
  4972. if ( monitor ) monitor.add( loader );
  4973. }
  4974. function rgb2hex( rgb ) {
  4975. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  4976. }
  4977. // defaults
  4978. var mtype = "MeshLambertMaterial";
  4979. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  4980. // parameters from model file
  4981. if ( m.shading ) {
  4982. var shading = m.shading.toLowerCase();
  4983. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  4984. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  4985. }
  4986. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  4987. mpars.blending = THREE[ m.blending ];
  4988. }
  4989. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  4990. mpars.transparent = m.transparent;
  4991. }
  4992. if ( m.depthTest !== undefined ) {
  4993. mpars.depthTest = m.depthTest;
  4994. }
  4995. if ( m.depthWrite !== undefined ) {
  4996. mpars.depthWrite = m.depthWrite;
  4997. }
  4998. if ( m.vertexColors !== undefined ) {
  4999. if ( m.vertexColors == "face" ) {
  5000. mpars.vertexColors = THREE.FaceColors;
  5001. } else if ( m.vertexColors ) {
  5002. mpars.vertexColors = THREE.VertexColors;
  5003. }
  5004. }
  5005. // colors
  5006. if ( m.colorDiffuse ) {
  5007. mpars.color = rgb2hex( m.colorDiffuse );
  5008. } else if ( m.DbgColor ) {
  5009. mpars.color = m.DbgColor;
  5010. }
  5011. if ( m.colorSpecular ) {
  5012. mpars.specular = rgb2hex( m.colorSpecular );
  5013. }
  5014. if ( m.colorAmbient ) {
  5015. mpars.ambient = rgb2hex( m.colorAmbient );
  5016. }
  5017. // modifiers
  5018. if ( m.transparency ) {
  5019. mpars.opacity = m.transparency;
  5020. }
  5021. if ( m.specularCoef ) {
  5022. mpars.shininess = m.specularCoef;
  5023. }
  5024. if ( m.visible !== undefined ) {
  5025. mpars.visible = m.visible;
  5026. }
  5027. if ( m.flipSided !== undefined ) {
  5028. mpars.side = THREE.BackSide;
  5029. }
  5030. if ( m.doubleSided !== undefined ) {
  5031. mpars.side = THREE.DoubleSide;
  5032. }
  5033. if ( m.wireframe !== undefined ) {
  5034. mpars.wireframe = m.wireframe;
  5035. }
  5036. // textures
  5037. if ( m.mapDiffuse ) {
  5038. createTexture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap );
  5039. }
  5040. if ( m.mapLight ) {
  5041. createTexture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap );
  5042. }
  5043. if ( m.mapBump ) {
  5044. createTexture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap );
  5045. }
  5046. if ( m.mapNormal ) {
  5047. createTexture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap );
  5048. }
  5049. if ( m.mapSpecular ) {
  5050. createTexture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap );
  5051. }
  5052. // special case for normal mapped material
  5053. if ( m.mapNormal ) {
  5054. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5055. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5056. uniforms[ "tNormal" ].value = mpars.normalMap;
  5057. if ( m.mapNormalFactor ) {
  5058. uniforms[ "uNormalScale" ].value = m.mapNormalFactor;
  5059. }
  5060. if ( mpars.map ) {
  5061. uniforms[ "tDiffuse" ].value = mpars.map;
  5062. uniforms[ "enableDiffuse" ].value = true;
  5063. }
  5064. if ( mpars.specularMap ) {
  5065. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5066. uniforms[ "enableSpecular" ].value = true;
  5067. }
  5068. if ( mpars.lightMap ) {
  5069. uniforms[ "tAO" ].value = mpars.lightMap;
  5070. uniforms[ "enableAO" ].value = true;
  5071. }
  5072. // for the moment don't handle displacement texture
  5073. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5074. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5075. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5076. uniforms[ "uShininess" ].value = mpars.shininess;
  5077. if ( mpars.opacity !== undefined ) {
  5078. uniforms[ "uOpacity" ].value = mpars.opacity;
  5079. }
  5080. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5081. var material = new THREE.ShaderMaterial( parameters );
  5082. } else {
  5083. var material = new THREE[ mtype ]( mpars );
  5084. }
  5085. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5086. geometry.materials[ i ] = material;
  5087. }
  5088. }
  5089. // geometry
  5090. function isBitSet( value, position ) {
  5091. return value & ( 1 << position );
  5092. }
  5093. var faces = data.faces;
  5094. var vertices = data.vertices;
  5095. var normals = data.normals;
  5096. var colors = data.colors;
  5097. var nUvLayers = 0;
  5098. // disregard empty arrays
  5099. if ( data.uvs ) {
  5100. for ( var i = 0; i < data.uvs.length; i ++ ) {
  5101. if ( data.uvs[ i ].length ) nUvLayers ++;
  5102. }
  5103. }
  5104. for ( var i = 0; i < nUvLayers; i ++ ) {
  5105. geometry.faceUvs[ i ] = [];
  5106. geometry.faceVertexUvs[ i ] = [];
  5107. }
  5108. var offset = 0;
  5109. var zLength = vertices.length;
  5110. while ( offset < zLength ) {
  5111. var vertex = new THREE.Vector3();
  5112. vertex.x = vertices[ offset ++ ] * scale;
  5113. vertex.y = vertices[ offset ++ ] * scale;
  5114. vertex.z = vertices[ offset ++ ] * scale;
  5115. geometry.vertices.push( vertex );
  5116. }
  5117. offset = 0;
  5118. zLength = faces.length;
  5119. while ( offset < zLength ) {
  5120. var type = faces[ offset ++ ];
  5121. var isQuad = isBitSet( type, 0 );
  5122. var hasMaterial = isBitSet( type, 1 );
  5123. var hasFaceUv = isBitSet( type, 2 );
  5124. var hasFaceVertexUv = isBitSet( type, 3 );
  5125. var hasFaceNormal = isBitSet( type, 4 );
  5126. var hasFaceVertexNormal = isBitSet( type, 5 );
  5127. var hasFaceColor = isBitSet( type, 6 );
  5128. var hasFaceVertexColor = isBitSet( type, 7 );
  5129. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5130. if ( isQuad ) {
  5131. var face = new THREE.Face4();
  5132. face.a = faces[ offset ++ ];
  5133. face.b = faces[ offset ++ ];
  5134. face.c = faces[ offset ++ ];
  5135. face.d = faces[ offset ++ ];
  5136. var nVertices = 4;
  5137. } else {
  5138. var face = new THREE.Face3();
  5139. face.a = faces[ offset ++ ];
  5140. face.b = faces[ offset ++ ];
  5141. face.c = faces[ offset ++ ];
  5142. var nVertices = 3;
  5143. }
  5144. if ( hasMaterial ) {
  5145. var materialIndex = faces[ offset ++ ];
  5146. face.materialIndex = materialIndex;
  5147. }
  5148. // to get face <=> uv index correspondence
  5149. var fi = geometry.faces.length;
  5150. if ( hasFaceUv ) {
  5151. for ( var i = 0; i < nUvLayers; i ++ ) {
  5152. var uvLayer = data.uvs[ i ];
  5153. var uvIndex = faces[ offset ++ ];
  5154. var u = uvLayer[ uvIndex * 2 ];
  5155. var v = uvLayer[ uvIndex * 2 + 1 ];
  5156. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  5157. }
  5158. }
  5159. if ( hasFaceVertexUv ) {
  5160. for ( var i = 0; i < nUvLayers; i ++ ) {
  5161. var uvLayer = data.uvs[ i ];
  5162. var uvs = [];
  5163. for ( var j = 0; j < nVertices; j ++ ) {
  5164. var uvIndex = faces[ offset ++ ];
  5165. var u = uvLayer[ uvIndex * 2 ];
  5166. var v = uvLayer[ uvIndex * 2 + 1 ];
  5167. uvs[ j ] = new THREE.UV( u, v );
  5168. }
  5169. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5170. }
  5171. }
  5172. if ( hasFaceNormal ) {
  5173. var normalIndex = faces[ offset ++ ] * 3;
  5174. var normal = new THREE.Vector3();
  5175. normal.x = normals[ normalIndex ++ ];
  5176. normal.y = normals[ normalIndex ++ ];
  5177. normal.z = normals[ normalIndex ];
  5178. face.normal = normal;
  5179. }
  5180. if ( hasFaceVertexNormal ) {
  5181. for ( i = 0; i < nVertices; i ++ ) {
  5182. var normalIndex = faces[ offset ++ ] * 3;
  5183. var normal = new THREE.Vector3();
  5184. normal.x = normals[ normalIndex ++ ];
  5185. normal.y = normals[ normalIndex ++ ];
  5186. normal.z = normals[ normalIndex ];
  5187. face.vertexNormals.push( normal );
  5188. }
  5189. }
  5190. if ( hasFaceColor ) {
  5191. var colorIndex = faces[ offset ++ ];
  5192. face.color = new THREE.Color( colors[ colorIndex ] );
  5193. }
  5194. if ( hasFaceVertexColor ) {
  5195. for ( var i = 0; i < nVertices; i ++ ) {
  5196. var colorIndex = faces[ offset ++ ];
  5197. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  5198. }
  5199. }
  5200. geometry.faces.push( face );
  5201. }
  5202. // skin
  5203. if ( data.skinWeights ) {
  5204. for ( var i = 0, l = data.skinWeights.length; i < l; i += 2 ) {
  5205. var x = data.skinWeights[ i ];
  5206. var y = data.skinWeights[ i + 1 ];
  5207. var z = 0;
  5208. var w = 0;
  5209. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5210. }
  5211. }
  5212. if ( data.skinIndices ) {
  5213. for ( var i = 0, l = data.skinIndices.length; i < l; i += 2 ) {
  5214. var a = data.skinIndices[ i ];
  5215. var b = data.skinIndices[ i + 1 ];
  5216. var c = 0;
  5217. var d = 0;
  5218. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5219. }
  5220. }
  5221. geometry.bones = data.bones;
  5222. geometry.animation = data.animation;
  5223. // morphing
  5224. if ( data.morphTargets ) {
  5225. for ( var i = 0, l = data.morphTargets.length; i < l; i ++ ) {
  5226. geometry.morphTargets[ i ] = {};
  5227. geometry.morphTargets[ i ].name = data.morphTargets[ i ].name;
  5228. geometry.morphTargets[ i ].vertices = [];
  5229. var dstVertices = geometry.morphTargets[ i ].vertices;
  5230. var srcVertices = data.morphTargets [ i ].vertices;
  5231. for( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5232. var vertex = new THREE.Vector3();
  5233. vertex.x = srcVertices[ v ] * scale;
  5234. vertex.y = srcVertices[ v + 1 ] * scale;
  5235. vertex.z = srcVertices[ v + 2 ] * scale;
  5236. dstVertices.push( vertex );
  5237. }
  5238. }
  5239. }
  5240. if ( data.morphColors ) {
  5241. for ( var i = 0, l = data.morphColors.length; i < l; i++ ) {
  5242. geometry.morphColors[ i ] = {};
  5243. geometry.morphColors[ i ].name = data.morphColors[ i ].name;
  5244. geometry.morphColors[ i ].colors = [];
  5245. var dstColors = geometry.morphColors[ i ].colors;
  5246. var srcColors = data.morphColors [ i ].colors;
  5247. for ( var c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5248. var color = new THREE.Color( 0xffaa00 );
  5249. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5250. dstColors.push( color );
  5251. }
  5252. }
  5253. }
  5254. geometry.computeCentroids();
  5255. geometry.computeFaceNormals();
  5256. return geometry;
  5257. }
  5258. };
  5259. /**
  5260. * @author alteredq / http://alteredqualia.com/
  5261. */
  5262. THREE.SceneLoader = function () {
  5263. this.onLoadStart = function () {};
  5264. this.onLoadProgress = function() {};
  5265. this.onLoadComplete = function () {};
  5266. this.callbackSync = function () {};
  5267. this.callbackProgress = function () {};
  5268. };
  5269. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5270. THREE.SceneLoader.prototype.load = function( url, callbackFinished ) {
  5271. var context = this;
  5272. var xhr = new XMLHttpRequest();
  5273. xhr.onreadystatechange = function () {
  5274. if ( xhr.readyState === 4 ) {
  5275. if ( xhr.status === 200 || xhr.status === 0 ) {
  5276. var json = JSON.parse( xhr.responseText );
  5277. context.createScene( json, callbackFinished, url );
  5278. } else {
  5279. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5280. }
  5281. }
  5282. };
  5283. xhr.open( "GET", url, true );
  5284. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "application/json; charset=x-user-defined" );
  5285. xhr.setRequestHeader( "Content-Type", "application/json" );
  5286. xhr.send( null );
  5287. };
  5288. THREE.SceneLoader.prototype.createScene = function ( json, callbackFinished, url ) {
  5289. var scope = this;
  5290. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  5291. var dg, dm, dd, dl, dc, df, dt,
  5292. g, o, m, l, d, p, r, q, s, c, t, f, tt, pp, u,
  5293. geometry, material, camera, fog,
  5294. texture, images,
  5295. light,
  5296. data, binLoader, jsonLoader,
  5297. counter_models, counter_textures,
  5298. total_models, total_textures,
  5299. result;
  5300. data = json;
  5301. binLoader = new THREE.BinaryLoader();
  5302. jsonLoader = new THREE.JSONLoader();
  5303. counter_models = 0;
  5304. counter_textures = 0;
  5305. result = {
  5306. scene: new THREE.Scene(),
  5307. geometries: {},
  5308. materials: {},
  5309. textures: {},
  5310. objects: {},
  5311. cameras: {},
  5312. lights: {},
  5313. fogs: {},
  5314. empties: {}
  5315. };
  5316. if ( data.transform ) {
  5317. var position = data.transform.position,
  5318. rotation = data.transform.rotation,
  5319. scale = data.transform.scale;
  5320. if ( position )
  5321. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  5322. if ( rotation )
  5323. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  5324. if ( scale )
  5325. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  5326. if ( position || rotation || scale ) {
  5327. result.scene.updateMatrix();
  5328. result.scene.updateMatrixWorld();
  5329. }
  5330. }
  5331. function get_url( source_url, url_type ) {
  5332. if ( url_type == "relativeToHTML" ) {
  5333. return source_url;
  5334. } else {
  5335. return urlBase + "/" + source_url;
  5336. }
  5337. };
  5338. // the toplevel loader function, delegates to handle_children
  5339. function handle_objects() {
  5340. handle_children( result.scene, data.objects );
  5341. }
  5342. // handle all the children from the loaded json and attach them to given parent
  5343. function handle_children( parent, children ) {
  5344. var object;
  5345. for ( dd in children ) {
  5346. // check by id if child has already been handled,
  5347. // if not, create new object
  5348. if ( result.objects[ dd ] === undefined ) {
  5349. o = children[ dd ];
  5350. if ( o.geometry !== undefined ) {
  5351. geometry = result.geometries[ o.geometry ];
  5352. // geometry already loaded
  5353. if ( geometry ) {
  5354. var hasNormals = false;
  5355. // not anymore support for multiple materials
  5356. // shouldn't really be array
  5357. material = result.materials[ o.materials[ 0 ] ];
  5358. hasNormals = material instanceof THREE.ShaderMaterial;
  5359. if ( hasNormals ) {
  5360. geometry.computeTangents();
  5361. }
  5362. p = o.position;
  5363. r = o.rotation;
  5364. q = o.quaternion;
  5365. s = o.scale;
  5366. m = o.matrix;
  5367. // turn off quaternions, for the moment
  5368. q = 0;
  5369. if ( o.materials.length == 0 ) {
  5370. material = new THREE.MeshFaceMaterial();
  5371. }
  5372. // dirty hack to handle meshes with multiple materials
  5373. // just use face materials defined in model
  5374. if ( o.materials.length > 1 ) {
  5375. material = new THREE.MeshFaceMaterial();
  5376. }
  5377. object = new THREE.Mesh( geometry, material );
  5378. object.name = dd;
  5379. if ( m ) {
  5380. object.matrixAutoUpdate = false;
  5381. object.matrix.set(
  5382. m[0], m[1], m[2], m[3],
  5383. m[4], m[5], m[6], m[7],
  5384. m[8], m[9], m[10], m[11],
  5385. m[12], m[13], m[14], m[15]
  5386. );
  5387. } else {
  5388. object.position.set( p[0], p[1], p[2] );
  5389. if ( q ) {
  5390. object.quaternion.set( q[0], q[1], q[2], q[3] );
  5391. object.useQuaternion = true;
  5392. } else {
  5393. object.rotation.set( r[0], r[1], r[2] );
  5394. }
  5395. object.scale.set( s[0], s[1], s[2] );
  5396. }
  5397. object.visible = o.visible;
  5398. object.castShadow = o.castShadow;
  5399. object.receiveShadow = o.receiveShadow;
  5400. parent.add( object );
  5401. result.objects[ dd ] = object;
  5402. }
  5403. // pure Object3D
  5404. } else {
  5405. p = o.position;
  5406. r = o.rotation;
  5407. q = o.quaternion;
  5408. s = o.scale;
  5409. // turn off quaternions, for the moment
  5410. q = 0;
  5411. object = new THREE.Object3D();
  5412. object.name = dd;
  5413. object.position.set( p[0], p[1], p[2] );
  5414. if ( q ) {
  5415. object.quaternion.set( q[0], q[1], q[2], q[3] );
  5416. object.useQuaternion = true;
  5417. } else {
  5418. object.rotation.set( r[0], r[1], r[2] );
  5419. }
  5420. object.scale.set( s[0], s[1], s[2] );
  5421. object.visible = ( o.visible !== undefined ) ? o.visible : false;
  5422. parent.add( object );
  5423. result.objects[ dd ] = object;
  5424. result.empties[ dd ] = object;
  5425. }
  5426. if ( o.properties !== undefined) {
  5427. for ( var key in o.properties ) {
  5428. var value = o.properties[ key ];
  5429. object.properties[ key ] = value;
  5430. }
  5431. }
  5432. if ( o.children !== undefined ) {
  5433. handle_children( object, o.children );
  5434. }
  5435. }
  5436. }
  5437. };
  5438. function handle_mesh( geo, id ) {
  5439. result.geometries[ id ] = geo;
  5440. handle_objects();
  5441. };
  5442. function create_callback( id ) {
  5443. return function( geo ) {
  5444. handle_mesh( geo, id );
  5445. counter_models -= 1;
  5446. scope.onLoadComplete();
  5447. async_callback_gate();
  5448. }
  5449. };
  5450. function create_callback_embed( id ) {
  5451. return function( geo ) {
  5452. result.geometries[ id ] = geo;
  5453. }
  5454. };
  5455. function async_callback_gate() {
  5456. var progress = {
  5457. totalModels : total_models,
  5458. totalTextures : total_textures,
  5459. loadedModels : total_models - counter_models,
  5460. loadedTextures : total_textures - counter_textures
  5461. };
  5462. scope.callbackProgress( progress, result );
  5463. scope.onLoadProgress();
  5464. if ( counter_models === 0 && counter_textures === 0 ) {
  5465. callbackFinished( result );
  5466. }
  5467. };
  5468. var callbackTexture = function ( count ) {
  5469. counter_textures -= count;
  5470. async_callback_gate();
  5471. scope.onLoadComplete();
  5472. };
  5473. // must use this instead of just directly calling callbackTexture
  5474. // because of closure in the calling context loop
  5475. var generateTextureCallback = function ( count ) {
  5476. return function() {
  5477. callbackTexture( count );
  5478. };
  5479. };
  5480. // first go synchronous elements
  5481. // cameras
  5482. for( dc in data.cameras ) {
  5483. c = data.cameras[ dc ];
  5484. if ( c.type === "perspective" ) {
  5485. camera = new THREE.PerspectiveCamera( c.fov, c.aspect, c.near, c.far );
  5486. } else if ( c.type === "ortho" ) {
  5487. camera = new THREE.OrthographicCamera( c.left, c.right, c.top, c.bottom, c.near, c.far );
  5488. }
  5489. p = c.position;
  5490. t = c.target;
  5491. u = c.up;
  5492. camera.position.set( p[0], p[1], p[2] );
  5493. camera.target = new THREE.Vector3( t[0], t[1], t[2] );
  5494. if ( u ) camera.up.set( u[0], u[1], u[2] );
  5495. result.cameras[ dc ] = camera;
  5496. }
  5497. // lights
  5498. var hex, intensity;
  5499. for ( dl in data.lights ) {
  5500. l = data.lights[ dl ];
  5501. hex = ( l.color !== undefined ) ? l.color : 0xffffff;
  5502. intensity = ( l.intensity !== undefined ) ? l.intensity : 1;
  5503. if ( l.type === "directional" ) {
  5504. p = l.direction;
  5505. light = new THREE.DirectionalLight( hex, intensity );
  5506. light.position.set( p[0], p[1], p[2] );
  5507. light.position.normalize();
  5508. } else if ( l.type === "point" ) {
  5509. p = l.position;
  5510. d = l.distance;
  5511. light = new THREE.PointLight( hex, intensity, d );
  5512. light.position.set( p[0], p[1], p[2] );
  5513. } else if ( l.type === "ambient" ) {
  5514. light = new THREE.AmbientLight( hex );
  5515. }
  5516. result.scene.add( light );
  5517. result.lights[ dl ] = light;
  5518. }
  5519. // fogs
  5520. for( df in data.fogs ) {
  5521. f = data.fogs[ df ];
  5522. if ( f.type === "linear" ) {
  5523. fog = new THREE.Fog( 0x000000, f.near, f.far );
  5524. } else if ( f.type === "exp2" ) {
  5525. fog = new THREE.FogExp2( 0x000000, f.density );
  5526. }
  5527. c = f.color;
  5528. fog.color.setRGB( c[0], c[1], c[2] );
  5529. result.fogs[ df ] = fog;
  5530. }
  5531. // defaults
  5532. if ( result.cameras && data.defaults.camera ) {
  5533. result.currentCamera = result.cameras[ data.defaults.camera ];
  5534. }
  5535. if ( result.fogs && data.defaults.fog ) {
  5536. result.scene.fog = result.fogs[ data.defaults.fog ];
  5537. }
  5538. c = data.defaults.bgcolor;
  5539. result.bgColor = new THREE.Color();
  5540. result.bgColor.setRGB( c[0], c[1], c[2] );
  5541. result.bgColorAlpha = data.defaults.bgalpha;
  5542. // now come potentially asynchronous elements
  5543. // geometries
  5544. // count how many models will be loaded asynchronously
  5545. for( dg in data.geometries ) {
  5546. g = data.geometries[ dg ];
  5547. if ( g.type == "bin_mesh" || g.type == "ascii_mesh" ) {
  5548. counter_models += 1;
  5549. scope.onLoadStart();
  5550. }
  5551. }
  5552. total_models = counter_models;
  5553. for ( dg in data.geometries ) {
  5554. g = data.geometries[ dg ];
  5555. if ( g.type === "cube" ) {
  5556. geometry = new THREE.CubeGeometry( g.width, g.height, g.depth, g.segmentsWidth, g.segmentsHeight, g.segmentsDepth, null, g.flipped, g.sides );
  5557. result.geometries[ dg ] = geometry;
  5558. } else if ( g.type === "plane" ) {
  5559. geometry = new THREE.PlaneGeometry( g.width, g.height, g.segmentsWidth, g.segmentsHeight );
  5560. result.geometries[ dg ] = geometry;
  5561. } else if ( g.type === "sphere" ) {
  5562. geometry = new THREE.SphereGeometry( g.radius, g.segmentsWidth, g.segmentsHeight );
  5563. result.geometries[ dg ] = geometry;
  5564. } else if ( g.type === "cylinder" ) {
  5565. geometry = new THREE.CylinderGeometry( g.topRad, g.botRad, g.height, g.radSegs, g.heightSegs );
  5566. result.geometries[ dg ] = geometry;
  5567. } else if ( g.type === "torus" ) {
  5568. geometry = new THREE.TorusGeometry( g.radius, g.tube, g.segmentsR, g.segmentsT );
  5569. result.geometries[ dg ] = geometry;
  5570. } else if ( g.type === "icosahedron" ) {
  5571. geometry = new THREE.IcosahedronGeometry( g.radius, g.subdivisions );
  5572. result.geometries[ dg ] = geometry;
  5573. } else if ( g.type === "bin_mesh" ) {
  5574. binLoader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ) );
  5575. } else if ( g.type === "ascii_mesh" ) {
  5576. jsonLoader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ) );
  5577. } else if ( g.type === "embedded_mesh" ) {
  5578. var modelJson = data.embeds[ g.id ],
  5579. texture_path = "";
  5580. // pass metadata along to jsonLoader so it knows the format version
  5581. modelJson.metadata = data.metadata;
  5582. if ( modelJson ) {
  5583. jsonLoader.createModel( modelJson, create_callback_embed( dg ), texture_path );
  5584. }
  5585. }
  5586. }
  5587. // textures
  5588. // count how many textures will be loaded asynchronously
  5589. for( dt in data.textures ) {
  5590. tt = data.textures[ dt ];
  5591. if( tt.url instanceof Array ) {
  5592. counter_textures += tt.url.length;
  5593. for( var n = 0; n < tt.url.length; n ++ ) {
  5594. scope.onLoadStart();
  5595. }
  5596. } else {
  5597. counter_textures += 1;
  5598. scope.onLoadStart();
  5599. }
  5600. }
  5601. total_textures = counter_textures;
  5602. for( dt in data.textures ) {
  5603. tt = data.textures[ dt ];
  5604. if ( tt.mapping !== undefined && THREE[ tt.mapping ] !== undefined ) {
  5605. tt.mapping = new THREE[ tt.mapping ]();
  5606. }
  5607. if( tt.url instanceof Array ) {
  5608. var count = tt.url.length;
  5609. var url_array = [];
  5610. for( var i = 0; i < count; i ++ ) {
  5611. url_array[ i ] = get_url( tt.url[ i ], data.urlBaseType );
  5612. }
  5613. texture = THREE.ImageUtils.loadTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
  5614. } else {
  5615. texture = THREE.ImageUtils.loadTexture( get_url( tt.url, data.urlBaseType ), tt.mapping, generateTextureCallback( 1 ) );
  5616. if ( THREE[ tt.minFilter ] !== undefined )
  5617. texture.minFilter = THREE[ tt.minFilter ];
  5618. if ( THREE[ tt.magFilter ] !== undefined )
  5619. texture.magFilter = THREE[ tt.magFilter ];
  5620. if ( tt.repeat ) {
  5621. texture.repeat.set( tt.repeat[ 0 ], tt.repeat[ 1 ] );
  5622. if ( tt.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  5623. if ( tt.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  5624. }
  5625. if ( tt.offset ) {
  5626. texture.offset.set( tt.offset[ 0 ], tt.offset[ 1 ] );
  5627. }
  5628. // handle wrap after repeat so that default repeat can be overriden
  5629. if ( tt.wrap ) {
  5630. var wrapMap = {
  5631. "repeat" : THREE.RepeatWrapping,
  5632. "mirror" : THREE.MirroredRepeatWrapping
  5633. }
  5634. if ( wrapMap[ tt.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ tt.wrap[ 0 ] ];
  5635. if ( wrapMap[ tt.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ tt.wrap[ 1 ] ];
  5636. }
  5637. }
  5638. result.textures[ dt ] = texture;
  5639. }
  5640. // materials
  5641. for ( dm in data.materials ) {
  5642. m = data.materials[ dm ];
  5643. for ( pp in m.parameters ) {
  5644. if ( pp === "envMap" || pp === "map" || pp === "lightMap" ) {
  5645. m.parameters[ pp ] = result.textures[ m.parameters[ pp ] ];
  5646. } else if ( pp === "shading" ) {
  5647. m.parameters[ pp ] = ( m.parameters[ pp ] == "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  5648. } else if ( pp === "blending" ) {
  5649. m.parameters[ pp ] = m.parameters[ pp ] in THREE ? THREE[ m.parameters[ pp ] ] : THREE.NormalBlending;
  5650. } else if ( pp === "combine" ) {
  5651. m.parameters[ pp ] = ( m.parameters[ pp ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
  5652. } else if ( pp === "vertexColors" ) {
  5653. if ( m.parameters[ pp ] == "face" ) {
  5654. m.parameters[ pp ] = THREE.FaceColors;
  5655. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  5656. } else if ( m.parameters[ pp ] ) {
  5657. m.parameters[ pp ] = THREE.VertexColors;
  5658. }
  5659. }
  5660. }
  5661. if ( m.parameters.opacity !== undefined && m.parameters.opacity < 1.0 ) {
  5662. m.parameters.transparent = true;
  5663. }
  5664. if ( m.parameters.normalMap ) {
  5665. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5666. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5667. var diffuse = m.parameters.color;
  5668. var specular = m.parameters.specular;
  5669. var ambient = m.parameters.ambient;
  5670. var shininess = m.parameters.shininess;
  5671. uniforms[ "tNormal" ].value = result.textures[ m.parameters.normalMap ];
  5672. if ( m.parameters.normalMapFactor ) {
  5673. uniforms[ "uNormalScale" ].value = m.parameters.normalMapFactor;
  5674. }
  5675. if ( m.parameters.map ) {
  5676. uniforms[ "tDiffuse" ].value = m.parameters.map;
  5677. uniforms[ "enableDiffuse" ].value = true;
  5678. }
  5679. if ( m.parameters.lightMap ) {
  5680. uniforms[ "tAO" ].value = m.parameters.lightMap;
  5681. uniforms[ "enableAO" ].value = true;
  5682. }
  5683. if ( m.parameters.specularMap ) {
  5684. uniforms[ "tSpecular" ].value = result.textures[ m.parameters.specularMap ];
  5685. uniforms[ "enableSpecular" ].value = true;
  5686. }
  5687. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  5688. uniforms[ "uSpecularColor" ].value.setHex( specular );
  5689. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  5690. uniforms[ "uShininess" ].value = shininess;
  5691. if ( m.parameters.opacity ) {
  5692. uniforms[ "uOpacity" ].value = m.parameters.opacity;
  5693. }
  5694. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5695. material = new THREE.ShaderMaterial( parameters );
  5696. } else {
  5697. material = new THREE[ m.type ]( m.parameters );
  5698. }
  5699. result.materials[ dm ] = material;
  5700. }
  5701. // objects ( synchronous init of procedural primitives )
  5702. handle_objects();
  5703. // synchronous callback
  5704. scope.callbackSync( result );
  5705. // just in case there are no async elements
  5706. async_callback_gate();
  5707. };
  5708. /**
  5709. * @author mrdoob / http://mrdoob.com/
  5710. */
  5711. THREE.TextureLoader = function () {
  5712. THREE.EventTarget.call( this );
  5713. this.crossOrigin = null;
  5714. };
  5715. THREE.TextureLoader.prototype = {
  5716. constructor: THREE.TextureLoader,
  5717. load: function ( url ) {
  5718. var scope = this;
  5719. var image = new Image();
  5720. image.addEventListener( 'load', function () {
  5721. var texture = new THREE.Texture( image );
  5722. texture.needsUpdate = true;
  5723. scope.dispatchEvent( { type: 'load', content: texture } );
  5724. }, false );
  5725. image.addEventListener( 'error', function () {
  5726. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5727. }, false );
  5728. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5729. image.src = url;
  5730. }
  5731. }
  5732. /**
  5733. * @author mrdoob / http://mrdoob.com/
  5734. * @author alteredq / http://alteredqualia.com/
  5735. */
  5736. THREE.Material = function () {
  5737. this.id = THREE.MaterialCount ++;
  5738. this.name = '';
  5739. this.side = THREE.FrontSide;
  5740. this.opacity = 1;
  5741. this.transparent = false;
  5742. this.blending = THREE.NormalBlending;
  5743. this.blendSrc = THREE.SrcAlphaFactor;
  5744. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  5745. this.blendEquation = THREE.AddEquation;
  5746. this.depthTest = true;
  5747. this.depthWrite = true;
  5748. this.polygonOffset = false;
  5749. this.polygonOffsetFactor = 0;
  5750. this.polygonOffsetUnits = 0;
  5751. this.alphaTest = 0;
  5752. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  5753. this.visible = true;
  5754. this.needsUpdate = true;
  5755. };
  5756. THREE.Material.prototype.setValues = function ( values ) {
  5757. if ( values === undefined ) return;
  5758. for ( var key in values ) {
  5759. var newValue = values[ key ];
  5760. if ( newValue === undefined ) {
  5761. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5762. continue;
  5763. }
  5764. if ( key in this ) {
  5765. var currentValue = this[ key ];
  5766. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  5767. currentValue.copy( newValue );
  5768. } else if ( currentValue instanceof THREE.Color && typeof( newValue ) === "number" ) {
  5769. currentValue.setHex( newValue );
  5770. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  5771. currentValue.copy( newValue );
  5772. } else {
  5773. this[ key ] = newValue;
  5774. }
  5775. }
  5776. }
  5777. };
  5778. THREE.Material.prototype.clone = function ( material ) {
  5779. if ( material === undefined ) material = new THREE.Material();
  5780. material.name = this.name;
  5781. material.side = this.side;
  5782. material.opacity = this.opacity;
  5783. material.transparent = this.transparent;
  5784. material.blending = this.blending;
  5785. material.blendSrc = this.blendSrc;
  5786. material.blendDst = this.blendDst;
  5787. material.blendEquation = this.blendEquation;
  5788. material.depthTest = this.depthTest;
  5789. material.depthWrite = this.depthWrite;
  5790. material.polygonOffset = this.polygonOffset;
  5791. material.polygonOffsetFactor = this.polygonOffsetFactor;
  5792. material.polygonOffsetUnits = this.polygonOffsetUnits;
  5793. material.alphaTest = this.alphaTest;
  5794. material.overdraw = this.overdraw;
  5795. material.visible = this.visible;
  5796. return material;
  5797. };
  5798. THREE.MaterialCount = 0;
  5799. /**
  5800. * @author mrdoob / http://mrdoob.com/
  5801. * @author alteredq / http://alteredqualia.com/
  5802. *
  5803. * parameters = {
  5804. * color: <hex>,
  5805. * opacity: <float>,
  5806. *
  5807. * blending: THREE.NormalBlending,
  5808. * depthTest: <bool>,
  5809. *
  5810. * linewidth: <float>,
  5811. * linecap: "round",
  5812. * linejoin: "round",
  5813. *
  5814. * vertexColors: <bool>
  5815. *
  5816. * fog: <bool>
  5817. * }
  5818. */
  5819. THREE.LineBasicMaterial = function ( parameters ) {
  5820. THREE.Material.call( this );
  5821. this.color = new THREE.Color( 0xffffff );
  5822. this.linewidth = 1;
  5823. this.linecap = 'round';
  5824. this.linejoin = 'round';
  5825. this.vertexColors = false;
  5826. this.fog = true;
  5827. this.setValues( parameters );
  5828. };
  5829. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  5830. THREE.LineBasicMaterial.prototype.clone = function () {
  5831. var material = new THREE.LineBasicMaterial();
  5832. THREE.Material.prototype.clone.call( this, material );
  5833. material.color.copy( this.color );
  5834. material.linewidth = this.linewidth;
  5835. material.linecap = this.linecap;
  5836. material.linejoin = this.linejoin;
  5837. material.vertexColors = this.vertexColors;
  5838. material.fog = this.fog;
  5839. return material;
  5840. };
  5841. /**
  5842. * @author mrdoob / http://mrdoob.com/
  5843. * @author alteredq / http://alteredqualia.com/
  5844. *
  5845. * parameters = {
  5846. * color: <hex>,
  5847. * opacity: <float>,
  5848. * map: new THREE.Texture( <Image> ),
  5849. *
  5850. * lightMap: new THREE.Texture( <Image> ),
  5851. *
  5852. * specularMap: new THREE.Texture( <Image> ),
  5853. *
  5854. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  5855. * combine: THREE.Multiply,
  5856. * reflectivity: <float>,
  5857. * refractionRatio: <float>,
  5858. *
  5859. * shading: THREE.SmoothShading,
  5860. * blending: THREE.NormalBlending,
  5861. * depthTest: <bool>,
  5862. *
  5863. * wireframe: <boolean>,
  5864. * wireframeLinewidth: <float>,
  5865. *
  5866. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  5867. *
  5868. * skinning: <bool>,
  5869. * morphTargets: <bool>,
  5870. *
  5871. * fog: <bool>
  5872. * }
  5873. */
  5874. THREE.MeshBasicMaterial = function ( parameters ) {
  5875. THREE.Material.call( this );
  5876. this.color = new THREE.Color( 0xffffff ); // emissive
  5877. this.map = null;
  5878. this.lightMap = null;
  5879. this.specularMap = null;
  5880. this.envMap = null;
  5881. this.combine = THREE.MultiplyOperation;
  5882. this.reflectivity = 1;
  5883. this.refractionRatio = 0.98;
  5884. this.fog = true;
  5885. this.shading = THREE.SmoothShading;
  5886. this.wireframe = false;
  5887. this.wireframeLinewidth = 1;
  5888. this.wireframeLinecap = 'round';
  5889. this.wireframeLinejoin = 'round';
  5890. this.vertexColors = THREE.NoColors;
  5891. this.skinning = false;
  5892. this.morphTargets = false;
  5893. this.setValues( parameters );
  5894. };
  5895. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  5896. THREE.MeshBasicMaterial.prototype.clone = function () {
  5897. var material = new THREE.MeshBasicMaterial();
  5898. THREE.Material.prototype.clone.call( this, material );
  5899. material.color.copy( this.color );
  5900. material.map = this.map;
  5901. material.lightMap = this.lightMap;
  5902. material.specularMap = this.specularMap;
  5903. material.envMap = this.envMap;
  5904. material.combine = this.combine;
  5905. material.reflectivity = this.reflectivity;
  5906. material.refractionRatio = this.refractionRatio;
  5907. material.fog = this.fog;
  5908. material.shading = this.shading;
  5909. material.wireframe = this.wireframe;
  5910. material.wireframeLinewidth = this.wireframeLinewidth;
  5911. material.wireframeLinecap = this.wireframeLinecap;
  5912. material.wireframeLinejoin = this.wireframeLinejoin;
  5913. material.vertexColors = this.vertexColors;
  5914. material.skinning = this.skinning;
  5915. material.morphTargets = this.morphTargets;
  5916. return material;
  5917. };
  5918. /**
  5919. * @author mrdoob / http://mrdoob.com/
  5920. * @author alteredq / http://alteredqualia.com/
  5921. *
  5922. * parameters = {
  5923. * color: <hex>,
  5924. * ambient: <hex>,
  5925. * emissive: <hex>,
  5926. * opacity: <float>,
  5927. *
  5928. * map: new THREE.Texture( <Image> ),
  5929. *
  5930. * lightMap: new THREE.Texture( <Image> ),
  5931. *
  5932. * specularMap: new THREE.Texture( <Image> ),
  5933. *
  5934. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  5935. * combine: THREE.Multiply,
  5936. * reflectivity: <float>,
  5937. * refractionRatio: <float>,
  5938. *
  5939. * shading: THREE.SmoothShading,
  5940. * blending: THREE.NormalBlending,
  5941. * depthTest: <bool>,
  5942. *
  5943. * wireframe: <boolean>,
  5944. * wireframeLinewidth: <float>,
  5945. *
  5946. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  5947. *
  5948. * skinning: <bool>,
  5949. * morphTargets: <bool>,
  5950. * morphNormals: <bool>,
  5951. *
  5952. * fog: <bool>
  5953. * }
  5954. */
  5955. THREE.MeshLambertMaterial = function ( parameters ) {
  5956. THREE.Material.call( this );
  5957. this.color = new THREE.Color( 0xffffff ); // diffuse
  5958. this.ambient = new THREE.Color( 0xffffff );
  5959. this.emissive = new THREE.Color( 0x000000 );
  5960. this.wrapAround = false;
  5961. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  5962. this.map = null;
  5963. this.lightMap = null;
  5964. this.specularMap = null;
  5965. this.envMap = null;
  5966. this.combine = THREE.MultiplyOperation;
  5967. this.reflectivity = 1;
  5968. this.refractionRatio = 0.98;
  5969. this.fog = true;
  5970. this.shading = THREE.SmoothShading;
  5971. this.wireframe = false;
  5972. this.wireframeLinewidth = 1;
  5973. this.wireframeLinecap = 'round';
  5974. this.wireframeLinejoin = 'round';
  5975. this.vertexColors = THREE.NoColors;
  5976. this.skinning = false;
  5977. this.morphTargets = false;
  5978. this.morphNormals = false;
  5979. this.setValues( parameters );
  5980. };
  5981. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  5982. THREE.MeshLambertMaterial.prototype.clone = function () {
  5983. var material = new THREE.MeshLambertMaterial();
  5984. THREE.Material.prototype.clone.call( this, material );
  5985. material.color.copy( this.color );
  5986. material.ambient.copy( this.ambient );
  5987. material.emissive.copy( this.emissive );
  5988. material.wrapAround = this.wrapAround;
  5989. material.wrapRGB.copy( this.wrapRGB );
  5990. material.map = this.map;
  5991. material.lightMap = this.lightMap;
  5992. material.specularMap = this.specularMap;
  5993. material.envMap = this.envMap;
  5994. material.combine = this.combine;
  5995. material.reflectivity = this.reflectivity;
  5996. material.refractionRatio = this.refractionRatio;
  5997. material.fog = this.fog;
  5998. material.shading = this.shading;
  5999. material.wireframe = this.wireframe;
  6000. material.wireframeLinewidth = this.wireframeLinewidth;
  6001. material.wireframeLinecap = this.wireframeLinecap;
  6002. material.wireframeLinejoin = this.wireframeLinejoin;
  6003. material.vertexColors = this.vertexColors;
  6004. material.skinning = this.skinning;
  6005. material.morphTargets = this.morphTargets;
  6006. material.morphNormals = this.morphNormals;
  6007. return material;
  6008. };
  6009. /**
  6010. * @author mrdoob / http://mrdoob.com/
  6011. * @author alteredq / http://alteredqualia.com/
  6012. *
  6013. * parameters = {
  6014. * color: <hex>,
  6015. * ambient: <hex>,
  6016. * emissive: <hex>,
  6017. * specular: <hex>,
  6018. * shininess: <float>,
  6019. * opacity: <float>,
  6020. *
  6021. * map: new THREE.Texture( <Image> ),
  6022. *
  6023. * lightMap: new THREE.Texture( <Image> ),
  6024. *
  6025. * bumpMap: new THREE.Texture( <Image> ),
  6026. * bumpScale: <float>,
  6027. *
  6028. * specularMap: new THREE.Texture( <Image> ),
  6029. *
  6030. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6031. * combine: THREE.Multiply,
  6032. * reflectivity: <float>,
  6033. * refractionRatio: <float>,
  6034. *
  6035. * shading: THREE.SmoothShading,
  6036. * blending: THREE.NormalBlending,
  6037. * depthTest: <bool>,
  6038. *
  6039. * wireframe: <boolean>,
  6040. * wireframeLinewidth: <float>,
  6041. *
  6042. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6043. *
  6044. * skinning: <bool>,
  6045. * morphTargets: <bool>,
  6046. * morphNormals: <bool>,
  6047. *
  6048. * fog: <bool>
  6049. * }
  6050. */
  6051. THREE.MeshPhongMaterial = function ( parameters ) {
  6052. THREE.Material.call( this );
  6053. this.color = new THREE.Color( 0xffffff ); // diffuse
  6054. this.ambient = new THREE.Color( 0xffffff );
  6055. this.emissive = new THREE.Color( 0x000000 );
  6056. this.specular = new THREE.Color( 0x111111 );
  6057. this.shininess = 30;
  6058. this.metal = false;
  6059. this.perPixel = false;
  6060. this.wrapAround = false;
  6061. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6062. this.map = null;
  6063. this.lightMap = null;
  6064. this.bumpMap = null;
  6065. this.bumpScale = 1;
  6066. this.specularMap = null;
  6067. this.envMap = null;
  6068. this.combine = THREE.MultiplyOperation;
  6069. this.reflectivity = 1;
  6070. this.refractionRatio = 0.98;
  6071. this.fog = true;
  6072. this.shading = THREE.SmoothShading;
  6073. this.wireframe = false;
  6074. this.wireframeLinewidth = 1;
  6075. this.wireframeLinecap = 'round';
  6076. this.wireframeLinejoin = 'round';
  6077. this.vertexColors = THREE.NoColors;
  6078. this.skinning = false;
  6079. this.morphTargets = false;
  6080. this.morphNormals = false;
  6081. this.setValues( parameters );
  6082. };
  6083. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  6084. THREE.MeshPhongMaterial.prototype.clone = function () {
  6085. var material = new THREE.MeshPhongMaterial();
  6086. THREE.Material.prototype.clone.call( this, material );
  6087. material.color.copy( this.color );
  6088. material.ambient.copy( this.ambient );
  6089. material.emissive.copy( this.emissive );
  6090. material.specular.copy( this.specular );
  6091. material.shininess = this.shininess;
  6092. material.metal = this.metal;
  6093. material.perPixel = this.perPixel;
  6094. material.wrapAround = this.wrapAround;
  6095. material.wrapRGB.copy( this.wrapRGB );
  6096. material.map = this.map;
  6097. material.lightMap = this.lightMap;
  6098. material.bumpMap = this.bumpMap;
  6099. material.bumpScale= this.bumpScale;
  6100. material.specularMap = this.specularMap;
  6101. material.envMap = this.envMap;
  6102. material.combine = this.combine;
  6103. material.reflectivity = this.reflectivity;
  6104. material.refractionRatio = this.refractionRatio;
  6105. material.fog = this.fog;
  6106. material.shading = this.shading;
  6107. material.wireframe = this.wireframe;
  6108. material.wireframeLinewidth = this.wireframeLinewidth;
  6109. material.wireframeLinecap = this.wireframeLinecap;
  6110. material.wireframeLinejoin = this.wireframeLinejoin;
  6111. material.vertexColors = this.vertexColors;
  6112. material.skinning = this.skinning;
  6113. material.morphTargets = this.morphTargets;
  6114. material.morphNormals = this.morphNormals;
  6115. return material;
  6116. };
  6117. /**
  6118. * @author mrdoob / http://mrdoob.com/
  6119. * @author alteredq / http://alteredqualia.com/
  6120. *
  6121. * parameters = {
  6122. * opacity: <float>,
  6123. * blending: THREE.NormalBlending,
  6124. * depthTest: <bool>,
  6125. * wireframe: <boolean>,
  6126. * wireframeLinewidth: <float>
  6127. * }
  6128. */
  6129. THREE.MeshDepthMaterial = function ( parameters ) {
  6130. THREE.Material.call( this );
  6131. this.wireframe = false;
  6132. this.wireframeLinewidth = 1;
  6133. this.setValues( parameters );
  6134. };
  6135. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  6136. THREE.MeshDepthMaterial.prototype.clone = function () {
  6137. var material = new THREE.LineBasicMaterial();
  6138. THREE.Material.prototype.clone.call( this, material );
  6139. material.wireframe = this.wireframe;
  6140. material.wireframeLinewidth = this.wireframeLinewidth;
  6141. return material;
  6142. };
  6143. /**
  6144. * @author mrdoob / http://mrdoob.com/
  6145. *
  6146. * parameters = {
  6147. * opacity: <float>,
  6148. * shading: THREE.FlatShading,
  6149. * blending: THREE.NormalBlending,
  6150. * depthTest: <bool>,
  6151. * wireframe: <boolean>,
  6152. * wireframeLinewidth: <float>
  6153. * }
  6154. */
  6155. THREE.MeshNormalMaterial = function ( parameters ) {
  6156. THREE.Material.call( this, parameters );
  6157. this.shading = THREE.FlatShading;
  6158. this.wireframe = false;
  6159. this.wireframeLinewidth = 1;
  6160. this.setValues( parameters );
  6161. };
  6162. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  6163. THREE.MeshNormalMaterial.prototype.clone = function () {
  6164. var material = new THREE.MeshNormalMaterial();
  6165. THREE.Material.prototype.clone.call( this, material );
  6166. material.shading = this.shading;
  6167. material.wireframe = this.wireframe;
  6168. material.wireframeLinewidth = this.wireframeLinewidth;
  6169. return material;
  6170. };
  6171. /**
  6172. * @author mrdoob / http://mrdoob.com/
  6173. */
  6174. THREE.MeshFaceMaterial = function () {};
  6175. THREE.MeshFaceMaterial.prototype.clone = function () {
  6176. return new THREE.MeshFaceMaterial();
  6177. };
  6178. /**
  6179. * @author mrdoob / http://mrdoob.com/
  6180. * @author alteredq / http://alteredqualia.com/
  6181. *
  6182. * parameters = {
  6183. * color: <hex>,
  6184. * opacity: <float>,
  6185. * map: new THREE.Texture( <Image> ),
  6186. *
  6187. * size: <float>,
  6188. *
  6189. * blending: THREE.NormalBlending,
  6190. * depthTest: <bool>,
  6191. *
  6192. * vertexColors: <bool>,
  6193. *
  6194. * fog: <bool>
  6195. * }
  6196. */
  6197. THREE.ParticleBasicMaterial = function ( parameters ) {
  6198. THREE.Material.call( this );
  6199. this.color = new THREE.Color( 0xffffff );
  6200. this.map = null;
  6201. this.size = 1;
  6202. this.sizeAttenuation = true;
  6203. this.vertexColors = false;
  6204. this.fog = true;
  6205. this.setValues( parameters );
  6206. };
  6207. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6208. THREE.ParticleBasicMaterial.prototype.clone = function () {
  6209. var material = new THREE.ParticleBasicMaterial();
  6210. THREE.Material.prototype.clone.call( this, material );
  6211. material.color.copy( this.color );
  6212. material.map = this.map;
  6213. material.size = this.size;
  6214. material.sizeAttenuation = this.sizeAttenuation;
  6215. material.vertexColors = this.vertexColors;
  6216. material.fog = this.fog;
  6217. return material;
  6218. };
  6219. /**
  6220. * @author mrdoob / http://mrdoob.com/
  6221. *
  6222. * parameters = {
  6223. * color: <hex>,
  6224. * program: <function>,
  6225. * opacity: <float>,
  6226. * blending: THREE.NormalBlending
  6227. * }
  6228. */
  6229. THREE.ParticleCanvasMaterial = function ( parameters ) {
  6230. THREE.Material.call( this );
  6231. this.color = new THREE.Color( 0xffffff );
  6232. this.program = function ( context, color ) {};
  6233. this.setValues( parameters );
  6234. };
  6235. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  6236. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  6237. var material = new THREE.ParticleCanvasMaterial();
  6238. THREE.Material.prototype.clone.call( this, material );
  6239. material.color.copy( this.color );
  6240. material.program = this.program;
  6241. return material;
  6242. };
  6243. /**
  6244. * @author mrdoob / http://mrdoob.com/
  6245. */
  6246. THREE.ParticleDOMMaterial = function ( domElement ) {
  6247. this.domElement = domElement;
  6248. };
  6249. THREE.ParticleDOMMaterial.prototype.clone = function(){
  6250. return new THREE.ParticleDOMMaterial( this.domElement );
  6251. };
  6252. /**
  6253. * @author alteredq / http://alteredqualia.com/
  6254. *
  6255. * parameters = {
  6256. * fragmentShader: <string>,
  6257. * vertexShader: <string>,
  6258. *
  6259. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  6260. *
  6261. * shading: THREE.SmoothShading,
  6262. * blending: THREE.NormalBlending,
  6263. * depthTest: <bool>,
  6264. *
  6265. * wireframe: <boolean>,
  6266. * wireframeLinewidth: <float>,
  6267. *
  6268. * lights: <bool>,
  6269. *
  6270. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6271. *
  6272. * skinning: <bool>,
  6273. * morphTargets: <bool>,
  6274. * morphNormals: <bool>,
  6275. *
  6276. * fog: <bool>
  6277. * }
  6278. */
  6279. THREE.ShaderMaterial = function ( parameters ) {
  6280. THREE.Material.call( this );
  6281. this.fragmentShader = "void main() {}";
  6282. this.vertexShader = "void main() {}";
  6283. this.uniforms = {};
  6284. this.attributes = null;
  6285. this.shading = THREE.SmoothShading;
  6286. this.wireframe = false;
  6287. this.wireframeLinewidth = 1;
  6288. this.fog = false; // set to use scene fog
  6289. this.lights = false; // set to use scene lights
  6290. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  6291. this.skinning = false; // set to use skinning attribute streams
  6292. this.morphTargets = false; // set to use morph targets
  6293. this.morphNormals = false; // set to use morph normals
  6294. this.setValues( parameters );
  6295. };
  6296. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  6297. THREE.ShaderMaterial.prototype.clone = function () {
  6298. var material = new THREE.ShaderMaterial();
  6299. THREE.Material.prototype.clone.call( this, material );
  6300. material.fragmentShader = this.fragmentShader;
  6301. material.vertexShader = this.vertexShader;
  6302. material.uniforms = this.uniforms;
  6303. material.attributes = this.attributes;
  6304. material.shading = this.shading;
  6305. material.wireframe = this.wireframe;
  6306. material.wireframeLinewidth = this.wireframeLinewidth;
  6307. material.fog = this.fog;
  6308. material.lights = this.lights;
  6309. material.vertexColors = this.vertexColors;
  6310. material.skinning = this.skinning;
  6311. material.morphTargets = this.morphTargets;
  6312. material.morphNormals = this.morphNormals;
  6313. return material;
  6314. };
  6315. /**
  6316. * @author mrdoob / http://mrdoob.com/
  6317. * @author alteredq / http://alteredqualia.com/
  6318. * @author szimek / https://github.com/szimek/
  6319. */
  6320. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  6321. this.id = THREE.TextureCount ++;
  6322. this.image = image;
  6323. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  6324. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  6325. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  6326. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  6327. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  6328. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  6329. this.format = format !== undefined ? format : THREE.RGBAFormat;
  6330. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  6331. this.offset = new THREE.Vector2( 0, 0 );
  6332. this.repeat = new THREE.Vector2( 1, 1 );
  6333. this.generateMipmaps = true;
  6334. this.premultiplyAlpha = false;
  6335. this.flipY = true;
  6336. this.needsUpdate = false;
  6337. this.onUpdate = null;
  6338. };
  6339. THREE.Texture.prototype = {
  6340. constructor: THREE.Texture,
  6341. clone: function () {
  6342. var clonedTexture = new THREE.Texture( this.image, this.mapping, this.wrapS, this.wrapT, this.magFilter, this.minFilter, this.format, this.type, this.anisotropy );
  6343. clonedTexture.offset.copy( this.offset );
  6344. clonedTexture.repeat.copy( this.repeat );
  6345. clonedTexture.generateMipmaps = this.generateMipmaps;
  6346. clonedTexture.premultiplyAlpha = this.premultiplyAlpha;
  6347. clonedTexture.flipY = this.flipY;
  6348. return clonedTexture;
  6349. }
  6350. };
  6351. THREE.TextureCount = 0;
  6352. /**
  6353. * @author alteredq / http://alteredqualia.com/
  6354. */
  6355. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {
  6356. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );
  6357. this.image = { data: data, width: width, height: height };
  6358. };
  6359. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  6360. THREE.DataTexture.prototype.clone = function () {
  6361. var clonedTexture = new THREE.DataTexture( this.image.data, this.image.width, this.image.height, this.format, this.type, this.mapping, this.wrapS, this.wrapT, this.magFilter, this.minFilter );
  6362. clonedTexture.offset.copy( this.offset );
  6363. clonedTexture.repeat.copy( this.repeat );
  6364. return clonedTexture;
  6365. };
  6366. /**
  6367. * @author mrdoob / http://mrdoob.com/
  6368. */
  6369. THREE.Particle = function ( material ) {
  6370. THREE.Object3D.call( this );
  6371. this.material = material;
  6372. };
  6373. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  6374. /**
  6375. * @author alteredq / http://alteredqualia.com/
  6376. */
  6377. THREE.ParticleSystem = function ( geometry, material ) {
  6378. THREE.Object3D.call( this );
  6379. this.geometry = geometry;
  6380. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  6381. this.sortParticles = false;
  6382. if ( this.geometry ) {
  6383. // calc bound radius
  6384. if( !this.geometry.boundingSphere ) {
  6385. this.geometry.computeBoundingSphere();
  6386. }
  6387. this.boundRadius = geometry.boundingSphere.radius;
  6388. }
  6389. this.frustumCulled = false;
  6390. };
  6391. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  6392. /**
  6393. * @author mrdoob / http://mrdoob.com/
  6394. */
  6395. THREE.Line = function ( geometry, material, type ) {
  6396. THREE.Object3D.call( this );
  6397. this.geometry = geometry;
  6398. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  6399. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  6400. if ( this.geometry ) {
  6401. if ( ! this.geometry.boundingSphere ) {
  6402. this.geometry.computeBoundingSphere();
  6403. }
  6404. }
  6405. };
  6406. THREE.LineStrip = 0;
  6407. THREE.LinePieces = 1;
  6408. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  6409. /**
  6410. * @author mrdoob / http://mrdoob.com/
  6411. * @author alteredq / http://alteredqualia.com/
  6412. * @author mikael emtinger / http://gomo.se/
  6413. */
  6414. THREE.Mesh = function ( geometry, material ) {
  6415. THREE.Object3D.call( this );
  6416. this.geometry = geometry;
  6417. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  6418. if ( this.geometry ) {
  6419. // calc bound radius
  6420. if ( ! this.geometry.boundingSphere ) {
  6421. this.geometry.computeBoundingSphere();
  6422. }
  6423. this.boundRadius = geometry.boundingSphere.radius;
  6424. // setup morph targets
  6425. if( this.geometry.morphTargets.length ) {
  6426. this.morphTargetBase = -1;
  6427. this.morphTargetForcedOrder = [];
  6428. this.morphTargetInfluences = [];
  6429. this.morphTargetDictionary = {};
  6430. for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
  6431. this.morphTargetInfluences.push( 0 );
  6432. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  6433. }
  6434. }
  6435. }
  6436. }
  6437. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  6438. /*
  6439. * Get Morph Target Index by Name
  6440. */
  6441. THREE.Mesh.prototype.getMorphTargetIndexByName = function( name ) {
  6442. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  6443. return this.morphTargetDictionary[ name ];
  6444. }
  6445. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  6446. return 0;
  6447. }
  6448. /**
  6449. * @author mikael emtinger / http://gomo.se/
  6450. * @author alteredq / http://alteredqualia.com/
  6451. */
  6452. THREE.Bone = function( belongsToSkin ) {
  6453. THREE.Object3D.call( this );
  6454. this.skin = belongsToSkin;
  6455. this.skinMatrix = new THREE.Matrix4();
  6456. };
  6457. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  6458. THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {
  6459. // update local
  6460. if ( this.matrixAutoUpdate ) {
  6461. forceUpdate |= this.updateMatrix();
  6462. }
  6463. // update skin matrix
  6464. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  6465. if( parentSkinMatrix ) {
  6466. this.skinMatrix.multiply( parentSkinMatrix, this.matrix );
  6467. } else {
  6468. this.skinMatrix.copy( this.matrix );
  6469. }
  6470. this.matrixWorldNeedsUpdate = false;
  6471. forceUpdate = true;
  6472. }
  6473. // update children
  6474. var child, i, l = this.children.length;
  6475. for ( i = 0; i < l; i ++ ) {
  6476. this.children[ i ].update( this.skinMatrix, forceUpdate );
  6477. }
  6478. };
  6479. /**
  6480. * @author mikael emtinger / http://gomo.se/
  6481. * @author alteredq / http://alteredqualia.com/
  6482. */
  6483. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  6484. THREE.Mesh.call( this, geometry, material );
  6485. //
  6486. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  6487. // init bones
  6488. this.identityMatrix = new THREE.Matrix4();
  6489. this.bones = [];
  6490. this.boneMatrices = [];
  6491. var b, bone, gbone, p, q, s;
  6492. if ( this.geometry.bones !== undefined ) {
  6493. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  6494. gbone = this.geometry.bones[ b ];
  6495. p = gbone.pos;
  6496. q = gbone.rotq;
  6497. s = gbone.scl;
  6498. bone = this.addBone();
  6499. bone.name = gbone.name;
  6500. bone.position.set( p[0], p[1], p[2] );
  6501. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  6502. bone.useQuaternion = true;
  6503. if ( s !== undefined ) {
  6504. bone.scale.set( s[0], s[1], s[2] );
  6505. } else {
  6506. bone.scale.set( 1, 1, 1 );
  6507. }
  6508. }
  6509. for ( b = 0; b < this.bones.length; b ++ ) {
  6510. gbone = this.geometry.bones[ b ];
  6511. bone = this.bones[ b ];
  6512. if ( gbone.parent === -1 ) {
  6513. this.add( bone );
  6514. } else {
  6515. this.bones[ gbone.parent ].add( bone );
  6516. }
  6517. }
  6518. //
  6519. var nBones = this.bones.length;
  6520. if ( this.useVertexTexture ) {
  6521. // layout (1 matrix = 4 pixels)
  6522. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  6523. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  6524. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  6525. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  6526. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  6527. var size;
  6528. if ( nBones > 256 )
  6529. size = 64;
  6530. else if ( nBones > 64 )
  6531. size = 32;
  6532. else if ( nBones > 16 )
  6533. size = 16;
  6534. else
  6535. size = 8;
  6536. this.boneTextureWidth = size;
  6537. this.boneTextureHeight = size;
  6538. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  6539. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  6540. this.boneTexture.minFilter = THREE.NearestFilter;
  6541. this.boneTexture.magFilter = THREE.NearestFilter;
  6542. this.boneTexture.generateMipmaps = false;
  6543. this.boneTexture.flipY = false;
  6544. } else {
  6545. this.boneMatrices = new Float32Array( 16 * nBones );
  6546. }
  6547. this.pose();
  6548. }
  6549. };
  6550. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  6551. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  6552. if ( bone === undefined ) {
  6553. bone = new THREE.Bone( this );
  6554. }
  6555. this.bones.push( bone );
  6556. return bone;
  6557. };
  6558. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  6559. this.matrixAutoUpdate && this.updateMatrix();
  6560. // update matrixWorld
  6561. if ( this.matrixWorldNeedsUpdate || force ) {
  6562. if ( this.parent ) {
  6563. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  6564. } else {
  6565. this.matrixWorld.copy( this.matrix );
  6566. }
  6567. this.matrixWorldNeedsUpdate = false;
  6568. force = true;
  6569. }
  6570. // update children
  6571. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6572. var child = this.children[ i ];
  6573. if ( child instanceof THREE.Bone ) {
  6574. child.update( this.identityMatrix, false );
  6575. } else {
  6576. child.updateMatrixWorld( true );
  6577. }
  6578. }
  6579. // make a snapshot of the bones' rest position
  6580. if ( this.boneInverses == undefined ) {
  6581. this.boneInverses = [];
  6582. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  6583. var inverse = new THREE.Matrix4();
  6584. inverse.getInverse( this.bones[ b ].skinMatrix );
  6585. this.boneInverses.push( inverse );
  6586. }
  6587. }
  6588. // flatten bone matrices to array
  6589. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  6590. // compute the offset between the current and the original transform;
  6591. //TODO: we could get rid of this multiplication step if the skinMatrix
  6592. // was already representing the offset; however, this requires some
  6593. // major changes to the animation system
  6594. THREE.SkinnedMesh.offsetMatrix.multiply( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  6595. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  6596. }
  6597. if ( this.useVertexTexture ) {
  6598. this.boneTexture.needsUpdate = true;
  6599. }
  6600. };
  6601. /*
  6602. * Pose
  6603. */
  6604. THREE.SkinnedMesh.prototype.pose = function() {
  6605. this.updateMatrixWorld( true );
  6606. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  6607. // normalize weights
  6608. var sw = this.geometry.skinWeights[ i ];
  6609. var scale = 1.0 / sw.lengthManhattan();
  6610. if ( scale !== Infinity ) {
  6611. sw.multiplyScalar( scale );
  6612. } else {
  6613. sw.set( 1 ); // this will be normalized by the shader anyway
  6614. }
  6615. }
  6616. };
  6617. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  6618. /**
  6619. * @author alteredq / http://alteredqualia.com/
  6620. */
  6621. THREE.MorphAnimMesh = function ( geometry, material ) {
  6622. THREE.Mesh.call( this, geometry, material );
  6623. // API
  6624. this.duration = 1000; // milliseconds
  6625. this.mirroredLoop = false;
  6626. this.time = 0;
  6627. // internals
  6628. this.lastKeyframe = 0;
  6629. this.currentKeyframe = 0;
  6630. this.direction = 1;
  6631. this.directionBackwards = false;
  6632. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  6633. };
  6634. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  6635. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  6636. this.startKeyframe = start;
  6637. this.endKeyframe = end;
  6638. this.length = this.endKeyframe - this.startKeyframe + 1;
  6639. };
  6640. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  6641. this.direction = 1;
  6642. this.directionBackwards = false;
  6643. };
  6644. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  6645. this.direction = -1;
  6646. this.directionBackwards = true;
  6647. };
  6648. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  6649. var geometry = this.geometry;
  6650. if ( ! geometry.animations ) geometry.animations = {};
  6651. var firstAnimation, animations = geometry.animations;
  6652. var pattern = /([a-z]+)(\d+)/;
  6653. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  6654. var morph = geometry.morphTargets[ i ];
  6655. var parts = morph.name.match( pattern );
  6656. if ( parts && parts.length > 1 ) {
  6657. var label = parts[ 1 ];
  6658. var num = parts[ 2 ];
  6659. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  6660. var animation = animations[ label ];
  6661. if ( i < animation.start ) animation.start = i;
  6662. if ( i > animation.end ) animation.end = i;
  6663. if ( ! firstAnimation ) firstAnimation = label;
  6664. }
  6665. }
  6666. geometry.firstAnimation = firstAnimation;
  6667. };
  6668. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  6669. if ( ! this.geometry.animations ) this.geometry.animations = {};
  6670. this.geometry.animations[ label ] = { start: start, end: end };
  6671. };
  6672. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  6673. var animation = this.geometry.animations[ label ];
  6674. if ( animation ) {
  6675. this.setFrameRange( animation.start, animation.end );
  6676. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  6677. this.time = 0;
  6678. } else {
  6679. console.warn( "animation[" + label + "] undefined" );
  6680. }
  6681. };
  6682. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  6683. var frameTime = this.duration / this.length;
  6684. this.time += this.direction * delta;
  6685. if ( this.mirroredLoop ) {
  6686. if ( this.time > this.duration || this.time < 0 ) {
  6687. this.direction *= -1;
  6688. if ( this.time > this.duration ) {
  6689. this.time = this.duration;
  6690. this.directionBackwards = true;
  6691. }
  6692. if ( this.time < 0 ) {
  6693. this.time = 0;
  6694. this.directionBackwards = false;
  6695. }
  6696. }
  6697. } else {
  6698. this.time = this.time % this.duration;
  6699. if ( this.time < 0 ) this.time += this.duration;
  6700. }
  6701. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  6702. if ( keyframe !== this.currentKeyframe ) {
  6703. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  6704. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  6705. this.morphTargetInfluences[ keyframe ] = 0;
  6706. this.lastKeyframe = this.currentKeyframe;
  6707. this.currentKeyframe = keyframe;
  6708. }
  6709. var mix = ( this.time % frameTime ) / frameTime;
  6710. if ( this.directionBackwards ) {
  6711. mix = 1 - mix;
  6712. }
  6713. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  6714. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  6715. };
  6716. /**
  6717. * @author alteredq / http://alteredqualia.com/
  6718. */
  6719. THREE.Ribbon = function ( geometry, material ) {
  6720. THREE.Object3D.call( this );
  6721. this.geometry = geometry;
  6722. this.material = material;
  6723. };
  6724. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  6725. /**
  6726. * @author mikael emtinger / http://gomo.se/
  6727. * @author alteredq / http://alteredqualia.com/
  6728. * @author mrdoob / http://mrdoob.com/
  6729. */
  6730. THREE.LOD = function () {
  6731. THREE.Object3D.call( this );
  6732. this.LODs = [];
  6733. };
  6734. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  6735. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  6736. if ( visibleAtDistance === undefined ) {
  6737. visibleAtDistance = 0;
  6738. }
  6739. visibleAtDistance = Math.abs( visibleAtDistance );
  6740. for ( var l = 0; l < this.LODs.length; l ++ ) {
  6741. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  6742. break;
  6743. }
  6744. }
  6745. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  6746. this.add( object3D );
  6747. };
  6748. THREE.LOD.prototype.update = function ( camera ) {
  6749. if ( this.LODs.length > 1 ) {
  6750. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  6751. var inverse = camera.matrixWorldInverse;
  6752. var distance = -( inverse.elements[2] * this.matrixWorld.elements[12] + inverse.elements[6] * this.matrixWorld.elements[13] + inverse.elements[10] * this.matrixWorld.elements[14] + inverse.elements[14] );
  6753. this.LODs[ 0 ].object3D.visible = true;
  6754. for ( var l = 1; l < this.LODs.length; l ++ ) {
  6755. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  6756. this.LODs[ l - 1 ].object3D.visible = false;
  6757. this.LODs[ l ].object3D.visible = true;
  6758. } else {
  6759. break;
  6760. }
  6761. }
  6762. for( ; l < this.LODs.length; l ++ ) {
  6763. this.LODs[ l ].object3D.visible = false;
  6764. }
  6765. }
  6766. };
  6767. /**
  6768. * @author mikael emtinger / http://gomo.se/
  6769. */
  6770. THREE.Sprite = function ( parameters ) {
  6771. THREE.Object3D.call( this );
  6772. this.color = ( parameters.color !== undefined ) ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  6773. this.map = ( parameters.map !== undefined ) ? parameters.map : new THREE.Texture();
  6774. this.blending = ( parameters.blending !== undefined ) ? parameters.blending : THREE.NormalBlending;
  6775. this.blendSrc = parameters.blendSrc !== undefined ? parameters.blendSrc : THREE.SrcAlphaFactor;
  6776. this.blendDst = parameters.blendDst !== undefined ? parameters.blendDst : THREE.OneMinusSrcAlphaFactor;
  6777. this.blendEquation = parameters.blendEquation !== undefined ? parameters.blendEquation : THREE.AddEquation;
  6778. this.useScreenCoordinates = ( parameters.useScreenCoordinates !== undefined ) ? parameters.useScreenCoordinates : true;
  6779. this.mergeWith3D = ( parameters.mergeWith3D !== undefined ) ? parameters.mergeWith3D : !this.useScreenCoordinates;
  6780. this.affectedByDistance = ( parameters.affectedByDistance !== undefined ) ? parameters.affectedByDistance : !this.useScreenCoordinates;
  6781. this.scaleByViewport = ( parameters.scaleByViewport !== undefined ) ? parameters.scaleByViewport : !this.affectedByDistance;
  6782. this.alignment = ( parameters.alignment instanceof THREE.Vector2 ) ? parameters.alignment : THREE.SpriteAlignment.center;
  6783. this.rotation3d = this.rotation;
  6784. this.rotation = 0;
  6785. this.opacity = 1;
  6786. this.uvOffset = new THREE.Vector2( 0, 0 );
  6787. this.uvScale = new THREE.Vector2( 1, 1 );
  6788. };
  6789. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  6790. /*
  6791. * Custom update matrix
  6792. */
  6793. THREE.Sprite.prototype.updateMatrix = function () {
  6794. this.matrix.setPosition( this.position );
  6795. this.rotation3d.set( 0, 0, this.rotation );
  6796. this.matrix.setRotationFromEuler( this.rotation3d );
  6797. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  6798. this.matrix.scale( this.scale );
  6799. this.boundRadiusScale = Math.max( this.scale.x, this.scale.y );
  6800. }
  6801. this.matrixWorldNeedsUpdate = true;
  6802. };
  6803. /*
  6804. * Alignment
  6805. */
  6806. THREE.SpriteAlignment = {};
  6807. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  6808. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  6809. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  6810. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  6811. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  6812. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  6813. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  6814. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  6815. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  6816. /**
  6817. * @author mrdoob / http://mrdoob.com/
  6818. */
  6819. THREE.Scene = function () {
  6820. THREE.Object3D.call( this );
  6821. this.fog = null;
  6822. this.overrideMaterial = null;
  6823. this.matrixAutoUpdate = false;
  6824. this.__objects = [];
  6825. this.__lights = [];
  6826. this.__objectsAdded = [];
  6827. this.__objectsRemoved = [];
  6828. };
  6829. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  6830. THREE.Scene.prototype.__addObject = function ( object ) {
  6831. if ( object instanceof THREE.Light ) {
  6832. if ( this.__lights.indexOf( object ) === - 1 ) {
  6833. this.__lights.push( object );
  6834. }
  6835. if ( object.target && object.target.parent === undefined ) {
  6836. this.add( object.target );
  6837. }
  6838. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  6839. if ( this.__objects.indexOf( object ) === - 1 ) {
  6840. this.__objects.push( object );
  6841. this.__objectsAdded.push( object );
  6842. // check if previously removed
  6843. var i = this.__objectsRemoved.indexOf( object );
  6844. if ( i !== -1 ) {
  6845. this.__objectsRemoved.splice( i, 1 );
  6846. }
  6847. }
  6848. }
  6849. for ( var c = 0; c < object.children.length; c ++ ) {
  6850. this.__addObject( object.children[ c ] );
  6851. }
  6852. };
  6853. THREE.Scene.prototype.__removeObject = function ( object ) {
  6854. if ( object instanceof THREE.Light ) {
  6855. var i = this.__lights.indexOf( object );
  6856. if ( i !== -1 ) {
  6857. this.__lights.splice( i, 1 );
  6858. }
  6859. } else if ( !( object instanceof THREE.Camera ) ) {
  6860. var i = this.__objects.indexOf( object );
  6861. if( i !== -1 ) {
  6862. this.__objects.splice( i, 1 );
  6863. this.__objectsRemoved.push( object );
  6864. // check if previously added
  6865. var ai = this.__objectsAdded.indexOf( object );
  6866. if ( ai !== -1 ) {
  6867. this.__objectsAdded.splice( ai, 1 );
  6868. }
  6869. }
  6870. }
  6871. for ( var c = 0; c < object.children.length; c ++ ) {
  6872. this.__removeObject( object.children[ c ] );
  6873. }
  6874. };
  6875. /**
  6876. * @author mrdoob / http://mrdoob.com/
  6877. * @author alteredq / http://alteredqualia.com/
  6878. */
  6879. THREE.Fog = function ( hex, near, far ) {
  6880. this.color = new THREE.Color( hex );
  6881. this.near = ( near !== undefined ) ? near : 1;
  6882. this.far = ( far !== undefined ) ? far : 1000;
  6883. };
  6884. /**
  6885. * @author mrdoob / http://mrdoob.com/
  6886. * @author alteredq / http://alteredqualia.com/
  6887. */
  6888. THREE.FogExp2 = function ( hex, density ) {
  6889. this.color = new THREE.Color( hex );
  6890. this.density = ( density !== undefined ) ? density : 0.00025;
  6891. };
  6892. /**
  6893. * @author mrdoob / http://mrdoob.com/
  6894. */
  6895. THREE.CanvasRenderer = function ( parameters ) {
  6896. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  6897. parameters = parameters || {};
  6898. var _this = this,
  6899. _renderData, _elements, _lights,
  6900. _projector = new THREE.Projector(),
  6901. _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  6902. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  6903. _context = _canvas.getContext( '2d' ),
  6904. _clearColor = new THREE.Color( 0x000000 ),
  6905. _clearOpacity = 0,
  6906. _contextGlobalAlpha = 1,
  6907. _contextGlobalCompositeOperation = 0,
  6908. _contextStrokeStyle = null,
  6909. _contextFillStyle = null,
  6910. _contextLineWidth = null,
  6911. _contextLineCap = null,
  6912. _contextLineJoin = null,
  6913. _v1, _v2, _v3, _v4,
  6914. _v5 = new THREE.RenderableVertex(),
  6915. _v6 = new THREE.RenderableVertex(),
  6916. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  6917. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  6918. _color = new THREE.Color(),
  6919. _color1 = new THREE.Color(),
  6920. _color2 = new THREE.Color(),
  6921. _color3 = new THREE.Color(),
  6922. _color4 = new THREE.Color(),
  6923. _patterns = [], _imagedatas = [],
  6924. _near, _far,
  6925. _image, _uvs,
  6926. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  6927. _clipRect = new THREE.Rectangle(),
  6928. _clearRect = new THREE.Rectangle(),
  6929. _bboxRect = new THREE.Rectangle(),
  6930. _enableLighting = false,
  6931. _ambientLight = new THREE.Color(),
  6932. _directionalLights = new THREE.Color(),
  6933. _pointLights = new THREE.Color(),
  6934. _pi2 = Math.PI * 2,
  6935. _vector3 = new THREE.Vector3(), // Needed for PointLight
  6936. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  6937. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  6938. _pixelMap = document.createElement( 'canvas' );
  6939. _pixelMap.width = _pixelMap.height = 2;
  6940. _pixelMapContext = _pixelMap.getContext( '2d' );
  6941. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  6942. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  6943. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  6944. _pixelMapData = _pixelMapImage.data;
  6945. _gradientMap = document.createElement( 'canvas' );
  6946. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  6947. _gradientMapContext = _gradientMap.getContext( '2d' );
  6948. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  6949. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  6950. _gradientMapQuality --; // Fix UVs
  6951. this.domElement = _canvas;
  6952. this.autoClear = true;
  6953. this.sortObjects = true;
  6954. this.sortElements = true;
  6955. this.info = {
  6956. render: {
  6957. vertices: 0,
  6958. faces: 0
  6959. }
  6960. }
  6961. this.setSize = function ( width, height ) {
  6962. _canvasWidth = width;
  6963. _canvasHeight = height;
  6964. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  6965. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  6966. _canvas.width = _canvasWidth;
  6967. _canvas.height = _canvasHeight;
  6968. _clipRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  6969. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  6970. _contextGlobalAlpha = 1;
  6971. _contextGlobalCompositeOperation = 0;
  6972. _contextStrokeStyle = null;
  6973. _contextFillStyle = null;
  6974. _contextLineWidth = null;
  6975. _contextLineCap = null;
  6976. _contextLineJoin = null;
  6977. };
  6978. this.setClearColor = function ( color, opacity ) {
  6979. _clearColor.copy( color );
  6980. _clearOpacity = opacity !== undefined ? opacity : 1;
  6981. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  6982. };
  6983. this.setClearColorHex = function ( hex, opacity ) {
  6984. _clearColor.setHex( hex );
  6985. _clearOpacity = opacity !== undefined ? opacity : 1;
  6986. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  6987. };
  6988. this.clear = function () {
  6989. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  6990. if ( _clearRect.isEmpty() === false ) {
  6991. _clearRect.minSelf( _clipRect );
  6992. _clearRect.inflate( 2 );
  6993. if ( _clearOpacity < 1 ) {
  6994. _context.clearRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  6995. }
  6996. if ( _clearOpacity > 0 ) {
  6997. setBlending( THREE.NormalBlending );
  6998. setOpacity( 1 );
  6999. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  7000. _context.fillRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  7001. }
  7002. _clearRect.empty();
  7003. }
  7004. };
  7005. this.render = function ( scene, camera ) {
  7006. if ( camera instanceof THREE.Camera === false ) {
  7007. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  7008. return;
  7009. }
  7010. var e, el, element, material;
  7011. this.autoClear === true ? this.clear() : _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7012. _this.info.render.vertices = 0;
  7013. _this.info.render.faces = 0;
  7014. _renderData = _projector.projectScene( scene, camera, this.sortElements );
  7015. _elements = _renderData.elements;
  7016. _lights = _renderData.lights;
  7017. /* DEBUG
  7018. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  7019. _context.fillRect( _clipRect.getX(), _clipRect.getY(), _clipRect.getWidth(), _clipRect.getHeight() );
  7020. */
  7021. _enableLighting = _lights.length > 0;
  7022. if ( _enableLighting === true ) {
  7023. calculateLights();
  7024. }
  7025. for ( e = 0, el = _elements.length; e < el; e++ ) {
  7026. element = _elements[ e ];
  7027. material = element.material;
  7028. if ( material === undefined || material.visible === false ) continue;
  7029. _bboxRect.empty();
  7030. if ( element instanceof THREE.RenderableParticle ) {
  7031. _v1 = element;
  7032. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  7033. renderParticle( _v1, element, material, scene );
  7034. } else if ( element instanceof THREE.RenderableLine ) {
  7035. _v1 = element.v1; _v2 = element.v2;
  7036. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7037. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7038. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7039. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7040. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7041. renderLine( _v1, _v2, element, material, scene );
  7042. }
  7043. } else if ( element instanceof THREE.RenderableFace3 ) {
  7044. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  7045. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7046. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7047. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7048. if ( material.overdraw === true ) {
  7049. expand( _v1.positionScreen, _v2.positionScreen );
  7050. expand( _v2.positionScreen, _v3.positionScreen );
  7051. expand( _v3.positionScreen, _v1.positionScreen );
  7052. }
  7053. _bboxRect.add3Points( _v1.positionScreen.x, _v1.positionScreen.y,
  7054. _v2.positionScreen.x, _v2.positionScreen.y,
  7055. _v3.positionScreen.x, _v3.positionScreen.y );
  7056. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7057. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  7058. }
  7059. } else if ( element instanceof THREE.RenderableFace4 ) {
  7060. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  7061. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7062. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7063. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7064. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  7065. _v5.positionScreen.copy( _v2.positionScreen );
  7066. _v6.positionScreen.copy( _v4.positionScreen );
  7067. if ( material.overdraw === true ) {
  7068. expand( _v1.positionScreen, _v2.positionScreen );
  7069. expand( _v2.positionScreen, _v4.positionScreen );
  7070. expand( _v4.positionScreen, _v1.positionScreen );
  7071. expand( _v3.positionScreen, _v5.positionScreen );
  7072. expand( _v3.positionScreen, _v6.positionScreen );
  7073. }
  7074. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7075. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7076. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  7077. _bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );
  7078. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7079. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  7080. }
  7081. }
  7082. /* DEBUG
  7083. _context.lineWidth = 1;
  7084. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  7085. _context.strokeRect( _bboxRect.getX(), _bboxRect.getY(), _bboxRect.getWidth(), _bboxRect.getHeight() );
  7086. */
  7087. _clearRect.addRectangle( _bboxRect );
  7088. }
  7089. /* DEBUG
  7090. _context.lineWidth = 1;
  7091. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  7092. _context.strokeRect( _clearRect.getX(), _clearRect.getY(), _clearRect.getWidth(), _clearRect.getHeight() );
  7093. */
  7094. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  7095. //
  7096. function calculateLights() {
  7097. _ambientLight.setRGB( 0, 0, 0 );
  7098. _directionalLights.setRGB( 0, 0, 0 );
  7099. _pointLights.setRGB( 0, 0, 0 );
  7100. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  7101. var light = _lights[ l ];
  7102. var lightColor = light.color;
  7103. if ( light instanceof THREE.AmbientLight ) {
  7104. _ambientLight.r += lightColor.r;
  7105. _ambientLight.g += lightColor.g;
  7106. _ambientLight.b += lightColor.b;
  7107. } else if ( light instanceof THREE.DirectionalLight ) {
  7108. // for particles
  7109. _directionalLights.r += lightColor.r;
  7110. _directionalLights.g += lightColor.g;
  7111. _directionalLights.b += lightColor.b;
  7112. } else if ( light instanceof THREE.PointLight ) {
  7113. // for particles
  7114. _pointLights.r += lightColor.r;
  7115. _pointLights.g += lightColor.g;
  7116. _pointLights.b += lightColor.b;
  7117. }
  7118. }
  7119. }
  7120. function calculateLight( position, normal, color ) {
  7121. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  7122. var light = _lights[ l ];
  7123. var lightColor = light.color;
  7124. if ( light instanceof THREE.DirectionalLight ) {
  7125. var lightPosition = light.matrixWorld.getPosition().normalize();
  7126. var amount = normal.dot( lightPosition );
  7127. if ( amount <= 0 ) continue;
  7128. amount *= light.intensity;
  7129. color.r += lightColor.r * amount;
  7130. color.g += lightColor.g * amount;
  7131. color.b += lightColor.b * amount;
  7132. } else if ( light instanceof THREE.PointLight ) {
  7133. var lightPosition = light.matrixWorld.getPosition();
  7134. var amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  7135. if ( amount <= 0 ) continue;
  7136. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  7137. if ( amount == 0 ) continue;
  7138. amount *= light.intensity;
  7139. color.r += lightColor.r * amount;
  7140. color.g += lightColor.g * amount;
  7141. color.b += lightColor.b * amount;
  7142. }
  7143. }
  7144. }
  7145. function renderParticle( v1, element, material, scene ) {
  7146. setOpacity( material.opacity );
  7147. setBlending( material.blending );
  7148. var width, height, scaleX, scaleY,
  7149. bitmap, bitmapWidth, bitmapHeight;
  7150. if ( material instanceof THREE.ParticleBasicMaterial ) {
  7151. if ( material.map === null ) {
  7152. scaleX = element.object.scale.x;
  7153. scaleY = element.object.scale.y;
  7154. // TODO: Be able to disable this
  7155. scaleX *= element.scale.x * _canvasWidthHalf;
  7156. scaleY *= element.scale.y * _canvasHeightHalf;
  7157. _bboxRect.set( v1.x - scaleX, v1.y - scaleY, v1.x + scaleX, v1.y + scaleY );
  7158. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7159. return;
  7160. }
  7161. setFillStyle( material.color.getContextStyle() );
  7162. _context.save();
  7163. _context.translate( v1.x, v1.y );
  7164. _context.rotate( - element.rotation );
  7165. _context.scale( scaleX, scaleY );
  7166. _context.fillRect( -1, -1, 2, 2 );
  7167. _context.restore();
  7168. } else {
  7169. bitmap = material.map.image;
  7170. bitmapWidth = bitmap.width >> 1;
  7171. bitmapHeight = bitmap.height >> 1;
  7172. scaleX = element.scale.x * _canvasWidthHalf;
  7173. scaleY = element.scale.y * _canvasHeightHalf;
  7174. width = scaleX * bitmapWidth;
  7175. height = scaleY * bitmapHeight;
  7176. // TODO: Rotations break this...
  7177. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7178. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7179. return;
  7180. }
  7181. _context.save();
  7182. _context.translate( v1.x, v1.y );
  7183. _context.rotate( - element.rotation );
  7184. _context.scale( scaleX, - scaleY );
  7185. _context.translate( - bitmapWidth, - bitmapHeight );
  7186. _context.drawImage( bitmap, 0, 0 );
  7187. _context.restore();
  7188. }
  7189. /* DEBUG
  7190. setStrokeStyle( 'rgb(255,255,0)' );
  7191. _context.beginPath();
  7192. _context.moveTo( v1.x - 10, v1.y );
  7193. _context.lineTo( v1.x + 10, v1.y );
  7194. _context.moveTo( v1.x, v1.y - 10 );
  7195. _context.lineTo( v1.x, v1.y + 10 );
  7196. _context.stroke();
  7197. */
  7198. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  7199. width = element.scale.x * _canvasWidthHalf;
  7200. height = element.scale.y * _canvasHeightHalf;
  7201. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7202. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7203. return;
  7204. }
  7205. setStrokeStyle( material.color.getContextStyle() );
  7206. setFillStyle( material.color.getContextStyle() );
  7207. _context.save();
  7208. _context.translate( v1.x, v1.y );
  7209. _context.rotate( - element.rotation );
  7210. _context.scale( width, height );
  7211. material.program( _context );
  7212. _context.restore();
  7213. }
  7214. }
  7215. function renderLine( v1, v2, element, material, scene ) {
  7216. setOpacity( material.opacity );
  7217. setBlending( material.blending );
  7218. _context.beginPath();
  7219. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  7220. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  7221. if ( material instanceof THREE.LineBasicMaterial ) {
  7222. setLineWidth( material.linewidth );
  7223. setLineCap( material.linecap );
  7224. setLineJoin( material.linejoin );
  7225. setStrokeStyle( material.color.getContextStyle() );
  7226. _context.stroke();
  7227. _bboxRect.inflate( material.linewidth * 2 );
  7228. }
  7229. }
  7230. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  7231. _this.info.render.vertices += 3;
  7232. _this.info.render.faces ++;
  7233. setOpacity( material.opacity );
  7234. setBlending( material.blending );
  7235. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7236. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7237. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7238. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  7239. if ( material instanceof THREE.MeshBasicMaterial ) {
  7240. if ( material.map !== null ) {
  7241. if ( material.map.mapping instanceof THREE.UVMapping ) {
  7242. _uvs = element.uvs[ 0 ];
  7243. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uvs[ uv1 ].u, _uvs[ uv1 ].v, _uvs[ uv2 ].u, _uvs[ uv2 ].v, _uvs[ uv3 ].u, _uvs[ uv3 ].v, material.map );
  7244. }
  7245. } else if ( material.envMap !== null ) {
  7246. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  7247. var cameraMatrix = camera.matrixWorldInverse;
  7248. _vector3.copy( element.vertexNormalsWorld[ uv1 ] );
  7249. _uv1x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7250. _uv1y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7251. _vector3.copy( element.vertexNormalsWorld[ uv2 ] );
  7252. _uv2x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7253. _uv2y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7254. _vector3.copy( element.vertexNormalsWorld[ uv3 ] );
  7255. _uv3x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7256. _uv3y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7257. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  7258. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  7259. }*/
  7260. } else {
  7261. material.wireframe === true ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  7262. }
  7263. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  7264. if ( _enableLighting === true ) {
  7265. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  7266. _color1.r = _color2.r = _color3.r = _ambientLight.r;
  7267. _color1.g = _color2.g = _color3.g = _ambientLight.g;
  7268. _color1.b = _color2.b = _color3.b = _ambientLight.b;
  7269. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7270. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7271. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color3 );
  7272. _color1.r = Math.max( 0, Math.min( material.color.r * _color1.r, 1 ) );
  7273. _color1.g = Math.max( 0, Math.min( material.color.g * _color1.g, 1 ) );
  7274. _color1.b = Math.max( 0, Math.min( material.color.b * _color1.b, 1 ) );
  7275. _color2.r = Math.max( 0, Math.min( material.color.r * _color2.r, 1 ) );
  7276. _color2.g = Math.max( 0, Math.min( material.color.g * _color2.g, 1 ) );
  7277. _color2.b = Math.max( 0, Math.min( material.color.b * _color2.b, 1 ) );
  7278. _color3.r = Math.max( 0, Math.min( material.color.r * _color3.r, 1 ) );
  7279. _color3.g = Math.max( 0, Math.min( material.color.g * _color3.g, 1 ) );
  7280. _color3.b = Math.max( 0, Math.min( material.color.b * _color3.b, 1 ) );
  7281. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7282. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7283. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7284. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7285. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7286. } else {
  7287. _color.r = _ambientLight.r;
  7288. _color.g = _ambientLight.g;
  7289. _color.b = _ambientLight.b;
  7290. calculateLight( element.centroidWorld, element.normalWorld, _color );
  7291. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  7292. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  7293. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  7294. material.wireframe === true ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  7295. }
  7296. } else {
  7297. material.wireframe === true ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  7298. }
  7299. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7300. _near = camera.near;
  7301. _far = camera.far;
  7302. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7303. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7304. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7305. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7306. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7307. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7308. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7309. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7310. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7311. _color.r = normalToComponent( element.normalWorld.x );
  7312. _color.g = normalToComponent( element.normalWorld.y );
  7313. _color.b = normalToComponent( element.normalWorld.z );
  7314. material.wireframe === true ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  7315. }
  7316. }
  7317. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  7318. _this.info.render.vertices += 4;
  7319. _this.info.render.faces ++;
  7320. setOpacity( material.opacity );
  7321. setBlending( material.blending );
  7322. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  7323. // Let renderFace3() handle this
  7324. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  7325. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  7326. return;
  7327. }
  7328. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7329. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7330. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7331. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  7332. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  7333. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  7334. if ( material instanceof THREE.MeshBasicMaterial ) {
  7335. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7336. material.wireframe === true ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  7337. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  7338. if ( _enableLighting === true ) {
  7339. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  7340. _color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
  7341. _color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
  7342. _color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;
  7343. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7344. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7345. calculateLight( element.v4.positionWorld, element.vertexNormalsWorld[ 3 ], _color3 );
  7346. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color4 );
  7347. _color1.r = Math.max( 0, Math.min( material.color.r * _color1.r, 1 ) );
  7348. _color1.g = Math.max( 0, Math.min( material.color.g * _color1.g, 1 ) );
  7349. _color1.b = Math.max( 0, Math.min( material.color.b * _color1.b, 1 ) );
  7350. _color2.r = Math.max( 0, Math.min( material.color.r * _color2.r, 1 ) );
  7351. _color2.g = Math.max( 0, Math.min( material.color.g * _color2.g, 1 ) );
  7352. _color2.b = Math.max( 0, Math.min( material.color.b * _color2.b, 1 ) );
  7353. _color3.r = Math.max( 0, Math.min( material.color.r * _color3.r, 1 ) );
  7354. _color3.g = Math.max( 0, Math.min( material.color.g * _color3.g, 1 ) );
  7355. _color3.b = Math.max( 0, Math.min( material.color.b * _color3.b, 1 ) );
  7356. _color4.r = Math.max( 0, Math.min( material.color.r * _color4.r, 1 ) );
  7357. _color4.g = Math.max( 0, Math.min( material.color.g * _color4.g, 1 ) );
  7358. _color4.b = Math.max( 0, Math.min( material.color.b * _color4.b, 1 ) );
  7359. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7360. // TODO: UVs are incorrect, v4->v3?
  7361. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7362. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7363. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7364. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7365. } else {
  7366. _color.r = _ambientLight.r;
  7367. _color.g = _ambientLight.g;
  7368. _color.b = _ambientLight.b;
  7369. calculateLight( element.centroidWorld, element.normalWorld, _color );
  7370. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  7371. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  7372. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  7373. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7374. material.wireframe === true ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  7375. }
  7376. } else {
  7377. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7378. material.wireframe === true ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  7379. }
  7380. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7381. _color.r = normalToComponent( element.normalWorld.x );
  7382. _color.g = normalToComponent( element.normalWorld.y );
  7383. _color.b = normalToComponent( element.normalWorld.z );
  7384. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7385. material.wireframe === true ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  7386. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7387. _near = camera.near;
  7388. _far = camera.far;
  7389. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7390. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7391. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  7392. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7393. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7394. // TODO: UVs are incorrect, v4->v3?
  7395. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7396. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7397. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7398. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7399. }
  7400. }
  7401. //
  7402. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  7403. _context.beginPath();
  7404. _context.moveTo( x0, y0 );
  7405. _context.lineTo( x1, y1 );
  7406. _context.lineTo( x2, y2 );
  7407. _context.closePath();
  7408. }
  7409. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  7410. _context.beginPath();
  7411. _context.moveTo( x0, y0 );
  7412. _context.lineTo( x1, y1 );
  7413. _context.lineTo( x2, y2 );
  7414. _context.lineTo( x3, y3 );
  7415. _context.closePath();
  7416. }
  7417. function strokePath( color, linewidth, linecap, linejoin ) {
  7418. setLineWidth( linewidth );
  7419. setLineCap( linecap );
  7420. setLineJoin( linejoin );
  7421. setStrokeStyle( color.getContextStyle() );
  7422. _context.stroke();
  7423. _bboxRect.inflate( linewidth * 2 );
  7424. }
  7425. function fillPath( color ) {
  7426. setFillStyle( color.getContextStyle() );
  7427. _context.fill();
  7428. }
  7429. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  7430. if ( texture.image === undefined || texture.image.width === 0 ) return;
  7431. if ( texture.needsUpdate === true || _patterns[ texture.id ] === undefined ) {
  7432. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  7433. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  7434. _patterns[ texture.id ] = _context.createPattern( texture.image, repeatX === true && repeatY === true ? 'repeat' : repeatX === true && repeatY === false ? 'repeat-x' : repeatX === false && repeatY === true ? 'repeat-y' : 'no-repeat' );
  7435. texture.needsUpdate = false;
  7436. }
  7437. setFillStyle( _patterns[ texture.id ] );
  7438. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7439. var a, b, c, d, e, f, det, idet,
  7440. offsetX = texture.offset.x / texture.repeat.x,
  7441. offsetY = texture.offset.y / texture.repeat.y,
  7442. width = texture.image.width * texture.repeat.x,
  7443. height = texture.image.height * texture.repeat.y;
  7444. u0 = ( u0 + offsetX ) * width;
  7445. v0 = ( 1.0 - v0 + offsetY ) * height;
  7446. u1 = ( u1 + offsetX ) * width;
  7447. v1 = ( 1.0 - v1 + offsetY ) * height;
  7448. u2 = ( u2 + offsetX ) * width;
  7449. v2 = ( 1.0 - v2 + offsetY ) * height;
  7450. x1 -= x0; y1 -= y0;
  7451. x2 -= x0; y2 -= y0;
  7452. u1 -= u0; v1 -= v0;
  7453. u2 -= u0; v2 -= v0;
  7454. det = u1 * v2 - u2 * v1;
  7455. if ( det === 0 ) {
  7456. if ( _imagedatas[ texture.id ] === undefined ) {
  7457. var canvas = document.createElement( 'canvas' )
  7458. canvas.width = texture.image.width;
  7459. canvas.height = texture.image.height;
  7460. var context = canvas.getContext( '2d' );
  7461. context.drawImage( texture.image, 0, 0 );
  7462. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  7463. }
  7464. var data = _imagedatas[ texture.id ];
  7465. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  7466. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  7467. fillPath( _color );
  7468. return;
  7469. }
  7470. idet = 1 / det;
  7471. a = ( v2 * x1 - v1 * x2 ) * idet;
  7472. b = ( v2 * y1 - v1 * y2 ) * idet;
  7473. c = ( u1 * x2 - u2 * x1 ) * idet;
  7474. d = ( u1 * y2 - u2 * y1 ) * idet;
  7475. e = x0 - a * u0 - c * v0;
  7476. f = y0 - b * u0 - d * v0;
  7477. _context.save();
  7478. _context.transform( a, b, c, d, e, f );
  7479. _context.fill();
  7480. _context.restore();
  7481. }
  7482. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  7483. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7484. var a, b, c, d, e, f, det, idet,
  7485. width = image.width - 1,
  7486. height = image.height - 1;
  7487. u0 *= width; v0 *= height;
  7488. u1 *= width; v1 *= height;
  7489. u2 *= width; v2 *= height;
  7490. x1 -= x0; y1 -= y0;
  7491. x2 -= x0; y2 -= y0;
  7492. u1 -= u0; v1 -= v0;
  7493. u2 -= u0; v2 -= v0;
  7494. det = u1 * v2 - u2 * v1;
  7495. idet = 1 / det;
  7496. a = ( v2 * x1 - v1 * x2 ) * idet;
  7497. b = ( v2 * y1 - v1 * y2 ) * idet;
  7498. c = ( u1 * x2 - u2 * x1 ) * idet;
  7499. d = ( u1 * y2 - u2 * y1 ) * idet;
  7500. e = x0 - a * u0 - c * v0;
  7501. f = y0 - b * u0 - d * v0;
  7502. _context.save();
  7503. _context.transform( a, b, c, d, e, f );
  7504. _context.clip();
  7505. _context.drawImage( image, 0, 0 );
  7506. _context.restore();
  7507. }
  7508. function getGradientTexture( color1, color2, color3, color4 ) {
  7509. // http://mrdoob.com/blog/post/710
  7510. var c1r = ( color1.r * 255 ) | 0, c1g = ( color1.g * 255 ) | 0, c1b = ( color1.b * 255 ) | 0;
  7511. var c2r = ( color2.r * 255 ) | 0, c2g = ( color2.g * 255 ) | 0, c2b = ( color2.b * 255 ) | 0;
  7512. var c3r = ( color3.r * 255 ) | 0, c3g = ( color3.g * 255 ) | 0, c3b = ( color3.b * 255 ) | 0;
  7513. var c4r = ( color4.r * 255 ) | 0, c4g = ( color4.g * 255 ) | 0, c4b = ( color4.b * 255 ) | 0;
  7514. _pixelMapData[ 0 ] = c1r < 0 ? 0 : c1r > 255 ? 255 : c1r;
  7515. _pixelMapData[ 1 ] = c1g < 0 ? 0 : c1g > 255 ? 255 : c1g;
  7516. _pixelMapData[ 2 ] = c1b < 0 ? 0 : c1b > 255 ? 255 : c1b;
  7517. _pixelMapData[ 4 ] = c2r < 0 ? 0 : c2r > 255 ? 255 : c2r;
  7518. _pixelMapData[ 5 ] = c2g < 0 ? 0 : c2g > 255 ? 255 : c2g;
  7519. _pixelMapData[ 6 ] = c2b < 0 ? 0 : c2b > 255 ? 255 : c2b;
  7520. _pixelMapData[ 8 ] = c3r < 0 ? 0 : c3r > 255 ? 255 : c3r;
  7521. _pixelMapData[ 9 ] = c3g < 0 ? 0 : c3g > 255 ? 255 : c3g;
  7522. _pixelMapData[ 10 ] = c3b < 0 ? 0 : c3b > 255 ? 255 : c3b;
  7523. _pixelMapData[ 12 ] = c4r < 0 ? 0 : c4r > 255 ? 255 : c4r;
  7524. _pixelMapData[ 13 ] = c4g < 0 ? 0 : c4g > 255 ? 255 : c4g;
  7525. _pixelMapData[ 14 ] = c4b < 0 ? 0 : c4b > 255 ? 255 : c4b;
  7526. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  7527. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  7528. return _gradientMap;
  7529. }
  7530. function smoothstep( value, min, max ) {
  7531. var x = ( value - min ) / ( max - min );
  7532. return x * x * ( 3 - 2 * x );
  7533. }
  7534. function normalToComponent( normal ) {
  7535. var component = ( normal + 1 ) * 0.5;
  7536. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  7537. }
  7538. // Hide anti-alias gaps
  7539. function expand( v1, v2 ) {
  7540. var x = v2.x - v1.x, y = v2.y - v1.y,
  7541. det = x * x + y * y, idet;
  7542. if ( det === 0 ) return;
  7543. idet = 1 / Math.sqrt( det );
  7544. x *= idet; y *= idet;
  7545. v2.x += x; v2.y += y;
  7546. v1.x -= x; v1.y -= y;
  7547. }
  7548. };
  7549. // Context cached methods.
  7550. function setOpacity( value ) {
  7551. if ( _contextGlobalAlpha !== value ) {
  7552. _context.globalAlpha = value;
  7553. _contextGlobalAlpha = value;
  7554. }
  7555. }
  7556. function setBlending( value ) {
  7557. if ( _contextGlobalCompositeOperation !== value ) {
  7558. if ( value === THREE.NormalBlending ) {
  7559. _context.globalCompositeOperation = 'source-over';
  7560. } else if ( value === THREE.AdditiveBlending ) {
  7561. _context.globalCompositeOperation = 'lighter';
  7562. } else if ( value === THREE.SubtractiveBlending ) {
  7563. _context.globalCompositeOperation = 'darker';
  7564. }
  7565. _contextGlobalCompositeOperation = value;
  7566. }
  7567. }
  7568. function setLineWidth( value ) {
  7569. if ( _contextLineWidth !== value ) {
  7570. _context.lineWidth = value;
  7571. _contextLineWidth = value;
  7572. }
  7573. }
  7574. function setLineCap( value ) {
  7575. // "butt", "round", "square"
  7576. if ( _contextLineCap !== value ) {
  7577. _context.lineCap = value;
  7578. _contextLineCap = value;
  7579. }
  7580. }
  7581. function setLineJoin( value ) {
  7582. // "round", "bevel", "miter"
  7583. if ( _contextLineJoin !== value ) {
  7584. _context.lineJoin = value;
  7585. _contextLineJoin = value;
  7586. }
  7587. }
  7588. function setStrokeStyle( value ) {
  7589. if ( _contextStrokeStyle !== value ) {
  7590. _context.strokeStyle = value;
  7591. _contextStrokeStyle = value;
  7592. }
  7593. }
  7594. function setFillStyle( value ) {
  7595. if ( _contextFillStyle !== value ) {
  7596. _context.fillStyle = value;
  7597. _contextFillStyle = value;
  7598. }
  7599. }
  7600. };
  7601. /**
  7602. * @author alteredq / http://alteredqualia.com/
  7603. * @author mrdoob / http://mrdoob.com/
  7604. * @author mikael emtinger / http://gomo.se/
  7605. */
  7606. THREE.ShaderChunk = {
  7607. // FOG
  7608. fog_pars_fragment: [
  7609. "#ifdef USE_FOG",
  7610. "uniform vec3 fogColor;",
  7611. "#ifdef FOG_EXP2",
  7612. "uniform float fogDensity;",
  7613. "#else",
  7614. "uniform float fogNear;",
  7615. "uniform float fogFar;",
  7616. "#endif",
  7617. "#endif"
  7618. ].join("\n"),
  7619. fog_fragment: [
  7620. "#ifdef USE_FOG",
  7621. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  7622. "#ifdef FOG_EXP2",
  7623. "const float LOG2 = 1.442695;",
  7624. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  7625. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  7626. "#else",
  7627. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  7628. "#endif",
  7629. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  7630. "#endif"
  7631. ].join("\n"),
  7632. // ENVIRONMENT MAP
  7633. envmap_pars_fragment: [
  7634. "#ifdef USE_ENVMAP",
  7635. "uniform float reflectivity;",
  7636. "uniform samplerCube envMap;",
  7637. "uniform float flipEnvMap;",
  7638. "uniform int combine;",
  7639. "#ifdef USE_BUMPMAP",
  7640. "uniform bool useRefract;",
  7641. "uniform float refractionRatio;",
  7642. "#else",
  7643. "varying vec3 vReflect;",
  7644. "#endif",
  7645. "#endif"
  7646. ].join("\n"),
  7647. envmap_fragment: [
  7648. "#ifdef USE_ENVMAP",
  7649. "vec3 reflectVec;",
  7650. "#ifdef USE_BUMPMAP",
  7651. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  7652. "if ( useRefract ) {",
  7653. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  7654. "} else { ",
  7655. "reflectVec = reflect( cameraToVertex, normal );",
  7656. "}",
  7657. "#else",
  7658. "reflectVec = vReflect;",
  7659. "#endif",
  7660. "#ifdef DOUBLE_SIDED",
  7661. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  7662. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  7663. "#else",
  7664. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  7665. "#endif",
  7666. "#ifdef GAMMA_INPUT",
  7667. "cubeColor.xyz *= cubeColor.xyz;",
  7668. "#endif",
  7669. "if ( combine == 1 ) {",
  7670. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  7671. "} else {",
  7672. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  7673. "}",
  7674. "#endif"
  7675. ].join("\n"),
  7676. envmap_pars_vertex: [
  7677. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP )",
  7678. "varying vec3 vReflect;",
  7679. "uniform float refractionRatio;",
  7680. "uniform bool useRefract;",
  7681. "#endif"
  7682. ].join("\n"),
  7683. worldpos_vertex : [
  7684. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  7685. "#ifdef USE_SKINNING",
  7686. "vec4 mPosition = modelMatrix * skinned;",
  7687. "#endif",
  7688. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  7689. "vec4 mPosition = modelMatrix * vec4( morphed, 1.0 );",
  7690. "#endif",
  7691. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  7692. "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
  7693. "#endif",
  7694. "#endif"
  7695. ].join("\n"),
  7696. envmap_vertex : [
  7697. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP )",
  7698. "vec3 nWorld = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  7699. "if ( useRefract ) {",
  7700. "vReflect = refract( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ), refractionRatio );",
  7701. "} else {",
  7702. "vReflect = reflect( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ) );",
  7703. "}",
  7704. "#endif"
  7705. ].join("\n"),
  7706. // COLOR MAP (particles)
  7707. map_particle_pars_fragment: [
  7708. "#ifdef USE_MAP",
  7709. "uniform sampler2D map;",
  7710. "#endif"
  7711. ].join("\n"),
  7712. map_particle_fragment: [
  7713. "#ifdef USE_MAP",
  7714. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  7715. "#endif"
  7716. ].join("\n"),
  7717. // COLOR MAP (triangles)
  7718. map_pars_vertex: [
  7719. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_SPECULARMAP )",
  7720. "varying vec2 vUv;",
  7721. "uniform vec4 offsetRepeat;",
  7722. "#endif"
  7723. ].join("\n"),
  7724. map_pars_fragment: [
  7725. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_SPECULARMAP )",
  7726. "varying vec2 vUv;",
  7727. "#endif",
  7728. "#ifdef USE_MAP",
  7729. "uniform sampler2D map;",
  7730. "#endif",
  7731. ].join("\n"),
  7732. map_vertex: [
  7733. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_SPECULARMAP )",
  7734. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  7735. "#endif"
  7736. ].join("\n"),
  7737. map_fragment: [
  7738. "#ifdef USE_MAP",
  7739. "#ifdef GAMMA_INPUT",
  7740. "vec4 texelColor = texture2D( map, vUv );",
  7741. "texelColor.xyz *= texelColor.xyz;",
  7742. "gl_FragColor = gl_FragColor * texelColor;",
  7743. "#else",
  7744. "gl_FragColor = gl_FragColor * texture2D( map, vUv );",
  7745. "#endif",
  7746. "#endif"
  7747. ].join("\n"),
  7748. // LIGHT MAP
  7749. lightmap_pars_fragment: [
  7750. "#ifdef USE_LIGHTMAP",
  7751. "varying vec2 vUv2;",
  7752. "uniform sampler2D lightMap;",
  7753. "#endif"
  7754. ].join("\n"),
  7755. lightmap_pars_vertex: [
  7756. "#ifdef USE_LIGHTMAP",
  7757. "varying vec2 vUv2;",
  7758. "#endif"
  7759. ].join("\n"),
  7760. lightmap_fragment: [
  7761. "#ifdef USE_LIGHTMAP",
  7762. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  7763. "#endif"
  7764. ].join("\n"),
  7765. lightmap_vertex: [
  7766. "#ifdef USE_LIGHTMAP",
  7767. "vUv2 = uv2;",
  7768. "#endif"
  7769. ].join("\n"),
  7770. // BUMP MAP
  7771. bumpmap_pars_fragment: [
  7772. "#ifdef USE_BUMPMAP",
  7773. "uniform sampler2D bumpMap;",
  7774. "uniform float bumpScale;",
  7775. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  7776. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  7777. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  7778. "vec2 dHdxy_fwd() {",
  7779. "vec2 dSTdx = dFdx( vUv );",
  7780. "vec2 dSTdy = dFdy( vUv );",
  7781. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  7782. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  7783. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  7784. "return vec2( dBx, dBy );",
  7785. "}",
  7786. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  7787. "vec3 vSigmaX = dFdx( surf_pos );",
  7788. "vec3 vSigmaY = dFdy( surf_pos );",
  7789. "vec3 vN = surf_norm;", // normalized
  7790. "vec3 R1 = cross( vSigmaY, vN );",
  7791. "vec3 R2 = cross( vN, vSigmaX );",
  7792. "float fDet = dot( vSigmaX, R1 );",
  7793. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  7794. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  7795. "}",
  7796. "#endif"
  7797. ].join("\n"),
  7798. // SPECULAR MAP
  7799. specularmap_pars_fragment: [
  7800. "#ifdef USE_SPECULARMAP",
  7801. "uniform sampler2D specularMap;",
  7802. "#endif"
  7803. ].join("\n"),
  7804. specularmap_fragment: [
  7805. "float specularStrength;",
  7806. "#ifdef USE_SPECULARMAP",
  7807. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  7808. "specularStrength = texelSpecular.r;",
  7809. "#else",
  7810. "specularStrength = 1.0;",
  7811. "#endif"
  7812. ].join("\n"),
  7813. // LIGHTS LAMBERT
  7814. lights_lambert_pars_vertex: [
  7815. "uniform vec3 ambient;",
  7816. "uniform vec3 diffuse;",
  7817. "uniform vec3 emissive;",
  7818. "uniform vec3 ambientLightColor;",
  7819. "#if MAX_DIR_LIGHTS > 0",
  7820. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  7821. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  7822. "#endif",
  7823. "#if MAX_HEMI_LIGHTS > 0",
  7824. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  7825. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  7826. "uniform vec3 hemisphereLightPosition[ MAX_HEMI_LIGHTS ];",
  7827. "#endif",
  7828. "#if MAX_POINT_LIGHTS > 0",
  7829. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  7830. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  7831. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  7832. "#endif",
  7833. "#if MAX_SPOT_LIGHTS > 0",
  7834. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  7835. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  7836. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  7837. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  7838. "uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
  7839. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  7840. "#endif",
  7841. "#ifdef WRAP_AROUND",
  7842. "uniform vec3 wrapRGB;",
  7843. "#endif"
  7844. ].join("\n"),
  7845. lights_lambert_vertex: [
  7846. "vLightFront = vec3( 0.0 );",
  7847. "#ifdef DOUBLE_SIDED",
  7848. "vLightBack = vec3( 0.0 );",
  7849. "#endif",
  7850. "transformedNormal = normalize( transformedNormal );",
  7851. "#if MAX_DIR_LIGHTS > 0",
  7852. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  7853. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  7854. "vec3 dirVector = normalize( lDirection.xyz );",
  7855. "float dotProduct = dot( transformedNormal, dirVector );",
  7856. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  7857. "#ifdef DOUBLE_SIDED",
  7858. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  7859. "#ifdef WRAP_AROUND",
  7860. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  7861. "#endif",
  7862. "#endif",
  7863. "#ifdef WRAP_AROUND",
  7864. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  7865. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  7866. "#ifdef DOUBLE_SIDED",
  7867. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  7868. "#endif",
  7869. "#endif",
  7870. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  7871. "#ifdef DOUBLE_SIDED",
  7872. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  7873. "#endif",
  7874. "}",
  7875. "#endif",
  7876. "#if MAX_POINT_LIGHTS > 0",
  7877. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  7878. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  7879. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  7880. "float lDistance = 1.0;",
  7881. "if ( pointLightDistance[ i ] > 0.0 )",
  7882. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  7883. "lVector = normalize( lVector );",
  7884. "float dotProduct = dot( transformedNormal, lVector );",
  7885. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  7886. "#ifdef DOUBLE_SIDED",
  7887. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  7888. "#ifdef WRAP_AROUND",
  7889. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  7890. "#endif",
  7891. "#endif",
  7892. "#ifdef WRAP_AROUND",
  7893. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  7894. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  7895. "#ifdef DOUBLE_SIDED",
  7896. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  7897. "#endif",
  7898. "#endif",
  7899. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  7900. "#ifdef DOUBLE_SIDED",
  7901. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  7902. "#endif",
  7903. "}",
  7904. "#endif",
  7905. "#if MAX_SPOT_LIGHTS > 0",
  7906. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  7907. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  7908. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  7909. "lVector = normalize( lVector );",
  7910. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - mPosition.xyz ) );",
  7911. "if ( spotEffect > spotLightAngle[ i ] ) {",
  7912. "spotEffect = pow( spotEffect, spotLightExponent[ i ] );",
  7913. "float lDistance = 1.0;",
  7914. "if ( spotLightDistance[ i ] > 0.0 )",
  7915. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  7916. "float dotProduct = dot( transformedNormal, lVector );",
  7917. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  7918. "#ifdef DOUBLE_SIDED",
  7919. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  7920. "#ifdef WRAP_AROUND",
  7921. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  7922. "#endif",
  7923. "#endif",
  7924. "#ifdef WRAP_AROUND",
  7925. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  7926. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  7927. "#ifdef DOUBLE_SIDED",
  7928. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  7929. "#endif",
  7930. "#endif",
  7931. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  7932. "#ifdef DOUBLE_SIDED",
  7933. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  7934. "#endif",
  7935. "}",
  7936. "}",
  7937. "#endif",
  7938. "#if MAX_HEMI_LIGHTS > 0",
  7939. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  7940. "vec4 lPosition = viewMatrix * vec4( hemisphereLightPosition[ i ], 1.0 );",
  7941. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  7942. "lVector = normalize( lVector );",
  7943. "float dotProduct = dot( normal, lVector );",
  7944. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  7945. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  7946. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  7947. "#ifdef DOUBLE_SIDED",
  7948. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  7949. "#endif",
  7950. "}",
  7951. "#endif",
  7952. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  7953. "#ifdef DOUBLE_SIDED",
  7954. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  7955. "#endif"
  7956. ].join("\n"),
  7957. // LIGHTS PHONG
  7958. lights_phong_pars_vertex: [
  7959. "#ifndef PHONG_PER_PIXEL",
  7960. "#if MAX_POINT_LIGHTS > 0",
  7961. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  7962. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  7963. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  7964. "#endif",
  7965. "#if MAX_SPOT_LIGHTS > 0",
  7966. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  7967. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  7968. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  7969. "#endif",
  7970. "#endif",
  7971. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  7972. "varying vec3 vWorldPosition;",
  7973. "#endif"
  7974. ].join("\n"),
  7975. lights_phong_vertex: [
  7976. "#ifndef PHONG_PER_PIXEL",
  7977. "#if MAX_POINT_LIGHTS > 0",
  7978. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  7979. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  7980. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  7981. "float lDistance = 1.0;",
  7982. "if ( pointLightDistance[ i ] > 0.0 )",
  7983. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  7984. "vPointLight[ i ] = vec4( lVector, lDistance );",
  7985. "}",
  7986. "#endif",
  7987. "#if MAX_SPOT_LIGHTS > 0",
  7988. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  7989. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  7990. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  7991. "float lDistance = 1.0;",
  7992. "if ( spotLightDistance[ i ] > 0.0 )",
  7993. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  7994. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  7995. "}",
  7996. "#endif",
  7997. "#endif",
  7998. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  7999. "vWorldPosition = mPosition.xyz;",
  8000. "#endif"
  8001. ].join("\n"),
  8002. lights_phong_pars_fragment: [
  8003. "uniform vec3 ambientLightColor;",
  8004. "#if MAX_DIR_LIGHTS > 0",
  8005. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8006. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8007. "#endif",
  8008. "#if MAX_HEMI_LIGHTS > 0",
  8009. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8010. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8011. "uniform vec3 hemisphereLightPosition[ MAX_HEMI_LIGHTS ];",
  8012. "#endif",
  8013. "#if MAX_POINT_LIGHTS > 0",
  8014. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8015. "#ifdef PHONG_PER_PIXEL",
  8016. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8017. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8018. "#else",
  8019. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  8020. "#endif",
  8021. "#endif",
  8022. "#if MAX_SPOT_LIGHTS > 0",
  8023. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8024. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8025. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8026. "uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
  8027. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8028. "#ifdef PHONG_PER_PIXEL",
  8029. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8030. "#else",
  8031. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  8032. "#endif",
  8033. "#endif",
  8034. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8035. "varying vec3 vWorldPosition;",
  8036. "#endif",
  8037. "#ifdef WRAP_AROUND",
  8038. "uniform vec3 wrapRGB;",
  8039. "#endif",
  8040. "varying vec3 vViewPosition;",
  8041. "varying vec3 vNormal;"
  8042. ].join("\n"),
  8043. lights_phong_fragment: [
  8044. "vec3 normal = normalize( vNormal );",
  8045. "vec3 viewPosition = normalize( vViewPosition );",
  8046. "#ifdef DOUBLE_SIDED",
  8047. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8048. "#endif",
  8049. "#ifdef USE_BUMPMAP",
  8050. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  8051. "#endif",
  8052. "#if MAX_POINT_LIGHTS > 0",
  8053. "vec3 pointDiffuse = vec3( 0.0 );",
  8054. "vec3 pointSpecular = vec3( 0.0 );",
  8055. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8056. "#ifdef PHONG_PER_PIXEL",
  8057. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8058. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8059. "float lDistance = 1.0;",
  8060. "if ( pointLightDistance[ i ] > 0.0 )",
  8061. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8062. "lVector = normalize( lVector );",
  8063. "#else",
  8064. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  8065. "float lDistance = vPointLight[ i ].w;",
  8066. "#endif",
  8067. // diffuse
  8068. "float dotProduct = dot( normal, lVector );",
  8069. "#ifdef WRAP_AROUND",
  8070. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  8071. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8072. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  8073. "#else",
  8074. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  8075. "#endif",
  8076. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  8077. // specular
  8078. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  8079. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  8080. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  8081. "#ifdef PHYSICALLY_BASED_SHADING",
  8082. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8083. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8084. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  8085. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  8086. "#else",
  8087. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  8088. "#endif",
  8089. "}",
  8090. "#endif",
  8091. "#if MAX_SPOT_LIGHTS > 0",
  8092. "vec3 spotDiffuse = vec3( 0.0 );",
  8093. "vec3 spotSpecular = vec3( 0.0 );",
  8094. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8095. "#ifdef PHONG_PER_PIXEL",
  8096. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8097. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8098. "float lDistance = 1.0;",
  8099. "if ( spotLightDistance[ i ] > 0.0 )",
  8100. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8101. "lVector = normalize( lVector );",
  8102. "#else",
  8103. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  8104. "float lDistance = vSpotLight[ i ].w;",
  8105. "#endif",
  8106. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  8107. "if ( spotEffect > spotLightAngle[ i ] ) {",
  8108. "spotEffect = pow( spotEffect, spotLightExponent[ i ] );",
  8109. // diffuse
  8110. "float dotProduct = dot( normal, lVector );",
  8111. "#ifdef WRAP_AROUND",
  8112. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  8113. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8114. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  8115. "#else",
  8116. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  8117. "#endif",
  8118. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  8119. // specular
  8120. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  8121. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  8122. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  8123. "#ifdef PHYSICALLY_BASED_SHADING",
  8124. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8125. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8126. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  8127. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  8128. "#else",
  8129. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  8130. "#endif",
  8131. "}",
  8132. "}",
  8133. "#endif",
  8134. "#if MAX_DIR_LIGHTS > 0",
  8135. "vec3 dirDiffuse = vec3( 0.0 );",
  8136. "vec3 dirSpecular = vec3( 0.0 );" ,
  8137. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8138. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8139. "vec3 dirVector = normalize( lDirection.xyz );",
  8140. // diffuse
  8141. "float dotProduct = dot( normal, dirVector );",
  8142. "#ifdef WRAP_AROUND",
  8143. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  8144. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8145. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  8146. "#else",
  8147. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  8148. "#endif",
  8149. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  8150. // specular
  8151. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  8152. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  8153. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  8154. "#ifdef PHYSICALLY_BASED_SHADING",
  8155. /*
  8156. // fresnel term from skin shader
  8157. "const float F0 = 0.128;",
  8158. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  8159. "float exponential = pow( base, 5.0 );",
  8160. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  8161. */
  8162. /*
  8163. // fresnel term from fresnel shader
  8164. "const float mFresnelBias = 0.08;",
  8165. "const float mFresnelScale = 0.3;",
  8166. "const float mFresnelPower = 5.0;",
  8167. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  8168. */
  8169. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8170. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8171. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  8172. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  8173. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  8174. "#else",
  8175. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  8176. "#endif",
  8177. "}",
  8178. "#endif",
  8179. "#if MAX_HEMI_LIGHTS > 0",
  8180. "vec3 hemiDiffuse = vec3( 0.0 );",
  8181. "vec3 hemiSpecular = vec3( 0.0 );" ,
  8182. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  8183. "vec4 lPosition = viewMatrix * vec4( hemisphereLightPosition[ i ], 1.0 );",
  8184. "vec3 lVector = normalize( lPosition.xyz + vViewPosition.xyz );",
  8185. // diffuse
  8186. "float dotProduct = dot( normal, lVector );",
  8187. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  8188. "hemiDiffuse += diffuse * mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  8189. // specular (sky light)
  8190. "float hemiSpecularWeight = 0.0;",
  8191. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  8192. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  8193. "hemiSpecularWeight += specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  8194. // specular (ground light)
  8195. "vec3 lVectorGround = normalize( -lPosition.xyz + vViewPosition.xyz );",
  8196. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  8197. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  8198. "hemiSpecularWeight += specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  8199. "#ifdef PHYSICALLY_BASED_SHADING",
  8200. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8201. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8202. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  8203. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  8204. "hemiSpecular += ( schlickSky + schlickGround ) * mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight ) * hemiSpecularWeight * hemiDiffuseWeight * specularNormalization;",
  8205. "#else",
  8206. "hemiSpecular += specular * mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight ) * hemiSpecularWeight * hemiDiffuseWeight;",
  8207. "#endif",
  8208. "}",
  8209. "#endif",
  8210. "vec3 totalDiffuse = vec3( 0.0 );",
  8211. "vec3 totalSpecular = vec3( 0.0 );",
  8212. "#if MAX_DIR_LIGHTS > 0",
  8213. "totalDiffuse += dirDiffuse;",
  8214. "totalSpecular += dirSpecular;",
  8215. "#endif",
  8216. "#if MAX_HEMI_LIGHTS > 0",
  8217. "totalDiffuse += hemiDiffuse;",
  8218. "totalSpecular += hemiSpecular;",
  8219. "#endif",
  8220. "#if MAX_POINT_LIGHTS > 0",
  8221. "totalDiffuse += pointDiffuse;",
  8222. "totalSpecular += pointSpecular;",
  8223. "#endif",
  8224. "#if MAX_SPOT_LIGHTS > 0",
  8225. "totalDiffuse += spotDiffuse;",
  8226. "totalSpecular += spotSpecular;",
  8227. "#endif",
  8228. "#ifdef METAL",
  8229. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  8230. "#else",
  8231. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  8232. "#endif"
  8233. ].join("\n"),
  8234. // VERTEX COLORS
  8235. color_pars_fragment: [
  8236. "#ifdef USE_COLOR",
  8237. "varying vec3 vColor;",
  8238. "#endif"
  8239. ].join("\n"),
  8240. color_fragment: [
  8241. "#ifdef USE_COLOR",
  8242. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  8243. "#endif"
  8244. ].join("\n"),
  8245. color_pars_vertex: [
  8246. "#ifdef USE_COLOR",
  8247. "varying vec3 vColor;",
  8248. "#endif"
  8249. ].join("\n"),
  8250. color_vertex: [
  8251. "#ifdef USE_COLOR",
  8252. "#ifdef GAMMA_INPUT",
  8253. "vColor = color * color;",
  8254. "#else",
  8255. "vColor = color;",
  8256. "#endif",
  8257. "#endif"
  8258. ].join("\n"),
  8259. // SKINNING
  8260. skinning_pars_vertex: [
  8261. "#ifdef USE_SKINNING",
  8262. "#ifdef BONE_TEXTURE",
  8263. "uniform sampler2D boneTexture;",
  8264. "mat4 getBoneMatrix( const in float i ) {",
  8265. "float j = i * 4.0;",
  8266. "float x = mod( j, N_BONE_PIXEL_X );",
  8267. "float y = floor( j / N_BONE_PIXEL_X );",
  8268. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  8269. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  8270. "y = dy * ( y + 0.5 );",
  8271. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  8272. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  8273. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  8274. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  8275. "mat4 bone = mat4( v1, v2, v3, v4 );",
  8276. "return bone;",
  8277. "}",
  8278. "#else",
  8279. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  8280. "mat4 getBoneMatrix( const in float i ) {",
  8281. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  8282. "return bone;",
  8283. "}",
  8284. "#endif",
  8285. "#endif"
  8286. ].join("\n"),
  8287. skinbase_vertex: [
  8288. "#ifdef USE_SKINNING",
  8289. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  8290. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  8291. "#endif"
  8292. ].join("\n"),
  8293. skinning_vertex: [
  8294. "#ifdef USE_SKINNING",
  8295. "#ifdef USE_MORPHTARGETS",
  8296. "vec4 skinVertex = vec4( morphed, 1.0 );",
  8297. "#else",
  8298. "vec4 skinVertex = vec4( position, 1.0 );",
  8299. "#endif",
  8300. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  8301. "skinned += boneMatY * skinVertex * skinWeight.y;",
  8302. "#endif"
  8303. ].join("\n"),
  8304. // MORPHING
  8305. morphtarget_pars_vertex: [
  8306. "#ifdef USE_MORPHTARGETS",
  8307. "#ifndef USE_MORPHNORMALS",
  8308. "uniform float morphTargetInfluences[ 8 ];",
  8309. "#else",
  8310. "uniform float morphTargetInfluences[ 4 ];",
  8311. "#endif",
  8312. "#endif"
  8313. ].join("\n"),
  8314. morphtarget_vertex: [
  8315. "#ifdef USE_MORPHTARGETS",
  8316. "vec3 morphed = vec3( 0.0 );",
  8317. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  8318. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  8319. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  8320. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  8321. "#ifndef USE_MORPHNORMALS",
  8322. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  8323. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  8324. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  8325. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  8326. "#endif",
  8327. "morphed += position;",
  8328. "#endif"
  8329. ].join("\n"),
  8330. default_vertex : [
  8331. "vec4 mvPosition;",
  8332. "#ifdef USE_SKINNING",
  8333. "mvPosition = modelViewMatrix * skinned;",
  8334. "#endif",
  8335. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  8336. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  8337. "#endif",
  8338. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  8339. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8340. "#endif",
  8341. "gl_Position = projectionMatrix * mvPosition;",
  8342. ].join("\n"),
  8343. morphnormal_vertex: [
  8344. "#ifdef USE_MORPHNORMALS",
  8345. "vec3 morphedNormal = vec3( 0.0 );",
  8346. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  8347. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  8348. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  8349. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  8350. "morphedNormal += normal;",
  8351. "#endif"
  8352. ].join("\n"),
  8353. skinnormal_vertex: [
  8354. "#ifdef USE_SKINNING",
  8355. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  8356. "skinMatrix += skinWeight.y * boneMatY;",
  8357. "#ifdef USE_MORPHNORMALS",
  8358. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  8359. "#else",
  8360. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  8361. "#endif",
  8362. "#endif"
  8363. ].join("\n"),
  8364. defaultnormal_vertex: [
  8365. "vec3 objectNormal;",
  8366. "#ifdef USE_SKINNING",
  8367. "objectNormal = skinnedNormal.xyz;",
  8368. "#endif",
  8369. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  8370. "objectNormal = morphedNormal;",
  8371. "#endif",
  8372. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  8373. "objectNormal = normal;",
  8374. "#endif",
  8375. "vec3 transformedNormal = normalMatrix * objectNormal;",
  8376. ].join("\n"),
  8377. // SHADOW MAP
  8378. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  8379. // http://spidergl.org/example.php?id=6
  8380. // http://fabiensanglard.net/shadowmapping
  8381. shadowmap_pars_fragment: [
  8382. "#ifdef USE_SHADOWMAP",
  8383. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  8384. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  8385. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  8386. "uniform float shadowBias[ MAX_SHADOWS ];",
  8387. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8388. "float unpackDepth( const in vec4 rgba_depth ) {",
  8389. "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 );",
  8390. "float depth = dot( rgba_depth, bit_shift );",
  8391. "return depth;",
  8392. "}",
  8393. "#endif"
  8394. ].join("\n"),
  8395. shadowmap_fragment: [
  8396. "#ifdef USE_SHADOWMAP",
  8397. "#ifdef SHADOWMAP_DEBUG",
  8398. "vec3 frustumColors[3];",
  8399. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  8400. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  8401. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  8402. "#endif",
  8403. "#ifdef SHADOWMAP_CASCADE",
  8404. "int inFrustumCount = 0;",
  8405. "#endif",
  8406. "float fDepth;",
  8407. "vec3 shadowColor = vec3( 1.0 );",
  8408. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8409. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  8410. // "if ( something && something )" breaks ATI OpenGL shader compiler
  8411. // "if ( all( something, something ) )" using this instead
  8412. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  8413. "bool inFrustum = all( inFrustumVec );",
  8414. // don't shadow pixels outside of light frustum
  8415. // use just first frustum (for cascades)
  8416. // don't shadow pixels behind far plane of light frustum
  8417. "#ifdef SHADOWMAP_CASCADE",
  8418. "inFrustumCount += int( inFrustum );",
  8419. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  8420. "#else",
  8421. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  8422. "#endif",
  8423. "bool frustumTest = all( frustumTestVec );",
  8424. "if ( frustumTest ) {",
  8425. "shadowCoord.z += shadowBias[ i ];",
  8426. "#ifdef SHADOWMAP_SOFT",
  8427. // Percentage-close filtering
  8428. // (9 pixel kernel)
  8429. // http://fabiensanglard.net/shadowmappingPCF/
  8430. "float shadow = 0.0;",
  8431. /*
  8432. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  8433. // must enroll loop manually
  8434. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  8435. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  8436. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  8437. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  8438. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  8439. "float fDepth = unpackDepth( rgbaDepth );",
  8440. "if ( fDepth < shadowCoord.z )",
  8441. "shadow += 1.0;",
  8442. "}",
  8443. "shadow /= 9.0;",
  8444. */
  8445. "const float shadowDelta = 1.0 / 9.0;",
  8446. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  8447. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  8448. "float dx0 = -1.25 * xPixelOffset;",
  8449. "float dy0 = -1.25 * yPixelOffset;",
  8450. "float dx1 = 1.25 * xPixelOffset;",
  8451. "float dy1 = 1.25 * yPixelOffset;",
  8452. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  8453. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8454. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  8455. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8456. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  8457. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8458. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  8459. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8460. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  8461. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8462. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  8463. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8464. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  8465. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8466. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  8467. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8468. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  8469. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8470. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  8471. "#else",
  8472. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  8473. "float fDepth = unpackDepth( rgbaDepth );",
  8474. "if ( fDepth < shadowCoord.z )",
  8475. // spot with multiple shadows is darker
  8476. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  8477. // spot with multiple shadows has the same color as single shadow spot
  8478. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  8479. "#endif",
  8480. "}",
  8481. "#ifdef SHADOWMAP_DEBUG",
  8482. "#ifdef SHADOWMAP_CASCADE",
  8483. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  8484. "#else",
  8485. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  8486. "#endif",
  8487. "#endif",
  8488. "}",
  8489. "#ifdef GAMMA_OUTPUT",
  8490. "shadowColor *= shadowColor;",
  8491. "#endif",
  8492. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  8493. "#endif"
  8494. ].join("\n"),
  8495. shadowmap_pars_vertex: [
  8496. "#ifdef USE_SHADOWMAP",
  8497. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8498. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  8499. "#endif"
  8500. ].join("\n"),
  8501. shadowmap_vertex: [
  8502. "#ifdef USE_SHADOWMAP",
  8503. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8504. "vShadowCoord[ i ] = shadowMatrix[ i ] * mPosition;",
  8505. "}",
  8506. "#endif"
  8507. ].join("\n"),
  8508. // ALPHATEST
  8509. alphatest_fragment: [
  8510. "#ifdef ALPHATEST",
  8511. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  8512. "#endif"
  8513. ].join("\n"),
  8514. // LINEAR SPACE
  8515. linear_to_gamma_fragment: [
  8516. "#ifdef GAMMA_OUTPUT",
  8517. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  8518. "#endif"
  8519. ].join("\n"),
  8520. };
  8521. THREE.UniformsUtils = {
  8522. merge: function ( uniforms ) {
  8523. var u, p, tmp, merged = {};
  8524. for ( u = 0; u < uniforms.length; u ++ ) {
  8525. tmp = this.clone( uniforms[ u ] );
  8526. for ( p in tmp ) {
  8527. merged[ p ] = tmp[ p ];
  8528. }
  8529. }
  8530. return merged;
  8531. },
  8532. clone: function ( uniforms_src ) {
  8533. var u, p, parameter, parameter_src, uniforms_dst = {};
  8534. for ( u in uniforms_src ) {
  8535. uniforms_dst[ u ] = {};
  8536. for ( p in uniforms_src[ u ] ) {
  8537. parameter_src = uniforms_src[ u ][ p ];
  8538. if ( parameter_src instanceof THREE.Color ||
  8539. parameter_src instanceof THREE.Vector2 ||
  8540. parameter_src instanceof THREE.Vector3 ||
  8541. parameter_src instanceof THREE.Vector4 ||
  8542. parameter_src instanceof THREE.Matrix4 ||
  8543. parameter_src instanceof THREE.Texture ) {
  8544. uniforms_dst[ u ][ p ] = parameter_src.clone();
  8545. } else if ( parameter_src instanceof Array ) {
  8546. uniforms_dst[ u ][ p ] = parameter_src.slice();
  8547. } else {
  8548. uniforms_dst[ u ][ p ] = parameter_src;
  8549. }
  8550. }
  8551. }
  8552. return uniforms_dst;
  8553. }
  8554. };
  8555. THREE.UniformsLib = {
  8556. common: {
  8557. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  8558. "opacity" : { type: "f", value: 1.0 },
  8559. "map" : { type: "t", value: null },
  8560. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  8561. "lightMap" : { type: "t", value: null },
  8562. "specularMap" : { type: "t", value: null },
  8563. "envMap" : { type: "t", value: null },
  8564. "flipEnvMap" : { type: "f", value: -1 },
  8565. "useRefract" : { type: "i", value: 0 },
  8566. "reflectivity" : { type: "f", value: 1.0 },
  8567. "refractionRatio" : { type: "f", value: 0.98 },
  8568. "combine" : { type: "i", value: 0 },
  8569. "morphTargetInfluences" : { type: "f", value: 0 }
  8570. },
  8571. bump: {
  8572. "bumpMap" : { type: "t", value: null },
  8573. "bumpScale" : { type: "f", value: 1 }
  8574. },
  8575. fog : {
  8576. "fogDensity" : { type: "f", value: 0.00025 },
  8577. "fogNear" : { type: "f", value: 1 },
  8578. "fogFar" : { type: "f", value: 2000 },
  8579. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  8580. },
  8581. lights: {
  8582. "ambientLightColor" : { type: "fv", value: [] },
  8583. "directionalLightDirection" : { type: "fv", value: [] },
  8584. "directionalLightColor" : { type: "fv", value: [] },
  8585. "hemisphereLightPosition" : { type: "fv", value: [] },
  8586. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  8587. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  8588. "pointLightColor" : { type: "fv", value: [] },
  8589. "pointLightPosition" : { type: "fv", value: [] },
  8590. "pointLightDistance" : { type: "fv1", value: [] },
  8591. "spotLightColor" : { type: "fv", value: [] },
  8592. "spotLightPosition" : { type: "fv", value: [] },
  8593. "spotLightDirection" : { type: "fv", value: [] },
  8594. "spotLightDistance" : { type: "fv1", value: [] },
  8595. "spotLightAngle" : { type: "fv1", value: [] },
  8596. "spotLightExponent" : { type: "fv1", value: [] }
  8597. },
  8598. particle: {
  8599. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  8600. "opacity" : { type: "f", value: 1.0 },
  8601. "size" : { type: "f", value: 1.0 },
  8602. "scale" : { type: "f", value: 1.0 },
  8603. "map" : { type: "t", value: null },
  8604. "fogDensity" : { type: "f", value: 0.00025 },
  8605. "fogNear" : { type: "f", value: 1 },
  8606. "fogFar" : { type: "f", value: 2000 },
  8607. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  8608. },
  8609. shadowmap: {
  8610. "shadowMap": { type: "tv", value: [] },
  8611. "shadowMapSize": { type: "v2v", value: [] },
  8612. "shadowBias" : { type: "fv1", value: [] },
  8613. "shadowDarkness": { type: "fv1", value: [] },
  8614. "shadowMatrix" : { type: "m4v", value: [] },
  8615. }
  8616. };
  8617. THREE.ShaderLib = {
  8618. 'depth': {
  8619. uniforms: {
  8620. "mNear": { type: "f", value: 1.0 },
  8621. "mFar" : { type: "f", value: 2000.0 },
  8622. "opacity" : { type: "f", value: 1.0 }
  8623. },
  8624. vertexShader: [
  8625. "void main() {",
  8626. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  8627. "}"
  8628. ].join("\n"),
  8629. fragmentShader: [
  8630. "uniform float mNear;",
  8631. "uniform float mFar;",
  8632. "uniform float opacity;",
  8633. "void main() {",
  8634. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  8635. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  8636. "gl_FragColor = vec4( vec3( color ), opacity );",
  8637. "}"
  8638. ].join("\n")
  8639. },
  8640. 'normal': {
  8641. uniforms: {
  8642. "opacity" : { type: "f", value: 1.0 }
  8643. },
  8644. vertexShader: [
  8645. "varying vec3 vNormal;",
  8646. "void main() {",
  8647. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8648. "vNormal = normalMatrix * normal;",
  8649. "gl_Position = projectionMatrix * mvPosition;",
  8650. "}"
  8651. ].join("\n"),
  8652. fragmentShader: [
  8653. "uniform float opacity;",
  8654. "varying vec3 vNormal;",
  8655. "void main() {",
  8656. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  8657. "}"
  8658. ].join("\n")
  8659. },
  8660. 'basic': {
  8661. uniforms: THREE.UniformsUtils.merge( [
  8662. THREE.UniformsLib[ "common" ],
  8663. THREE.UniformsLib[ "fog" ],
  8664. THREE.UniformsLib[ "shadowmap" ]
  8665. ] ),
  8666. vertexShader: [
  8667. THREE.ShaderChunk[ "map_pars_vertex" ],
  8668. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  8669. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  8670. THREE.ShaderChunk[ "color_pars_vertex" ],
  8671. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  8672. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  8673. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  8674. "void main() {",
  8675. THREE.ShaderChunk[ "map_vertex" ],
  8676. THREE.ShaderChunk[ "lightmap_vertex" ],
  8677. THREE.ShaderChunk[ "color_vertex" ],
  8678. "#ifdef USE_ENVMAP",
  8679. THREE.ShaderChunk[ "morphnormal_vertex" ],
  8680. THREE.ShaderChunk[ "skinbase_vertex" ],
  8681. THREE.ShaderChunk[ "skinnormal_vertex" ],
  8682. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  8683. "#endif",
  8684. THREE.ShaderChunk[ "morphtarget_vertex" ],
  8685. THREE.ShaderChunk[ "skinning_vertex" ],
  8686. THREE.ShaderChunk[ "default_vertex" ],
  8687. THREE.ShaderChunk[ "worldpos_vertex" ],
  8688. THREE.ShaderChunk[ "envmap_vertex" ],
  8689. THREE.ShaderChunk[ "shadowmap_vertex" ],
  8690. "}"
  8691. ].join("\n"),
  8692. fragmentShader: [
  8693. "uniform vec3 diffuse;",
  8694. "uniform float opacity;",
  8695. THREE.ShaderChunk[ "color_pars_fragment" ],
  8696. THREE.ShaderChunk[ "map_pars_fragment" ],
  8697. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  8698. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  8699. THREE.ShaderChunk[ "fog_pars_fragment" ],
  8700. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  8701. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  8702. "void main() {",
  8703. "gl_FragColor = vec4( diffuse, opacity );",
  8704. THREE.ShaderChunk[ "map_fragment" ],
  8705. THREE.ShaderChunk[ "alphatest_fragment" ],
  8706. THREE.ShaderChunk[ "specularmap_fragment" ],
  8707. THREE.ShaderChunk[ "lightmap_fragment" ],
  8708. THREE.ShaderChunk[ "color_fragment" ],
  8709. THREE.ShaderChunk[ "envmap_fragment" ],
  8710. THREE.ShaderChunk[ "shadowmap_fragment" ],
  8711. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  8712. THREE.ShaderChunk[ "fog_fragment" ],
  8713. "}"
  8714. ].join("\n")
  8715. },
  8716. 'lambert': {
  8717. uniforms: THREE.UniformsUtils.merge( [
  8718. THREE.UniformsLib[ "common" ],
  8719. THREE.UniformsLib[ "fog" ],
  8720. THREE.UniformsLib[ "lights" ],
  8721. THREE.UniformsLib[ "shadowmap" ],
  8722. {
  8723. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  8724. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  8725. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  8726. }
  8727. ] ),
  8728. vertexShader: [
  8729. "#define LAMBERT",
  8730. "varying vec3 vLightFront;",
  8731. "#ifdef DOUBLE_SIDED",
  8732. "varying vec3 vLightBack;",
  8733. "#endif",
  8734. THREE.ShaderChunk[ "map_pars_vertex" ],
  8735. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  8736. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  8737. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  8738. THREE.ShaderChunk[ "color_pars_vertex" ],
  8739. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  8740. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  8741. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  8742. "void main() {",
  8743. THREE.ShaderChunk[ "map_vertex" ],
  8744. THREE.ShaderChunk[ "lightmap_vertex" ],
  8745. THREE.ShaderChunk[ "color_vertex" ],
  8746. THREE.ShaderChunk[ "morphnormal_vertex" ],
  8747. THREE.ShaderChunk[ "skinbase_vertex" ],
  8748. THREE.ShaderChunk[ "skinnormal_vertex" ],
  8749. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  8750. THREE.ShaderChunk[ "morphtarget_vertex" ],
  8751. THREE.ShaderChunk[ "skinning_vertex" ],
  8752. THREE.ShaderChunk[ "default_vertex" ],
  8753. THREE.ShaderChunk[ "worldpos_vertex" ],
  8754. THREE.ShaderChunk[ "envmap_vertex" ],
  8755. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  8756. THREE.ShaderChunk[ "shadowmap_vertex" ],
  8757. "}"
  8758. ].join("\n"),
  8759. fragmentShader: [
  8760. "uniform float opacity;",
  8761. "varying vec3 vLightFront;",
  8762. "#ifdef DOUBLE_SIDED",
  8763. "varying vec3 vLightBack;",
  8764. "#endif",
  8765. THREE.ShaderChunk[ "color_pars_fragment" ],
  8766. THREE.ShaderChunk[ "map_pars_fragment" ],
  8767. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  8768. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  8769. THREE.ShaderChunk[ "fog_pars_fragment" ],
  8770. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  8771. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  8772. "void main() {",
  8773. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  8774. THREE.ShaderChunk[ "map_fragment" ],
  8775. THREE.ShaderChunk[ "alphatest_fragment" ],
  8776. THREE.ShaderChunk[ "specularmap_fragment" ],
  8777. "#ifdef DOUBLE_SIDED",
  8778. //"float isFront = float( gl_FrontFacing );",
  8779. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  8780. "if ( gl_FrontFacing )",
  8781. "gl_FragColor.xyz *= vLightFront;",
  8782. "else",
  8783. "gl_FragColor.xyz *= vLightBack;",
  8784. "#else",
  8785. "gl_FragColor.xyz *= vLightFront;",
  8786. "#endif",
  8787. THREE.ShaderChunk[ "lightmap_fragment" ],
  8788. THREE.ShaderChunk[ "color_fragment" ],
  8789. THREE.ShaderChunk[ "envmap_fragment" ],
  8790. THREE.ShaderChunk[ "shadowmap_fragment" ],
  8791. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  8792. THREE.ShaderChunk[ "fog_fragment" ],
  8793. "}"
  8794. ].join("\n")
  8795. },
  8796. 'phong': {
  8797. uniforms: THREE.UniformsUtils.merge( [
  8798. THREE.UniformsLib[ "common" ],
  8799. THREE.UniformsLib[ "bump" ],
  8800. THREE.UniformsLib[ "fog" ],
  8801. THREE.UniformsLib[ "lights" ],
  8802. THREE.UniformsLib[ "shadowmap" ],
  8803. {
  8804. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  8805. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  8806. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  8807. "shininess": { type: "f", value: 30 },
  8808. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  8809. }
  8810. ] ),
  8811. vertexShader: [
  8812. "#define PHONG",
  8813. "varying vec3 vViewPosition;",
  8814. "varying vec3 vNormal;",
  8815. THREE.ShaderChunk[ "map_pars_vertex" ],
  8816. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  8817. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  8818. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  8819. THREE.ShaderChunk[ "color_pars_vertex" ],
  8820. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  8821. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  8822. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  8823. "void main() {",
  8824. THREE.ShaderChunk[ "map_vertex" ],
  8825. THREE.ShaderChunk[ "lightmap_vertex" ],
  8826. THREE.ShaderChunk[ "color_vertex" ],
  8827. THREE.ShaderChunk[ "morphnormal_vertex" ],
  8828. THREE.ShaderChunk[ "skinbase_vertex" ],
  8829. THREE.ShaderChunk[ "skinnormal_vertex" ],
  8830. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  8831. "vNormal = transformedNormal;",
  8832. THREE.ShaderChunk[ "morphtarget_vertex" ],
  8833. THREE.ShaderChunk[ "skinning_vertex" ],
  8834. THREE.ShaderChunk[ "default_vertex" ],
  8835. "vViewPosition = -mvPosition.xyz;",
  8836. THREE.ShaderChunk[ "worldpos_vertex" ],
  8837. THREE.ShaderChunk[ "envmap_vertex" ],
  8838. THREE.ShaderChunk[ "lights_phong_vertex" ],
  8839. THREE.ShaderChunk[ "shadowmap_vertex" ],
  8840. "}"
  8841. ].join("\n"),
  8842. fragmentShader: [
  8843. "uniform vec3 diffuse;",
  8844. "uniform float opacity;",
  8845. "uniform vec3 ambient;",
  8846. "uniform vec3 emissive;",
  8847. "uniform vec3 specular;",
  8848. "uniform float shininess;",
  8849. THREE.ShaderChunk[ "color_pars_fragment" ],
  8850. THREE.ShaderChunk[ "map_pars_fragment" ],
  8851. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  8852. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  8853. THREE.ShaderChunk[ "fog_pars_fragment" ],
  8854. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  8855. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  8856. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  8857. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  8858. "void main() {",
  8859. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  8860. THREE.ShaderChunk[ "map_fragment" ],
  8861. THREE.ShaderChunk[ "alphatest_fragment" ],
  8862. THREE.ShaderChunk[ "specularmap_fragment" ],
  8863. THREE.ShaderChunk[ "lights_phong_fragment" ],
  8864. THREE.ShaderChunk[ "lightmap_fragment" ],
  8865. THREE.ShaderChunk[ "color_fragment" ],
  8866. THREE.ShaderChunk[ "envmap_fragment" ],
  8867. THREE.ShaderChunk[ "shadowmap_fragment" ],
  8868. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  8869. THREE.ShaderChunk[ "fog_fragment" ],
  8870. "}"
  8871. ].join("\n")
  8872. },
  8873. 'particle_basic': {
  8874. uniforms: THREE.UniformsUtils.merge( [
  8875. THREE.UniformsLib[ "particle" ],
  8876. THREE.UniformsLib[ "shadowmap" ]
  8877. ] ),
  8878. vertexShader: [
  8879. "uniform float size;",
  8880. "uniform float scale;",
  8881. THREE.ShaderChunk[ "color_pars_vertex" ],
  8882. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  8883. "void main() {",
  8884. THREE.ShaderChunk[ "color_vertex" ],
  8885. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8886. "#ifdef USE_SIZEATTENUATION",
  8887. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  8888. "#else",
  8889. "gl_PointSize = size;",
  8890. "#endif",
  8891. "gl_Position = projectionMatrix * mvPosition;",
  8892. THREE.ShaderChunk[ "worldpos_vertex" ],
  8893. THREE.ShaderChunk[ "shadowmap_vertex" ],
  8894. "}"
  8895. ].join("\n"),
  8896. fragmentShader: [
  8897. "uniform vec3 psColor;",
  8898. "uniform float opacity;",
  8899. THREE.ShaderChunk[ "color_pars_fragment" ],
  8900. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  8901. THREE.ShaderChunk[ "fog_pars_fragment" ],
  8902. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  8903. "void main() {",
  8904. "gl_FragColor = vec4( psColor, opacity );",
  8905. THREE.ShaderChunk[ "map_particle_fragment" ],
  8906. THREE.ShaderChunk[ "alphatest_fragment" ],
  8907. THREE.ShaderChunk[ "color_fragment" ],
  8908. THREE.ShaderChunk[ "shadowmap_fragment" ],
  8909. THREE.ShaderChunk[ "fog_fragment" ],
  8910. "}"
  8911. ].join("\n")
  8912. },
  8913. // Depth encoding into RGBA texture
  8914. // based on SpiderGL shadow map example
  8915. // http://spidergl.org/example.php?id=6
  8916. // originally from
  8917. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  8918. // see also here:
  8919. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  8920. 'depthRGBA': {
  8921. uniforms: {},
  8922. vertexShader: [
  8923. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  8924. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  8925. "void main() {",
  8926. THREE.ShaderChunk[ "skinbase_vertex" ],
  8927. THREE.ShaderChunk[ "morphtarget_vertex" ],
  8928. THREE.ShaderChunk[ "skinning_vertex" ],
  8929. THREE.ShaderChunk[ "default_vertex" ],
  8930. "}"
  8931. ].join("\n"),
  8932. fragmentShader: [
  8933. "vec4 pack_depth( const in float depth ) {",
  8934. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  8935. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  8936. "vec4 res = fract( depth * bit_shift );",
  8937. "res -= res.xxyz * bit_mask;",
  8938. "return res;",
  8939. "}",
  8940. "void main() {",
  8941. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  8942. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  8943. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  8944. //"gl_FragData[ 0 ] = pack_depth( z );",
  8945. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  8946. "}"
  8947. ].join("\n")
  8948. }
  8949. };
  8950. /**
  8951. * @author supereggbert / http://www.paulbrunt.co.uk/
  8952. * @author mrdoob / http://mrdoob.com/
  8953. * @author alteredq / http://alteredqualia.com/
  8954. * @author szimek / https://github.com/szimek/
  8955. */
  8956. THREE.WebGLRenderer = function ( parameters ) {
  8957. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  8958. parameters = parameters || {};
  8959. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  8960. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  8961. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  8962. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  8963. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  8964. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  8965. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  8966. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  8967. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0,
  8968. _maxLights = parameters.maxLights !== undefined ? parameters.maxLights : 4;
  8969. // public properties
  8970. this.domElement = _canvas;
  8971. this.context = null;
  8972. // clearing
  8973. this.autoClear = true;
  8974. this.autoClearColor = true;
  8975. this.autoClearDepth = true;
  8976. this.autoClearStencil = true;
  8977. // scene graph
  8978. this.sortObjects = true;
  8979. this.autoUpdateObjects = true;
  8980. this.autoUpdateScene = true;
  8981. // physically based shading
  8982. this.gammaInput = false;
  8983. this.gammaOutput = false;
  8984. this.physicallyBasedShading = false;
  8985. // shadow map
  8986. this.shadowMapEnabled = false;
  8987. this.shadowMapAutoUpdate = true;
  8988. this.shadowMapSoft = true;
  8989. this.shadowMapCullFrontFaces = true;
  8990. this.shadowMapDebug = false;
  8991. this.shadowMapCascade = false;
  8992. // morphs
  8993. this.maxMorphTargets = 8;
  8994. this.maxMorphNormals = 4;
  8995. // flags
  8996. this.autoScaleCubemaps = true;
  8997. // custom render plugins
  8998. this.renderPluginsPre = [];
  8999. this.renderPluginsPost = [];
  9000. // info
  9001. this.info = {
  9002. memory: {
  9003. programs: 0,
  9004. geometries: 0,
  9005. textures: 0
  9006. },
  9007. render: {
  9008. calls: 0,
  9009. vertices: 0,
  9010. faces: 0,
  9011. points: 0
  9012. }
  9013. };
  9014. // internal properties
  9015. var _this = this,
  9016. _programs = [],
  9017. _programs_counter = 0,
  9018. // internal state cache
  9019. _currentProgram = null,
  9020. _currentFramebuffer = null,
  9021. _currentMaterialId = -1,
  9022. _currentGeometryGroupHash = null,
  9023. _currentCamera = null,
  9024. _geometryGroupCounter = 0,
  9025. _usedTextureUnits = 0,
  9026. // GL state cache
  9027. _oldDoubleSided = -1,
  9028. _oldFlipSided = -1,
  9029. _oldBlending = -1,
  9030. _oldBlendEquation = -1,
  9031. _oldBlendSrc = -1,
  9032. _oldBlendDst = -1,
  9033. _oldDepthTest = -1,
  9034. _oldDepthWrite = -1,
  9035. _oldPolygonOffset = null,
  9036. _oldPolygonOffsetFactor = null,
  9037. _oldPolygonOffsetUnits = null,
  9038. _oldLineWidth = null,
  9039. _viewportX = 0,
  9040. _viewportY = 0,
  9041. _viewportWidth = 0,
  9042. _viewportHeight = 0,
  9043. _currentWidth = 0,
  9044. _currentHeight = 0,
  9045. // frustum
  9046. _frustum = new THREE.Frustum(),
  9047. // camera matrices cache
  9048. _projScreenMatrix = new THREE.Matrix4(),
  9049. _projScreenMatrixPS = new THREE.Matrix4(),
  9050. _vector3 = new THREE.Vector4(),
  9051. // light arrays cache
  9052. _direction = new THREE.Vector3(),
  9053. _lightsNeedUpdate = true,
  9054. _lights = {
  9055. ambient: [ 0, 0, 0 ],
  9056. directional: { length: 0, colors: new Array(), positions: new Array() },
  9057. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  9058. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), angles: new Array(), exponents: new Array() },
  9059. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  9060. };
  9061. // initialize
  9062. var _gl;
  9063. var _glExtensionTextureFloat;
  9064. var _glExtensionStandardDerivatives;
  9065. var _glExtensionTextureFilterAnisotropic;
  9066. initGL();
  9067. setDefaultGLState();
  9068. this.context = _gl;
  9069. // GPU capabilities
  9070. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  9071. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9072. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  9073. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9074. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  9075. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  9076. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  9077. // API
  9078. this.getContext = function () {
  9079. return _gl;
  9080. };
  9081. this.supportsVertexTextures = function () {
  9082. return _supportsVertexTextures;
  9083. };
  9084. this.getMaxAnisotropy = function () {
  9085. return _maxAnisotropy;
  9086. };
  9087. this.setSize = function ( width, height ) {
  9088. _canvas.width = width;
  9089. _canvas.height = height;
  9090. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  9091. };
  9092. this.setViewport = function ( x, y, width, height ) {
  9093. _viewportX = x !== undefined ? x : 0;
  9094. _viewportY = y !== undefined ? y : 0;
  9095. _viewportWidth = width !== undefined ? width : _canvas.width;
  9096. _viewportHeight = height !== undefined ? height : _canvas.height;
  9097. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  9098. };
  9099. this.setScissor = function ( x, y, width, height ) {
  9100. _gl.scissor( x, y, width, height );
  9101. };
  9102. this.enableScissorTest = function ( enable ) {
  9103. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  9104. };
  9105. // Clearing
  9106. this.setClearColorHex = function ( hex, alpha ) {
  9107. _clearColor.setHex( hex );
  9108. _clearAlpha = alpha;
  9109. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9110. };
  9111. this.setClearColor = function ( color, alpha ) {
  9112. _clearColor.copy( color );
  9113. _clearAlpha = alpha;
  9114. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9115. };
  9116. this.getClearColor = function () {
  9117. return _clearColor;
  9118. };
  9119. this.getClearAlpha = function () {
  9120. return _clearAlpha;
  9121. };
  9122. this.clear = function ( color, depth, stencil ) {
  9123. var bits = 0;
  9124. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  9125. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  9126. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  9127. _gl.clear( bits );
  9128. };
  9129. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  9130. this.setRenderTarget( renderTarget );
  9131. this.clear( color, depth, stencil );
  9132. };
  9133. // Plugins
  9134. this.addPostPlugin = function ( plugin ) {
  9135. plugin.init( this );
  9136. this.renderPluginsPost.push( plugin );
  9137. };
  9138. this.addPrePlugin = function ( plugin ) {
  9139. plugin.init( this );
  9140. this.renderPluginsPre.push( plugin );
  9141. };
  9142. // Deallocation
  9143. this.deallocateObject = function ( object ) {
  9144. if ( ! object.__webglInit ) return;
  9145. object.__webglInit = false;
  9146. delete object._modelViewMatrix;
  9147. delete object._normalMatrix;
  9148. delete object._normalMatrixArray;
  9149. delete object._modelViewMatrixArray;
  9150. delete object._modelMatrixArray;
  9151. if ( object instanceof THREE.Mesh ) {
  9152. for ( var g in object.geometry.geometryGroups ) {
  9153. deleteMeshBuffers( object.geometry.geometryGroups[ g ] );
  9154. }
  9155. } else if ( object instanceof THREE.Ribbon ) {
  9156. deleteRibbonBuffers( object.geometry );
  9157. } else if ( object instanceof THREE.Line ) {
  9158. deleteLineBuffers( object.geometry );
  9159. } else if ( object instanceof THREE.ParticleSystem ) {
  9160. deleteParticleBuffers( object.geometry );
  9161. }
  9162. };
  9163. this.deallocateTexture = function ( texture ) {
  9164. if ( ! texture.__webglInit ) return;
  9165. texture.__webglInit = false;
  9166. _gl.deleteTexture( texture.__webglTexture );
  9167. _this.info.memory.textures --;
  9168. };
  9169. this.deallocateRenderTarget = function ( renderTarget ) {
  9170. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  9171. _gl.deleteTexture( renderTarget.__webglTexture );
  9172. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  9173. for ( var i = 0; i < 6; i ++ ) {
  9174. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  9175. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  9176. }
  9177. } else {
  9178. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  9179. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  9180. }
  9181. };
  9182. this.deallocateMaterial = function ( material ) {
  9183. var program = material.program;
  9184. if ( ! program ) return;
  9185. material.program = undefined;
  9186. // only deallocate GL program if this was the last use of shared program
  9187. // assumed there is only single copy of any program in the _programs list
  9188. // (that's how it's constructed)
  9189. var i, il, programInfo;
  9190. var deleteProgram = false;
  9191. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9192. programInfo = _programs[ i ];
  9193. if ( programInfo.program === program ) {
  9194. programInfo.usedTimes --;
  9195. if ( programInfo.usedTimes === 0 ) {
  9196. deleteProgram = true;
  9197. }
  9198. break;
  9199. }
  9200. }
  9201. if ( deleteProgram ) {
  9202. // avoid using array.splice, this is costlier than creating new array from scratch
  9203. var newPrograms = [];
  9204. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9205. programInfo = _programs[ i ];
  9206. if ( programInfo.program !== program ) {
  9207. newPrograms.push( programInfo );
  9208. }
  9209. }
  9210. _programs = newPrograms;
  9211. _gl.deleteProgram( program );
  9212. _this.info.memory.programs --;
  9213. }
  9214. };
  9215. // Rendering
  9216. this.updateShadowMap = function ( scene, camera ) {
  9217. _currentProgram = null;
  9218. _oldBlending = -1;
  9219. _oldDepthTest = -1;
  9220. _oldDepthWrite = -1;
  9221. _currentGeometryGroupHash = -1;
  9222. _currentMaterialId = -1;
  9223. _lightsNeedUpdate = true;
  9224. _oldDoubleSided = -1;
  9225. _oldFlipSided = -1;
  9226. this.shadowMapPlugin.update( scene, camera );
  9227. };
  9228. // Internal functions
  9229. // Buffer allocation
  9230. function createParticleBuffers ( geometry ) {
  9231. geometry.__webglVertexBuffer = _gl.createBuffer();
  9232. geometry.__webglColorBuffer = _gl.createBuffer();
  9233. _this.info.geometries ++;
  9234. };
  9235. function createLineBuffers ( geometry ) {
  9236. geometry.__webglVertexBuffer = _gl.createBuffer();
  9237. geometry.__webglColorBuffer = _gl.createBuffer();
  9238. _this.info.memory.geometries ++;
  9239. };
  9240. function createRibbonBuffers ( geometry ) {
  9241. geometry.__webglVertexBuffer = _gl.createBuffer();
  9242. geometry.__webglColorBuffer = _gl.createBuffer();
  9243. _this.info.memory.geometries ++;
  9244. };
  9245. function createMeshBuffers ( geometryGroup ) {
  9246. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  9247. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  9248. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  9249. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  9250. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  9251. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  9252. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  9253. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  9254. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  9255. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  9256. var m, ml;
  9257. if ( geometryGroup.numMorphTargets ) {
  9258. geometryGroup.__webglMorphTargetsBuffers = [];
  9259. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9260. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  9261. }
  9262. }
  9263. if ( geometryGroup.numMorphNormals ) {
  9264. geometryGroup.__webglMorphNormalsBuffers = [];
  9265. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9266. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  9267. }
  9268. }
  9269. _this.info.memory.geometries ++;
  9270. };
  9271. // Buffer deallocation
  9272. function deleteParticleBuffers ( geometry ) {
  9273. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9274. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9275. _this.info.memory.geometries --;
  9276. };
  9277. function deleteLineBuffers ( geometry ) {
  9278. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9279. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9280. _this.info.memory.geometries --;
  9281. };
  9282. function deleteRibbonBuffers ( geometry ) {
  9283. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9284. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9285. _this.info.memory.geometries --;
  9286. };
  9287. function deleteMeshBuffers ( geometryGroup ) {
  9288. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  9289. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  9290. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  9291. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  9292. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  9293. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  9294. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  9295. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  9296. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  9297. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  9298. var m, ml;
  9299. if ( geometryGroup.numMorphTargets ) {
  9300. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9301. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  9302. }
  9303. }
  9304. if ( geometryGroup.numMorphNormals ) {
  9305. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9306. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  9307. }
  9308. }
  9309. if ( geometryGroup.__webglCustomAttributesList ) {
  9310. for ( var id in geometryGroup.__webglCustomAttributesList ) {
  9311. _gl.deleteBuffer( geometryGroup.__webglCustomAttributesList[ id ].buffer );
  9312. }
  9313. }
  9314. _this.info.memory.geometries --;
  9315. };
  9316. // Buffer initialization
  9317. function initCustomAttributes ( geometry, object ) {
  9318. var nvertices = geometry.vertices.length;
  9319. var material = object.material;
  9320. if ( material.attributes ) {
  9321. if ( geometry.__webglCustomAttributesList === undefined ) {
  9322. geometry.__webglCustomAttributesList = [];
  9323. }
  9324. for ( var a in material.attributes ) {
  9325. var attribute = material.attributes[ a ];
  9326. if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9327. attribute.__webglInitialized = true;
  9328. var size = 1; // "f" and "i"
  9329. if ( attribute.type === "v2" ) size = 2;
  9330. else if ( attribute.type === "v3" ) size = 3;
  9331. else if ( attribute.type === "v4" ) size = 4;
  9332. else if ( attribute.type === "c" ) size = 3;
  9333. attribute.size = size;
  9334. attribute.array = new Float32Array( nvertices * size );
  9335. attribute.buffer = _gl.createBuffer();
  9336. attribute.buffer.belongsToAttribute = a;
  9337. attribute.needsUpdate = true;
  9338. }
  9339. geometry.__webglCustomAttributesList.push( attribute );
  9340. }
  9341. }
  9342. };
  9343. function initParticleBuffers ( geometry, object ) {
  9344. var nvertices = geometry.vertices.length;
  9345. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9346. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9347. geometry.__sortArray = [];
  9348. geometry.__webglParticleCount = nvertices;
  9349. initCustomAttributes ( geometry, object );
  9350. };
  9351. function initLineBuffers ( geometry, object ) {
  9352. var nvertices = geometry.vertices.length;
  9353. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9354. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9355. geometry.__webglLineCount = nvertices;
  9356. initCustomAttributes ( geometry, object );
  9357. };
  9358. function initRibbonBuffers ( geometry ) {
  9359. var nvertices = geometry.vertices.length;
  9360. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9361. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9362. geometry.__webglVertexCount = nvertices;
  9363. };
  9364. function initMeshBuffers ( geometryGroup, object ) {
  9365. var geometry = object.geometry,
  9366. faces3 = geometryGroup.faces3,
  9367. faces4 = geometryGroup.faces4,
  9368. nvertices = faces3.length * 3 + faces4.length * 4,
  9369. ntris = faces3.length * 1 + faces4.length * 2,
  9370. nlines = faces3.length * 3 + faces4.length * 4,
  9371. material = getBufferMaterial( object, geometryGroup ),
  9372. uvType = bufferGuessUVType( material ),
  9373. normalType = bufferGuessNormalType( material ),
  9374. vertexColorType = bufferGuessVertexColorType( material );
  9375. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  9376. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  9377. if ( normalType ) {
  9378. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  9379. }
  9380. if ( geometry.hasTangents ) {
  9381. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  9382. }
  9383. if ( vertexColorType ) {
  9384. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  9385. }
  9386. if ( uvType ) {
  9387. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  9388. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  9389. }
  9390. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  9391. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  9392. }
  9393. }
  9394. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  9395. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  9396. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  9397. }
  9398. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  9399. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  9400. var m, ml;
  9401. if ( geometryGroup.numMorphTargets ) {
  9402. geometryGroup.__morphTargetsArrays = [];
  9403. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9404. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  9405. }
  9406. }
  9407. if ( geometryGroup.numMorphNormals ) {
  9408. geometryGroup.__morphNormalsArrays = [];
  9409. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9410. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  9411. }
  9412. }
  9413. geometryGroup.__webglFaceCount = ntris * 3;
  9414. geometryGroup.__webglLineCount = nlines * 2;
  9415. // custom attributes
  9416. if ( material.attributes ) {
  9417. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  9418. geometryGroup.__webglCustomAttributesList = [];
  9419. }
  9420. for ( var a in material.attributes ) {
  9421. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  9422. // attribute buffers which are correctly indexed in the setMeshBuffers function
  9423. var originalAttribute = material.attributes[ a ];
  9424. var attribute = {};
  9425. for ( var property in originalAttribute ) {
  9426. attribute[ property ] = originalAttribute[ property ];
  9427. }
  9428. if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9429. attribute.__webglInitialized = true;
  9430. var size = 1; // "f" and "i"
  9431. if( attribute.type === "v2" ) size = 2;
  9432. else if( attribute.type === "v3" ) size = 3;
  9433. else if( attribute.type === "v4" ) size = 4;
  9434. else if( attribute.type === "c" ) size = 3;
  9435. attribute.size = size;
  9436. attribute.array = new Float32Array( nvertices * size );
  9437. attribute.buffer = _gl.createBuffer();
  9438. attribute.buffer.belongsToAttribute = a;
  9439. originalAttribute.needsUpdate = true;
  9440. attribute.__original = originalAttribute;
  9441. }
  9442. geometryGroup.__webglCustomAttributesList.push( attribute );
  9443. }
  9444. }
  9445. geometryGroup.__inittedArrays = true;
  9446. };
  9447. function getBufferMaterial( object, geometryGroup ) {
  9448. if ( object.material && ! ( object.material instanceof THREE.MeshFaceMaterial ) ) {
  9449. return object.material;
  9450. } else if ( geometryGroup.materialIndex >= 0 ) {
  9451. return object.geometry.materials[ geometryGroup.materialIndex ];
  9452. }
  9453. };
  9454. function materialNeedsSmoothNormals ( material ) {
  9455. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  9456. };
  9457. function bufferGuessNormalType ( material ) {
  9458. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  9459. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  9460. return false;
  9461. }
  9462. if ( materialNeedsSmoothNormals( material ) ) {
  9463. return THREE.SmoothShading;
  9464. } else {
  9465. return THREE.FlatShading;
  9466. }
  9467. };
  9468. function bufferGuessVertexColorType ( material ) {
  9469. if ( material.vertexColors ) {
  9470. return material.vertexColors;
  9471. }
  9472. return false;
  9473. };
  9474. function bufferGuessUVType ( material ) {
  9475. // material must use some texture to require uvs
  9476. if ( material.map || material.lightMap || material.bumpMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  9477. return true;
  9478. }
  9479. return false;
  9480. };
  9481. //
  9482. function initDirectBuffers( geometry ) {
  9483. var a, attribute, type;
  9484. for ( a in geometry.attributes ) {
  9485. if ( a === "index" ) {
  9486. type = _gl.ELEMENT_ARRAY_BUFFER;
  9487. } else {
  9488. type = _gl.ARRAY_BUFFER;
  9489. }
  9490. attribute = geometry.attributes[ a ];
  9491. attribute.buffer = _gl.createBuffer();
  9492. _gl.bindBuffer( type, attribute.buffer );
  9493. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  9494. }
  9495. };
  9496. // Buffer setting
  9497. function setParticleBuffers ( geometry, hint, object ) {
  9498. var v, c, vertex, offset, index, color,
  9499. vertices = geometry.vertices,
  9500. vl = vertices.length,
  9501. colors = geometry.colors,
  9502. cl = colors.length,
  9503. vertexArray = geometry.__vertexArray,
  9504. colorArray = geometry.__colorArray,
  9505. sortArray = geometry.__sortArray,
  9506. dirtyVertices = geometry.verticesNeedUpdate,
  9507. dirtyElements = geometry.elementsNeedUpdate,
  9508. dirtyColors = geometry.colorsNeedUpdate,
  9509. customAttributes = geometry.__webglCustomAttributesList,
  9510. i, il,
  9511. a, ca, cal, value,
  9512. customAttribute;
  9513. if ( object.sortParticles ) {
  9514. _projScreenMatrixPS.copy( _projScreenMatrix );
  9515. _projScreenMatrixPS.multiplySelf( object.matrixWorld );
  9516. for ( v = 0; v < vl; v ++ ) {
  9517. vertex = vertices[ v ];
  9518. _vector3.copy( vertex );
  9519. _projScreenMatrixPS.multiplyVector3( _vector3 );
  9520. sortArray[ v ] = [ _vector3.z, v ];
  9521. }
  9522. sortArray.sort( function( a, b ) { return b[ 0 ] - a[ 0 ]; } );
  9523. for ( v = 0; v < vl; v ++ ) {
  9524. vertex = vertices[ sortArray[v][1] ];
  9525. offset = v * 3;
  9526. vertexArray[ offset ] = vertex.x;
  9527. vertexArray[ offset + 1 ] = vertex.y;
  9528. vertexArray[ offset + 2 ] = vertex.z;
  9529. }
  9530. for ( c = 0; c < cl; c ++ ) {
  9531. offset = c * 3;
  9532. color = colors[ sortArray[c][1] ];
  9533. colorArray[ offset ] = color.r;
  9534. colorArray[ offset + 1 ] = color.g;
  9535. colorArray[ offset + 2 ] = color.b;
  9536. }
  9537. if ( customAttributes ) {
  9538. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  9539. customAttribute = customAttributes[ i ];
  9540. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  9541. offset = 0;
  9542. cal = customAttribute.value.length;
  9543. if ( customAttribute.size === 1 ) {
  9544. for ( ca = 0; ca < cal; ca ++ ) {
  9545. index = sortArray[ ca ][ 1 ];
  9546. customAttribute.array[ ca ] = customAttribute.value[ index ];
  9547. }
  9548. } else if ( customAttribute.size === 2 ) {
  9549. for ( ca = 0; ca < cal; ca ++ ) {
  9550. index = sortArray[ ca ][ 1 ];
  9551. value = customAttribute.value[ index ];
  9552. customAttribute.array[ offset ] = value.x;
  9553. customAttribute.array[ offset + 1 ] = value.y;
  9554. offset += 2;
  9555. }
  9556. } else if ( customAttribute.size === 3 ) {
  9557. if ( customAttribute.type === "c" ) {
  9558. for ( ca = 0; ca < cal; ca ++ ) {
  9559. index = sortArray[ ca ][ 1 ];
  9560. value = customAttribute.value[ index ];
  9561. customAttribute.array[ offset ] = value.r;
  9562. customAttribute.array[ offset + 1 ] = value.g;
  9563. customAttribute.array[ offset + 2 ] = value.b;
  9564. offset += 3;
  9565. }
  9566. } else {
  9567. for ( ca = 0; ca < cal; ca ++ ) {
  9568. index = sortArray[ ca ][ 1 ];
  9569. value = customAttribute.value[ index ];
  9570. customAttribute.array[ offset ] = value.x;
  9571. customAttribute.array[ offset + 1 ] = value.y;
  9572. customAttribute.array[ offset + 2 ] = value.z;
  9573. offset += 3;
  9574. }
  9575. }
  9576. } else if ( customAttribute.size === 4 ) {
  9577. for ( ca = 0; ca < cal; ca ++ ) {
  9578. index = sortArray[ ca ][ 1 ];
  9579. value = customAttribute.value[ index ];
  9580. customAttribute.array[ offset ] = value.x;
  9581. customAttribute.array[ offset + 1 ] = value.y;
  9582. customAttribute.array[ offset + 2 ] = value.z;
  9583. customAttribute.array[ offset + 3 ] = value.w;
  9584. offset += 4;
  9585. }
  9586. }
  9587. }
  9588. }
  9589. } else {
  9590. if ( dirtyVertices ) {
  9591. for ( v = 0; v < vl; v ++ ) {
  9592. vertex = vertices[ v ];
  9593. offset = v * 3;
  9594. vertexArray[ offset ] = vertex.x;
  9595. vertexArray[ offset + 1 ] = vertex.y;
  9596. vertexArray[ offset + 2 ] = vertex.z;
  9597. }
  9598. }
  9599. if ( dirtyColors ) {
  9600. for ( c = 0; c < cl; c ++ ) {
  9601. color = colors[ c ];
  9602. offset = c * 3;
  9603. colorArray[ offset ] = color.r;
  9604. colorArray[ offset + 1 ] = color.g;
  9605. colorArray[ offset + 2 ] = color.b;
  9606. }
  9607. }
  9608. if ( customAttributes ) {
  9609. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  9610. customAttribute = customAttributes[ i ];
  9611. if ( customAttribute.needsUpdate &&
  9612. ( customAttribute.boundTo === undefined ||
  9613. customAttribute.boundTo === "vertices") ) {
  9614. cal = customAttribute.value.length;
  9615. offset = 0;
  9616. if ( customAttribute.size === 1 ) {
  9617. for ( ca = 0; ca < cal; ca ++ ) {
  9618. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  9619. }
  9620. } else if ( customAttribute.size === 2 ) {
  9621. for ( ca = 0; ca < cal; ca ++ ) {
  9622. value = customAttribute.value[ ca ];
  9623. customAttribute.array[ offset ] = value.x;
  9624. customAttribute.array[ offset + 1 ] = value.y;
  9625. offset += 2;
  9626. }
  9627. } else if ( customAttribute.size === 3 ) {
  9628. if ( customAttribute.type === "c" ) {
  9629. for ( ca = 0; ca < cal; ca ++ ) {
  9630. value = customAttribute.value[ ca ];
  9631. customAttribute.array[ offset ] = value.r;
  9632. customAttribute.array[ offset + 1 ] = value.g;
  9633. customAttribute.array[ offset + 2 ] = value.b;
  9634. offset += 3;
  9635. }
  9636. } else {
  9637. for ( ca = 0; ca < cal; ca ++ ) {
  9638. value = customAttribute.value[ ca ];
  9639. customAttribute.array[ offset ] = value.x;
  9640. customAttribute.array[ offset + 1 ] = value.y;
  9641. customAttribute.array[ offset + 2 ] = value.z;
  9642. offset += 3;
  9643. }
  9644. }
  9645. } else if ( customAttribute.size === 4 ) {
  9646. for ( ca = 0; ca < cal; ca ++ ) {
  9647. value = customAttribute.value[ ca ];
  9648. customAttribute.array[ offset ] = value.x;
  9649. customAttribute.array[ offset + 1 ] = value.y;
  9650. customAttribute.array[ offset + 2 ] = value.z;
  9651. customAttribute.array[ offset + 3 ] = value.w;
  9652. offset += 4;
  9653. }
  9654. }
  9655. }
  9656. }
  9657. }
  9658. }
  9659. if ( dirtyVertices || object.sortParticles ) {
  9660. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  9661. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  9662. }
  9663. if ( dirtyColors || object.sortParticles ) {
  9664. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  9665. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  9666. }
  9667. if ( customAttributes ) {
  9668. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  9669. customAttribute = customAttributes[ i ];
  9670. if ( customAttribute.needsUpdate || object.sortParticles ) {
  9671. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  9672. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  9673. }
  9674. }
  9675. }
  9676. };
  9677. function setLineBuffers ( geometry, hint ) {
  9678. var v, c, vertex, offset, color,
  9679. vertices = geometry.vertices,
  9680. colors = geometry.colors,
  9681. vl = vertices.length,
  9682. cl = colors.length,
  9683. vertexArray = geometry.__vertexArray,
  9684. colorArray = geometry.__colorArray,
  9685. dirtyVertices = geometry.verticesNeedUpdate,
  9686. dirtyColors = geometry.colorsNeedUpdate,
  9687. customAttributes = geometry.__webglCustomAttributesList,
  9688. i, il,
  9689. a, ca, cal, value,
  9690. customAttribute;
  9691. if ( dirtyVertices ) {
  9692. for ( v = 0; v < vl; v ++ ) {
  9693. vertex = vertices[ v ];
  9694. offset = v * 3;
  9695. vertexArray[ offset ] = vertex.x;
  9696. vertexArray[ offset + 1 ] = vertex.y;
  9697. vertexArray[ offset + 2 ] = vertex.z;
  9698. }
  9699. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  9700. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  9701. }
  9702. if ( dirtyColors ) {
  9703. for ( c = 0; c < cl; c ++ ) {
  9704. color = colors[ c ];
  9705. offset = c * 3;
  9706. colorArray[ offset ] = color.r;
  9707. colorArray[ offset + 1 ] = color.g;
  9708. colorArray[ offset + 2 ] = color.b;
  9709. }
  9710. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  9711. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  9712. }
  9713. if ( customAttributes ) {
  9714. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  9715. customAttribute = customAttributes[ i ];
  9716. if ( customAttribute.needsUpdate &&
  9717. ( customAttribute.boundTo === undefined ||
  9718. customAttribute.boundTo === "vertices" ) ) {
  9719. offset = 0;
  9720. cal = customAttribute.value.length;
  9721. if ( customAttribute.size === 1 ) {
  9722. for ( ca = 0; ca < cal; ca ++ ) {
  9723. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  9724. }
  9725. } else if ( customAttribute.size === 2 ) {
  9726. for ( ca = 0; ca < cal; ca ++ ) {
  9727. value = customAttribute.value[ ca ];
  9728. customAttribute.array[ offset ] = value.x;
  9729. customAttribute.array[ offset + 1 ] = value.y;
  9730. offset += 2;
  9731. }
  9732. } else if ( customAttribute.size === 3 ) {
  9733. if ( customAttribute.type === "c" ) {
  9734. for ( ca = 0; ca < cal; ca ++ ) {
  9735. value = customAttribute.value[ ca ];
  9736. customAttribute.array[ offset ] = value.r;
  9737. customAttribute.array[ offset + 1 ] = value.g;
  9738. customAttribute.array[ offset + 2 ] = value.b;
  9739. offset += 3;
  9740. }
  9741. } else {
  9742. for ( ca = 0; ca < cal; ca ++ ) {
  9743. value = customAttribute.value[ ca ];
  9744. customAttribute.array[ offset ] = value.x;
  9745. customAttribute.array[ offset + 1 ] = value.y;
  9746. customAttribute.array[ offset + 2 ] = value.z;
  9747. offset += 3;
  9748. }
  9749. }
  9750. } else if ( customAttribute.size === 4 ) {
  9751. for ( ca = 0; ca < cal; ca ++ ) {
  9752. value = customAttribute.value[ ca ];
  9753. customAttribute.array[ offset ] = value.x;
  9754. customAttribute.array[ offset + 1 ] = value.y;
  9755. customAttribute.array[ offset + 2 ] = value.z;
  9756. customAttribute.array[ offset + 3 ] = value.w;
  9757. offset += 4;
  9758. }
  9759. }
  9760. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  9761. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  9762. }
  9763. }
  9764. }
  9765. };
  9766. function setRibbonBuffers ( geometry, hint ) {
  9767. var v, c, vertex, offset, color,
  9768. vertices = geometry.vertices,
  9769. colors = geometry.colors,
  9770. vl = vertices.length,
  9771. cl = colors.length,
  9772. vertexArray = geometry.__vertexArray,
  9773. colorArray = geometry.__colorArray,
  9774. dirtyVertices = geometry.verticesNeedUpdate,
  9775. dirtyColors = geometry.colorsNeedUpdate;
  9776. if ( dirtyVertices ) {
  9777. for ( v = 0; v < vl; v ++ ) {
  9778. vertex = vertices[ v ];
  9779. offset = v * 3;
  9780. vertexArray[ offset ] = vertex.x;
  9781. vertexArray[ offset + 1 ] = vertex.y;
  9782. vertexArray[ offset + 2 ] = vertex.z;
  9783. }
  9784. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  9785. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  9786. }
  9787. if ( dirtyColors ) {
  9788. for ( c = 0; c < cl; c ++ ) {
  9789. color = colors[ c ];
  9790. offset = c * 3;
  9791. colorArray[ offset ] = color.r;
  9792. colorArray[ offset + 1 ] = color.g;
  9793. colorArray[ offset + 2 ] = color.b;
  9794. }
  9795. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  9796. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  9797. }
  9798. };
  9799. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  9800. if ( ! geometryGroup.__inittedArrays ) {
  9801. // console.log( object );
  9802. return;
  9803. }
  9804. var normalType = bufferGuessNormalType( material ),
  9805. vertexColorType = bufferGuessVertexColorType( material ),
  9806. uvType = bufferGuessUVType( material ),
  9807. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  9808. var f, fl, fi, face,
  9809. vertexNormals, faceNormal, normal,
  9810. vertexColors, faceColor,
  9811. vertexTangents,
  9812. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  9813. c1, c2, c3, c4,
  9814. sw1, sw2, sw3, sw4,
  9815. si1, si2, si3, si4,
  9816. sa1, sa2, sa3, sa4,
  9817. sb1, sb2, sb3, sb4,
  9818. m, ml, i, il,
  9819. vn, uvi, uv2i,
  9820. vk, vkl, vka,
  9821. nka, chf, faceVertexNormals,
  9822. a,
  9823. vertexIndex = 0,
  9824. offset = 0,
  9825. offset_uv = 0,
  9826. offset_uv2 = 0,
  9827. offset_face = 0,
  9828. offset_normal = 0,
  9829. offset_tangent = 0,
  9830. offset_line = 0,
  9831. offset_color = 0,
  9832. offset_skin = 0,
  9833. offset_morphTarget = 0,
  9834. offset_custom = 0,
  9835. offset_customSrc = 0,
  9836. value,
  9837. vertexArray = geometryGroup.__vertexArray,
  9838. uvArray = geometryGroup.__uvArray,
  9839. uv2Array = geometryGroup.__uv2Array,
  9840. normalArray = geometryGroup.__normalArray,
  9841. tangentArray = geometryGroup.__tangentArray,
  9842. colorArray = geometryGroup.__colorArray,
  9843. skinIndexArray = geometryGroup.__skinIndexArray,
  9844. skinWeightArray = geometryGroup.__skinWeightArray,
  9845. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  9846. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  9847. customAttributes = geometryGroup.__webglCustomAttributesList,
  9848. customAttribute,
  9849. faceArray = geometryGroup.__faceArray,
  9850. lineArray = geometryGroup.__lineArray,
  9851. geometry = object.geometry, // this is shared for all chunks
  9852. dirtyVertices = geometry.verticesNeedUpdate,
  9853. dirtyElements = geometry.elementsNeedUpdate,
  9854. dirtyUvs = geometry.uvsNeedUpdate,
  9855. dirtyNormals = geometry.normalsNeedUpdate,
  9856. dirtyTangents = geometry.tangentsNeedUpdate,
  9857. dirtyColors = geometry.colorsNeedUpdate,
  9858. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  9859. vertices = geometry.vertices,
  9860. chunk_faces3 = geometryGroup.faces3,
  9861. chunk_faces4 = geometryGroup.faces4,
  9862. obj_faces = geometry.faces,
  9863. obj_uvs = geometry.faceVertexUvs[ 0 ],
  9864. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  9865. obj_colors = geometry.colors,
  9866. obj_skinIndices = geometry.skinIndices,
  9867. obj_skinWeights = geometry.skinWeights,
  9868. morphTargets = geometry.morphTargets,
  9869. morphNormals = geometry.morphNormals;
  9870. if ( dirtyVertices ) {
  9871. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  9872. face = obj_faces[ chunk_faces3[ f ] ];
  9873. v1 = vertices[ face.a ];
  9874. v2 = vertices[ face.b ];
  9875. v3 = vertices[ face.c ];
  9876. vertexArray[ offset ] = v1.x;
  9877. vertexArray[ offset + 1 ] = v1.y;
  9878. vertexArray[ offset + 2 ] = v1.z;
  9879. vertexArray[ offset + 3 ] = v2.x;
  9880. vertexArray[ offset + 4 ] = v2.y;
  9881. vertexArray[ offset + 5 ] = v2.z;
  9882. vertexArray[ offset + 6 ] = v3.x;
  9883. vertexArray[ offset + 7 ] = v3.y;
  9884. vertexArray[ offset + 8 ] = v3.z;
  9885. offset += 9;
  9886. }
  9887. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  9888. face = obj_faces[ chunk_faces4[ f ] ];
  9889. v1 = vertices[ face.a ];
  9890. v2 = vertices[ face.b ];
  9891. v3 = vertices[ face.c ];
  9892. v4 = vertices[ face.d ];
  9893. vertexArray[ offset ] = v1.x;
  9894. vertexArray[ offset + 1 ] = v1.y;
  9895. vertexArray[ offset + 2 ] = v1.z;
  9896. vertexArray[ offset + 3 ] = v2.x;
  9897. vertexArray[ offset + 4 ] = v2.y;
  9898. vertexArray[ offset + 5 ] = v2.z;
  9899. vertexArray[ offset + 6 ] = v3.x;
  9900. vertexArray[ offset + 7 ] = v3.y;
  9901. vertexArray[ offset + 8 ] = v3.z;
  9902. vertexArray[ offset + 9 ] = v4.x;
  9903. vertexArray[ offset + 10 ] = v4.y;
  9904. vertexArray[ offset + 11 ] = v4.z;
  9905. offset += 12;
  9906. }
  9907. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  9908. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  9909. }
  9910. if ( dirtyMorphTargets ) {
  9911. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  9912. offset_morphTarget = 0;
  9913. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  9914. chf = chunk_faces3[ f ];
  9915. face = obj_faces[ chf ];
  9916. // morph positions
  9917. v1 = morphTargets[ vk ].vertices[ face.a ];
  9918. v2 = morphTargets[ vk ].vertices[ face.b ];
  9919. v3 = morphTargets[ vk ].vertices[ face.c ];
  9920. vka = morphTargetsArrays[ vk ];
  9921. vka[ offset_morphTarget ] = v1.x;
  9922. vka[ offset_morphTarget + 1 ] = v1.y;
  9923. vka[ offset_morphTarget + 2 ] = v1.z;
  9924. vka[ offset_morphTarget + 3 ] = v2.x;
  9925. vka[ offset_morphTarget + 4 ] = v2.y;
  9926. vka[ offset_morphTarget + 5 ] = v2.z;
  9927. vka[ offset_morphTarget + 6 ] = v3.x;
  9928. vka[ offset_morphTarget + 7 ] = v3.y;
  9929. vka[ offset_morphTarget + 8 ] = v3.z;
  9930. // morph normals
  9931. if ( material.morphNormals ) {
  9932. if ( needsSmoothNormals ) {
  9933. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  9934. n1 = faceVertexNormals.a;
  9935. n2 = faceVertexNormals.b;
  9936. n3 = faceVertexNormals.c;
  9937. } else {
  9938. n1 = morphNormals[ vk ].faceNormals[ chf ];
  9939. n2 = n1;
  9940. n3 = n1;
  9941. }
  9942. nka = morphNormalsArrays[ vk ];
  9943. nka[ offset_morphTarget ] = n1.x;
  9944. nka[ offset_morphTarget + 1 ] = n1.y;
  9945. nka[ offset_morphTarget + 2 ] = n1.z;
  9946. nka[ offset_morphTarget + 3 ] = n2.x;
  9947. nka[ offset_morphTarget + 4 ] = n2.y;
  9948. nka[ offset_morphTarget + 5 ] = n2.z;
  9949. nka[ offset_morphTarget + 6 ] = n3.x;
  9950. nka[ offset_morphTarget + 7 ] = n3.y;
  9951. nka[ offset_morphTarget + 8 ] = n3.z;
  9952. }
  9953. //
  9954. offset_morphTarget += 9;
  9955. }
  9956. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  9957. chf = chunk_faces4[ f ];
  9958. face = obj_faces[ chf ];
  9959. // morph positions
  9960. v1 = morphTargets[ vk ].vertices[ face.a ];
  9961. v2 = morphTargets[ vk ].vertices[ face.b ];
  9962. v3 = morphTargets[ vk ].vertices[ face.c ];
  9963. v4 = morphTargets[ vk ].vertices[ face.d ];
  9964. vka = morphTargetsArrays[ vk ];
  9965. vka[ offset_morphTarget ] = v1.x;
  9966. vka[ offset_morphTarget + 1 ] = v1.y;
  9967. vka[ offset_morphTarget + 2 ] = v1.z;
  9968. vka[ offset_morphTarget + 3 ] = v2.x;
  9969. vka[ offset_morphTarget + 4 ] = v2.y;
  9970. vka[ offset_morphTarget + 5 ] = v2.z;
  9971. vka[ offset_morphTarget + 6 ] = v3.x;
  9972. vka[ offset_morphTarget + 7 ] = v3.y;
  9973. vka[ offset_morphTarget + 8 ] = v3.z;
  9974. vka[ offset_morphTarget + 9 ] = v4.x;
  9975. vka[ offset_morphTarget + 10 ] = v4.y;
  9976. vka[ offset_morphTarget + 11 ] = v4.z;
  9977. // morph normals
  9978. if ( material.morphNormals ) {
  9979. if ( needsSmoothNormals ) {
  9980. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  9981. n1 = faceVertexNormals.a;
  9982. n2 = faceVertexNormals.b;
  9983. n3 = faceVertexNormals.c;
  9984. n4 = faceVertexNormals.d;
  9985. } else {
  9986. n1 = morphNormals[ vk ].faceNormals[ chf ];
  9987. n2 = n1;
  9988. n3 = n1;
  9989. n4 = n1;
  9990. }
  9991. nka = morphNormalsArrays[ vk ];
  9992. nka[ offset_morphTarget ] = n1.x;
  9993. nka[ offset_morphTarget + 1 ] = n1.y;
  9994. nka[ offset_morphTarget + 2 ] = n1.z;
  9995. nka[ offset_morphTarget + 3 ] = n2.x;
  9996. nka[ offset_morphTarget + 4 ] = n2.y;
  9997. nka[ offset_morphTarget + 5 ] = n2.z;
  9998. nka[ offset_morphTarget + 6 ] = n3.x;
  9999. nka[ offset_morphTarget + 7 ] = n3.y;
  10000. nka[ offset_morphTarget + 8 ] = n3.z;
  10001. nka[ offset_morphTarget + 9 ] = n4.x;
  10002. nka[ offset_morphTarget + 10 ] = n4.y;
  10003. nka[ offset_morphTarget + 11 ] = n4.z;
  10004. }
  10005. //
  10006. offset_morphTarget += 12;
  10007. }
  10008. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  10009. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  10010. if ( material.morphNormals ) {
  10011. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  10012. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  10013. }
  10014. }
  10015. }
  10016. if ( obj_skinWeights.length ) {
  10017. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10018. face = obj_faces[ chunk_faces3[ f ] ];
  10019. // weights
  10020. sw1 = obj_skinWeights[ face.a ];
  10021. sw2 = obj_skinWeights[ face.b ];
  10022. sw3 = obj_skinWeights[ face.c ];
  10023. skinWeightArray[ offset_skin ] = sw1.x;
  10024. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  10025. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  10026. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  10027. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  10028. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  10029. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  10030. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  10031. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  10032. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  10033. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  10034. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  10035. // indices
  10036. si1 = obj_skinIndices[ face.a ];
  10037. si2 = obj_skinIndices[ face.b ];
  10038. si3 = obj_skinIndices[ face.c ];
  10039. skinIndexArray[ offset_skin ] = si1.x;
  10040. skinIndexArray[ offset_skin + 1 ] = si1.y;
  10041. skinIndexArray[ offset_skin + 2 ] = si1.z;
  10042. skinIndexArray[ offset_skin + 3 ] = si1.w;
  10043. skinIndexArray[ offset_skin + 4 ] = si2.x;
  10044. skinIndexArray[ offset_skin + 5 ] = si2.y;
  10045. skinIndexArray[ offset_skin + 6 ] = si2.z;
  10046. skinIndexArray[ offset_skin + 7 ] = si2.w;
  10047. skinIndexArray[ offset_skin + 8 ] = si3.x;
  10048. skinIndexArray[ offset_skin + 9 ] = si3.y;
  10049. skinIndexArray[ offset_skin + 10 ] = si3.z;
  10050. skinIndexArray[ offset_skin + 11 ] = si3.w;
  10051. offset_skin += 12;
  10052. }
  10053. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10054. face = obj_faces[ chunk_faces4[ f ] ];
  10055. // weights
  10056. sw1 = obj_skinWeights[ face.a ];
  10057. sw2 = obj_skinWeights[ face.b ];
  10058. sw3 = obj_skinWeights[ face.c ];
  10059. sw4 = obj_skinWeights[ face.d ];
  10060. skinWeightArray[ offset_skin ] = sw1.x;
  10061. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  10062. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  10063. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  10064. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  10065. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  10066. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  10067. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  10068. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  10069. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  10070. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  10071. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  10072. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  10073. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  10074. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  10075. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  10076. // indices
  10077. si1 = obj_skinIndices[ face.a ];
  10078. si2 = obj_skinIndices[ face.b ];
  10079. si3 = obj_skinIndices[ face.c ];
  10080. si4 = obj_skinIndices[ face.d ];
  10081. skinIndexArray[ offset_skin ] = si1.x;
  10082. skinIndexArray[ offset_skin + 1 ] = si1.y;
  10083. skinIndexArray[ offset_skin + 2 ] = si1.z;
  10084. skinIndexArray[ offset_skin + 3 ] = si1.w;
  10085. skinIndexArray[ offset_skin + 4 ] = si2.x;
  10086. skinIndexArray[ offset_skin + 5 ] = si2.y;
  10087. skinIndexArray[ offset_skin + 6 ] = si2.z;
  10088. skinIndexArray[ offset_skin + 7 ] = si2.w;
  10089. skinIndexArray[ offset_skin + 8 ] = si3.x;
  10090. skinIndexArray[ offset_skin + 9 ] = si3.y;
  10091. skinIndexArray[ offset_skin + 10 ] = si3.z;
  10092. skinIndexArray[ offset_skin + 11 ] = si3.w;
  10093. skinIndexArray[ offset_skin + 12 ] = si4.x;
  10094. skinIndexArray[ offset_skin + 13 ] = si4.y;
  10095. skinIndexArray[ offset_skin + 14 ] = si4.z;
  10096. skinIndexArray[ offset_skin + 15 ] = si4.w;
  10097. offset_skin += 16;
  10098. }
  10099. if ( offset_skin > 0 ) {
  10100. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  10101. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  10102. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  10103. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  10104. }
  10105. }
  10106. if ( dirtyColors && vertexColorType ) {
  10107. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10108. face = obj_faces[ chunk_faces3[ f ] ];
  10109. vertexColors = face.vertexColors;
  10110. faceColor = face.color;
  10111. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  10112. c1 = vertexColors[ 0 ];
  10113. c2 = vertexColors[ 1 ];
  10114. c3 = vertexColors[ 2 ];
  10115. } else {
  10116. c1 = faceColor;
  10117. c2 = faceColor;
  10118. c3 = faceColor;
  10119. }
  10120. colorArray[ offset_color ] = c1.r;
  10121. colorArray[ offset_color + 1 ] = c1.g;
  10122. colorArray[ offset_color + 2 ] = c1.b;
  10123. colorArray[ offset_color + 3 ] = c2.r;
  10124. colorArray[ offset_color + 4 ] = c2.g;
  10125. colorArray[ offset_color + 5 ] = c2.b;
  10126. colorArray[ offset_color + 6 ] = c3.r;
  10127. colorArray[ offset_color + 7 ] = c3.g;
  10128. colorArray[ offset_color + 8 ] = c3.b;
  10129. offset_color += 9;
  10130. }
  10131. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10132. face = obj_faces[ chunk_faces4[ f ] ];
  10133. vertexColors = face.vertexColors;
  10134. faceColor = face.color;
  10135. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  10136. c1 = vertexColors[ 0 ];
  10137. c2 = vertexColors[ 1 ];
  10138. c3 = vertexColors[ 2 ];
  10139. c4 = vertexColors[ 3 ];
  10140. } else {
  10141. c1 = faceColor;
  10142. c2 = faceColor;
  10143. c3 = faceColor;
  10144. c4 = faceColor;
  10145. }
  10146. colorArray[ offset_color ] = c1.r;
  10147. colorArray[ offset_color + 1 ] = c1.g;
  10148. colorArray[ offset_color + 2 ] = c1.b;
  10149. colorArray[ offset_color + 3 ] = c2.r;
  10150. colorArray[ offset_color + 4 ] = c2.g;
  10151. colorArray[ offset_color + 5 ] = c2.b;
  10152. colorArray[ offset_color + 6 ] = c3.r;
  10153. colorArray[ offset_color + 7 ] = c3.g;
  10154. colorArray[ offset_color + 8 ] = c3.b;
  10155. colorArray[ offset_color + 9 ] = c4.r;
  10156. colorArray[ offset_color + 10 ] = c4.g;
  10157. colorArray[ offset_color + 11 ] = c4.b;
  10158. offset_color += 12;
  10159. }
  10160. if ( offset_color > 0 ) {
  10161. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  10162. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10163. }
  10164. }
  10165. if ( dirtyTangents && geometry.hasTangents ) {
  10166. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10167. face = obj_faces[ chunk_faces3[ f ] ];
  10168. vertexTangents = face.vertexTangents;
  10169. t1 = vertexTangents[ 0 ];
  10170. t2 = vertexTangents[ 1 ];
  10171. t3 = vertexTangents[ 2 ];
  10172. tangentArray[ offset_tangent ] = t1.x;
  10173. tangentArray[ offset_tangent + 1 ] = t1.y;
  10174. tangentArray[ offset_tangent + 2 ] = t1.z;
  10175. tangentArray[ offset_tangent + 3 ] = t1.w;
  10176. tangentArray[ offset_tangent + 4 ] = t2.x;
  10177. tangentArray[ offset_tangent + 5 ] = t2.y;
  10178. tangentArray[ offset_tangent + 6 ] = t2.z;
  10179. tangentArray[ offset_tangent + 7 ] = t2.w;
  10180. tangentArray[ offset_tangent + 8 ] = t3.x;
  10181. tangentArray[ offset_tangent + 9 ] = t3.y;
  10182. tangentArray[ offset_tangent + 10 ] = t3.z;
  10183. tangentArray[ offset_tangent + 11 ] = t3.w;
  10184. offset_tangent += 12;
  10185. }
  10186. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10187. face = obj_faces[ chunk_faces4[ f ] ];
  10188. vertexTangents = face.vertexTangents;
  10189. t1 = vertexTangents[ 0 ];
  10190. t2 = vertexTangents[ 1 ];
  10191. t3 = vertexTangents[ 2 ];
  10192. t4 = vertexTangents[ 3 ];
  10193. tangentArray[ offset_tangent ] = t1.x;
  10194. tangentArray[ offset_tangent + 1 ] = t1.y;
  10195. tangentArray[ offset_tangent + 2 ] = t1.z;
  10196. tangentArray[ offset_tangent + 3 ] = t1.w;
  10197. tangentArray[ offset_tangent + 4 ] = t2.x;
  10198. tangentArray[ offset_tangent + 5 ] = t2.y;
  10199. tangentArray[ offset_tangent + 6 ] = t2.z;
  10200. tangentArray[ offset_tangent + 7 ] = t2.w;
  10201. tangentArray[ offset_tangent + 8 ] = t3.x;
  10202. tangentArray[ offset_tangent + 9 ] = t3.y;
  10203. tangentArray[ offset_tangent + 10 ] = t3.z;
  10204. tangentArray[ offset_tangent + 11 ] = t3.w;
  10205. tangentArray[ offset_tangent + 12 ] = t4.x;
  10206. tangentArray[ offset_tangent + 13 ] = t4.y;
  10207. tangentArray[ offset_tangent + 14 ] = t4.z;
  10208. tangentArray[ offset_tangent + 15 ] = t4.w;
  10209. offset_tangent += 16;
  10210. }
  10211. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  10212. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  10213. }
  10214. if ( dirtyNormals && normalType ) {
  10215. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10216. face = obj_faces[ chunk_faces3[ f ] ];
  10217. vertexNormals = face.vertexNormals;
  10218. faceNormal = face.normal;
  10219. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  10220. for ( i = 0; i < 3; i ++ ) {
  10221. vn = vertexNormals[ i ];
  10222. normalArray[ offset_normal ] = vn.x;
  10223. normalArray[ offset_normal + 1 ] = vn.y;
  10224. normalArray[ offset_normal + 2 ] = vn.z;
  10225. offset_normal += 3;
  10226. }
  10227. } else {
  10228. for ( i = 0; i < 3; i ++ ) {
  10229. normalArray[ offset_normal ] = faceNormal.x;
  10230. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10231. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10232. offset_normal += 3;
  10233. }
  10234. }
  10235. }
  10236. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10237. face = obj_faces[ chunk_faces4[ f ] ];
  10238. vertexNormals = face.vertexNormals;
  10239. faceNormal = face.normal;
  10240. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  10241. for ( i = 0; i < 4; i ++ ) {
  10242. vn = vertexNormals[ i ];
  10243. normalArray[ offset_normal ] = vn.x;
  10244. normalArray[ offset_normal + 1 ] = vn.y;
  10245. normalArray[ offset_normal + 2 ] = vn.z;
  10246. offset_normal += 3;
  10247. }
  10248. } else {
  10249. for ( i = 0; i < 4; i ++ ) {
  10250. normalArray[ offset_normal ] = faceNormal.x;
  10251. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10252. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10253. offset_normal += 3;
  10254. }
  10255. }
  10256. }
  10257. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  10258. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  10259. }
  10260. if ( dirtyUvs && obj_uvs && uvType ) {
  10261. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10262. fi = chunk_faces3[ f ];
  10263. face = obj_faces[ fi ];
  10264. uv = obj_uvs[ fi ];
  10265. if ( uv === undefined ) continue;
  10266. for ( i = 0; i < 3; i ++ ) {
  10267. uvi = uv[ i ];
  10268. uvArray[ offset_uv ] = uvi.u;
  10269. uvArray[ offset_uv + 1 ] = uvi.v;
  10270. offset_uv += 2;
  10271. }
  10272. }
  10273. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10274. fi = chunk_faces4[ f ];
  10275. face = obj_faces[ fi ];
  10276. uv = obj_uvs[ fi ];
  10277. if ( uv === undefined ) continue;
  10278. for ( i = 0; i < 4; i ++ ) {
  10279. uvi = uv[ i ];
  10280. uvArray[ offset_uv ] = uvi.u;
  10281. uvArray[ offset_uv + 1 ] = uvi.v;
  10282. offset_uv += 2;
  10283. }
  10284. }
  10285. if ( offset_uv > 0 ) {
  10286. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  10287. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  10288. }
  10289. }
  10290. if ( dirtyUvs && obj_uvs2 && uvType ) {
  10291. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10292. fi = chunk_faces3[ f ];
  10293. face = obj_faces[ fi ];
  10294. uv2 = obj_uvs2[ fi ];
  10295. if ( uv2 === undefined ) continue;
  10296. for ( i = 0; i < 3; i ++ ) {
  10297. uv2i = uv2[ i ];
  10298. uv2Array[ offset_uv2 ] = uv2i.u;
  10299. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10300. offset_uv2 += 2;
  10301. }
  10302. }
  10303. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10304. fi = chunk_faces4[ f ];
  10305. face = obj_faces[ fi ];
  10306. uv2 = obj_uvs2[ fi ];
  10307. if ( uv2 === undefined ) continue;
  10308. for ( i = 0; i < 4; i ++ ) {
  10309. uv2i = uv2[ i ];
  10310. uv2Array[ offset_uv2 ] = uv2i.u;
  10311. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10312. offset_uv2 += 2;
  10313. }
  10314. }
  10315. if ( offset_uv2 > 0 ) {
  10316. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  10317. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  10318. }
  10319. }
  10320. if ( dirtyElements ) {
  10321. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10322. face = obj_faces[ chunk_faces3[ f ] ];
  10323. faceArray[ offset_face ] = vertexIndex;
  10324. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10325. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  10326. offset_face += 3;
  10327. lineArray[ offset_line ] = vertexIndex;
  10328. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10329. lineArray[ offset_line + 2 ] = vertexIndex;
  10330. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  10331. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10332. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10333. offset_line += 6;
  10334. vertexIndex += 3;
  10335. }
  10336. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10337. face = obj_faces[ chunk_faces4[ f ] ];
  10338. faceArray[ offset_face ] = vertexIndex;
  10339. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10340. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  10341. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  10342. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  10343. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  10344. offset_face += 6;
  10345. lineArray[ offset_line ] = vertexIndex;
  10346. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10347. lineArray[ offset_line + 2 ] = vertexIndex;
  10348. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  10349. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10350. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10351. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  10352. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  10353. offset_line += 8;
  10354. vertexIndex += 4;
  10355. }
  10356. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  10357. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  10358. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  10359. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  10360. }
  10361. if ( customAttributes ) {
  10362. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10363. customAttribute = customAttributes[ i ];
  10364. if ( ! customAttribute.__original.needsUpdate ) continue;
  10365. offset_custom = 0;
  10366. offset_customSrc = 0;
  10367. if ( customAttribute.size === 1 ) {
  10368. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10369. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10370. face = obj_faces[ chunk_faces3[ f ] ];
  10371. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10372. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  10373. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  10374. offset_custom += 3;
  10375. }
  10376. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10377. face = obj_faces[ chunk_faces4[ f ] ];
  10378. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10379. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  10380. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  10381. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  10382. offset_custom += 4;
  10383. }
  10384. } else if ( customAttribute.boundTo === "faces" ) {
  10385. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10386. value = customAttribute.value[ chunk_faces3[ f ] ];
  10387. customAttribute.array[ offset_custom ] = value;
  10388. customAttribute.array[ offset_custom + 1 ] = value;
  10389. customAttribute.array[ offset_custom + 2 ] = value;
  10390. offset_custom += 3;
  10391. }
  10392. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10393. value = customAttribute.value[ chunk_faces4[ f ] ];
  10394. customAttribute.array[ offset_custom ] = value;
  10395. customAttribute.array[ offset_custom + 1 ] = value;
  10396. customAttribute.array[ offset_custom + 2 ] = value;
  10397. customAttribute.array[ offset_custom + 3 ] = value;
  10398. offset_custom += 4;
  10399. }
  10400. }
  10401. } else if ( customAttribute.size === 2 ) {
  10402. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10403. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10404. face = obj_faces[ chunk_faces3[ f ] ];
  10405. v1 = customAttribute.value[ face.a ];
  10406. v2 = customAttribute.value[ face.b ];
  10407. v3 = customAttribute.value[ face.c ];
  10408. customAttribute.array[ offset_custom ] = v1.x;
  10409. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10410. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10411. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10412. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10413. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10414. offset_custom += 6;
  10415. }
  10416. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10417. face = obj_faces[ chunk_faces4[ f ] ];
  10418. v1 = customAttribute.value[ face.a ];
  10419. v2 = customAttribute.value[ face.b ];
  10420. v3 = customAttribute.value[ face.c ];
  10421. v4 = customAttribute.value[ face.d ];
  10422. customAttribute.array[ offset_custom ] = v1.x;
  10423. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10424. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10425. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10426. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10427. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10428. customAttribute.array[ offset_custom + 6 ] = v4.x;
  10429. customAttribute.array[ offset_custom + 7 ] = v4.y;
  10430. offset_custom += 8;
  10431. }
  10432. } else if ( customAttribute.boundTo === "faces" ) {
  10433. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10434. value = customAttribute.value[ chunk_faces3[ f ] ];
  10435. v1 = value;
  10436. v2 = value;
  10437. v3 = value;
  10438. customAttribute.array[ offset_custom ] = v1.x;
  10439. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10440. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10441. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10442. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10443. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10444. offset_custom += 6;
  10445. }
  10446. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10447. value = customAttribute.value[ chunk_faces4[ f ] ];
  10448. v1 = value;
  10449. v2 = value;
  10450. v3 = value;
  10451. v4 = value;
  10452. customAttribute.array[ offset_custom ] = v1.x;
  10453. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10454. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10455. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10456. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10457. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10458. customAttribute.array[ offset_custom + 6 ] = v4.x;
  10459. customAttribute.array[ offset_custom + 7 ] = v4.y;
  10460. offset_custom += 8;
  10461. }
  10462. }
  10463. } else if ( customAttribute.size === 3 ) {
  10464. var pp;
  10465. if ( customAttribute.type === "c" ) {
  10466. pp = [ "r", "g", "b" ];
  10467. } else {
  10468. pp = [ "x", "y", "z" ];
  10469. }
  10470. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10471. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10472. face = obj_faces[ chunk_faces3[ f ] ];
  10473. v1 = customAttribute.value[ face.a ];
  10474. v2 = customAttribute.value[ face.b ];
  10475. v3 = customAttribute.value[ face.c ];
  10476. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10477. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10478. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10479. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10480. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10481. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10482. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10483. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10484. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10485. offset_custom += 9;
  10486. }
  10487. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10488. face = obj_faces[ chunk_faces4[ f ] ];
  10489. v1 = customAttribute.value[ face.a ];
  10490. v2 = customAttribute.value[ face.b ];
  10491. v3 = customAttribute.value[ face.c ];
  10492. v4 = customAttribute.value[ face.d ];
  10493. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10494. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10495. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10496. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10497. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10498. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10499. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10500. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10501. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10502. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  10503. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  10504. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  10505. offset_custom += 12;
  10506. }
  10507. } else if ( customAttribute.boundTo === "faces" ) {
  10508. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10509. value = customAttribute.value[ chunk_faces3[ f ] ];
  10510. v1 = value;
  10511. v2 = value;
  10512. v3 = value;
  10513. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10514. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10515. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10516. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10517. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10518. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10519. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10520. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10521. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10522. offset_custom += 9;
  10523. }
  10524. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10525. value = customAttribute.value[ chunk_faces4[ f ] ];
  10526. v1 = value;
  10527. v2 = value;
  10528. v3 = value;
  10529. v4 = value;
  10530. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10531. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10532. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10533. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10534. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10535. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10536. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10537. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10538. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10539. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  10540. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  10541. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  10542. offset_custom += 12;
  10543. }
  10544. } else if ( customAttribute.boundTo === "faceVertices" ) {
  10545. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10546. value = customAttribute.value[ chunk_faces3[ f ] ];
  10547. v1 = value[ 0 ];
  10548. v2 = value[ 1 ];
  10549. v3 = value[ 2 ];
  10550. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10551. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10552. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10553. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10554. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10555. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10556. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10557. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10558. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10559. offset_custom += 9;
  10560. }
  10561. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10562. value = customAttribute.value[ chunk_faces4[ f ] ];
  10563. v1 = value[ 0 ];
  10564. v2 = value[ 1 ];
  10565. v3 = value[ 2 ];
  10566. v4 = value[ 3 ];
  10567. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10568. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10569. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10570. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10571. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10572. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10573. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10574. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10575. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10576. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  10577. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  10578. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  10579. offset_custom += 12;
  10580. }
  10581. }
  10582. } else if ( customAttribute.size === 4 ) {
  10583. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10584. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10585. face = obj_faces[ chunk_faces3[ f ] ];
  10586. v1 = customAttribute.value[ face.a ];
  10587. v2 = customAttribute.value[ face.b ];
  10588. v3 = customAttribute.value[ face.c ];
  10589. customAttribute.array[ offset_custom ] = v1.x;
  10590. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10591. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10592. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10593. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10594. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10595. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10596. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10597. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10598. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10599. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10600. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10601. offset_custom += 12;
  10602. }
  10603. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10604. face = obj_faces[ chunk_faces4[ f ] ];
  10605. v1 = customAttribute.value[ face.a ];
  10606. v2 = customAttribute.value[ face.b ];
  10607. v3 = customAttribute.value[ face.c ];
  10608. v4 = customAttribute.value[ face.d ];
  10609. customAttribute.array[ offset_custom ] = v1.x;
  10610. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10611. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10612. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10613. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10614. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10615. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10616. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10617. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10618. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10619. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10620. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10621. customAttribute.array[ offset_custom + 12 ] = v4.x;
  10622. customAttribute.array[ offset_custom + 13 ] = v4.y;
  10623. customAttribute.array[ offset_custom + 14 ] = v4.z;
  10624. customAttribute.array[ offset_custom + 15 ] = v4.w;
  10625. offset_custom += 16;
  10626. }
  10627. } else if ( customAttribute.boundTo === "faces" ) {
  10628. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10629. value = customAttribute.value[ chunk_faces3[ f ] ];
  10630. v1 = value;
  10631. v2 = value;
  10632. v3 = value;
  10633. customAttribute.array[ offset_custom ] = v1.x;
  10634. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10635. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10636. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10637. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10638. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10639. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10640. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10641. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10642. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10643. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10644. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10645. offset_custom += 12;
  10646. }
  10647. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10648. value = customAttribute.value[ chunk_faces4[ f ] ];
  10649. v1 = value;
  10650. v2 = value;
  10651. v3 = value;
  10652. v4 = value;
  10653. customAttribute.array[ offset_custom ] = v1.x;
  10654. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10655. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10656. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10657. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10658. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10659. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10660. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10661. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10662. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10663. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10664. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10665. customAttribute.array[ offset_custom + 12 ] = v4.x;
  10666. customAttribute.array[ offset_custom + 13 ] = v4.y;
  10667. customAttribute.array[ offset_custom + 14 ] = v4.z;
  10668. customAttribute.array[ offset_custom + 15 ] = v4.w;
  10669. offset_custom += 16;
  10670. }
  10671. } else if ( customAttribute.boundTo === "faceVertices" ) {
  10672. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10673. value = customAttribute.value[ chunk_faces3[ f ] ];
  10674. v1 = value[ 0 ];
  10675. v2 = value[ 1 ];
  10676. v3 = value[ 2 ];
  10677. customAttribute.array[ offset_custom ] = v1.x;
  10678. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10679. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10680. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10681. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10682. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10683. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10684. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10685. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10686. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10687. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10688. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10689. offset_custom += 12;
  10690. }
  10691. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10692. value = customAttribute.value[ chunk_faces4[ f ] ];
  10693. v1 = value[ 0 ];
  10694. v2 = value[ 1 ];
  10695. v3 = value[ 2 ];
  10696. v4 = value[ 3 ];
  10697. customAttribute.array[ offset_custom ] = v1.x;
  10698. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10699. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10700. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10701. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10702. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10703. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10704. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10705. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10706. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10707. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10708. customAttribute.array[ offset_custom + 11 ] = v3.w;
  10709. customAttribute.array[ offset_custom + 12 ] = v4.x;
  10710. customAttribute.array[ offset_custom + 13 ] = v4.y;
  10711. customAttribute.array[ offset_custom + 14 ] = v4.z;
  10712. customAttribute.array[ offset_custom + 15 ] = v4.w;
  10713. offset_custom += 16;
  10714. }
  10715. }
  10716. }
  10717. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10718. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10719. }
  10720. }
  10721. if ( dispose ) {
  10722. delete geometryGroup.__inittedArrays;
  10723. delete geometryGroup.__colorArray;
  10724. delete geometryGroup.__normalArray;
  10725. delete geometryGroup.__tangentArray;
  10726. delete geometryGroup.__uvArray;
  10727. delete geometryGroup.__uv2Array;
  10728. delete geometryGroup.__faceArray;
  10729. delete geometryGroup.__vertexArray;
  10730. delete geometryGroup.__lineArray;
  10731. delete geometryGroup.__skinIndexArray;
  10732. delete geometryGroup.__skinWeightArray;
  10733. }
  10734. };
  10735. function setDirectBuffers ( geometry, hint, dispose ) {
  10736. var attributes = geometry.attributes;
  10737. var index = attributes[ "index" ];
  10738. var position = attributes[ "position" ];
  10739. var normal = attributes[ "normal" ];
  10740. var uv = attributes[ "uv" ];
  10741. var color = attributes[ "color" ];
  10742. var tangent = attributes[ "tangent" ];
  10743. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  10744. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  10745. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  10746. }
  10747. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  10748. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  10749. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  10750. }
  10751. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  10752. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  10753. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  10754. }
  10755. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  10756. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  10757. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  10758. }
  10759. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  10760. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  10761. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  10762. }
  10763. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  10764. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  10765. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  10766. }
  10767. if ( dispose ) {
  10768. for ( var i in geometry.attributes ) {
  10769. delete geometry.attributes[ i ].array;
  10770. }
  10771. }
  10772. };
  10773. // Buffer rendering
  10774. this.renderBufferImmediate = function ( object, program, material ) {
  10775. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  10776. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  10777. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  10778. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  10779. if ( object.hasPositions ) {
  10780. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  10781. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  10782. _gl.enableVertexAttribArray( program.attributes.position );
  10783. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  10784. }
  10785. if ( object.hasNormals ) {
  10786. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  10787. if ( material.shading === THREE.FlatShading ) {
  10788. var nx, ny, nz,
  10789. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  10790. normalArray,
  10791. i, il = object.count * 3;
  10792. for( i = 0; i < il; i += 9 ) {
  10793. normalArray = object.normalArray;
  10794. nax = normalArray[ i ];
  10795. nay = normalArray[ i + 1 ];
  10796. naz = normalArray[ i + 2 ];
  10797. nbx = normalArray[ i + 3 ];
  10798. nby = normalArray[ i + 4 ];
  10799. nbz = normalArray[ i + 5 ];
  10800. ncx = normalArray[ i + 6 ];
  10801. ncy = normalArray[ i + 7 ];
  10802. ncz = normalArray[ i + 8 ];
  10803. nx = ( nax + nbx + ncx ) / 3;
  10804. ny = ( nay + nby + ncy ) / 3;
  10805. nz = ( naz + nbz + ncz ) / 3;
  10806. normalArray[ i ] = nx;
  10807. normalArray[ i + 1 ] = ny;
  10808. normalArray[ i + 2 ] = nz;
  10809. normalArray[ i + 3 ] = nx;
  10810. normalArray[ i + 4 ] = ny;
  10811. normalArray[ i + 5 ] = nz;
  10812. normalArray[ i + 6 ] = nx;
  10813. normalArray[ i + 7 ] = ny;
  10814. normalArray[ i + 8 ] = nz;
  10815. }
  10816. }
  10817. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  10818. _gl.enableVertexAttribArray( program.attributes.normal );
  10819. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  10820. }
  10821. if ( object.hasUvs && material.map ) {
  10822. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  10823. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  10824. _gl.enableVertexAttribArray( program.attributes.uv );
  10825. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  10826. }
  10827. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  10828. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  10829. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  10830. _gl.enableVertexAttribArray( program.attributes.color );
  10831. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  10832. }
  10833. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  10834. object.count = 0;
  10835. };
  10836. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  10837. if ( material.visible === false ) return;
  10838. var program, attributes, linewidth, primitives, a, attribute;
  10839. program = setProgram( camera, lights, fog, material, object );
  10840. attributes = program.attributes;
  10841. var updateBuffers = false,
  10842. wireframeBit = material.wireframe ? 1 : 0,
  10843. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  10844. if ( geometryHash !== _currentGeometryGroupHash ) {
  10845. _currentGeometryGroupHash = geometryHash;
  10846. updateBuffers = true;
  10847. }
  10848. // render mesh
  10849. if ( object instanceof THREE.Mesh ) {
  10850. var offsets = geometry.offsets;
  10851. // if there is more than 1 chunk
  10852. // must set attribute pointers to use new offsets for each chunk
  10853. // even if geometry and materials didn't change
  10854. if ( offsets.length > 1 ) updateBuffers = true;
  10855. for ( var i = 0, il = offsets.length; i < il; ++ i ) {
  10856. var startIndex = offsets[ i ].index;
  10857. if ( updateBuffers ) {
  10858. // vertices
  10859. var position = geometry.attributes[ "position" ];
  10860. var positionSize = position.itemSize;
  10861. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  10862. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  10863. // normals
  10864. var normal = geometry.attributes[ "normal" ];
  10865. if ( attributes.normal >= 0 && normal ) {
  10866. var normalSize = normal.itemSize;
  10867. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  10868. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  10869. }
  10870. // uvs
  10871. var uv = geometry.attributes[ "uv" ];
  10872. if ( attributes.uv >= 0 && uv ) {
  10873. if ( uv.buffer ) {
  10874. var uvSize = uv.itemSize;
  10875. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  10876. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  10877. _gl.enableVertexAttribArray( attributes.uv );
  10878. } else {
  10879. _gl.disableVertexAttribArray( attributes.uv );
  10880. }
  10881. }
  10882. // colors
  10883. var color = geometry.attributes[ "color" ];
  10884. if ( attributes.color >= 0 && color ) {
  10885. var colorSize = color.itemSize;
  10886. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  10887. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  10888. }
  10889. // tangents
  10890. var tangent = geometry.attributes[ "tangent" ];
  10891. if ( attributes.tangent >= 0 && tangent ) {
  10892. var tangentSize = tangent.itemSize;
  10893. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  10894. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  10895. }
  10896. // indices
  10897. var index = geometry.attributes[ "index" ];
  10898. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  10899. }
  10900. // render indexed triangles
  10901. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  10902. _this.info.render.calls ++;
  10903. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  10904. _this.info.render.faces += offsets[ i ].count / 3;
  10905. }
  10906. }
  10907. };
  10908. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  10909. if ( material.visible === false ) return;
  10910. var program, attributes, linewidth, primitives, a, attribute, i, il;
  10911. program = setProgram( camera, lights, fog, material, object );
  10912. attributes = program.attributes;
  10913. var updateBuffers = false,
  10914. wireframeBit = material.wireframe ? 1 : 0,
  10915. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  10916. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  10917. _currentGeometryGroupHash = geometryGroupHash;
  10918. updateBuffers = true;
  10919. }
  10920. // vertices
  10921. if ( !material.morphTargets && attributes.position >= 0 ) {
  10922. if ( updateBuffers ) {
  10923. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  10924. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  10925. }
  10926. } else {
  10927. if ( object.morphTargetBase ) {
  10928. setupMorphTargets( material, geometryGroup, object );
  10929. }
  10930. }
  10931. if ( updateBuffers ) {
  10932. // custom attributes
  10933. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  10934. if ( geometryGroup.__webglCustomAttributesList ) {
  10935. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  10936. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  10937. if( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  10938. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  10939. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  10940. }
  10941. }
  10942. }
  10943. // colors
  10944. if ( attributes.color >= 0 ) {
  10945. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  10946. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  10947. }
  10948. // normals
  10949. if ( attributes.normal >= 0 ) {
  10950. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  10951. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  10952. }
  10953. // tangents
  10954. if ( attributes.tangent >= 0 ) {
  10955. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  10956. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  10957. }
  10958. // uvs
  10959. if ( attributes.uv >= 0 ) {
  10960. if ( geometryGroup.__webglUVBuffer ) {
  10961. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  10962. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  10963. _gl.enableVertexAttribArray( attributes.uv );
  10964. } else {
  10965. _gl.disableVertexAttribArray( attributes.uv );
  10966. }
  10967. }
  10968. if ( attributes.uv2 >= 0 ) {
  10969. if ( geometryGroup.__webglUV2Buffer ) {
  10970. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  10971. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  10972. _gl.enableVertexAttribArray( attributes.uv2 );
  10973. } else {
  10974. _gl.disableVertexAttribArray( attributes.uv2 );
  10975. }
  10976. }
  10977. if ( material.skinning &&
  10978. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  10979. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  10980. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  10981. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  10982. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  10983. }
  10984. }
  10985. // render mesh
  10986. if ( object instanceof THREE.Mesh ) {
  10987. // wireframe
  10988. if ( material.wireframe ) {
  10989. setLineWidth( material.wireframeLinewidth );
  10990. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  10991. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  10992. // triangles
  10993. } else {
  10994. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  10995. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  10996. }
  10997. _this.info.render.calls ++;
  10998. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  10999. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  11000. // render lines
  11001. } else if ( object instanceof THREE.Line ) {
  11002. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  11003. setLineWidth( material.linewidth );
  11004. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  11005. _this.info.render.calls ++;
  11006. // render particles
  11007. } else if ( object instanceof THREE.ParticleSystem ) {
  11008. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  11009. _this.info.render.calls ++;
  11010. _this.info.render.points += geometryGroup.__webglParticleCount;
  11011. // render ribbon
  11012. } else if ( object instanceof THREE.Ribbon ) {
  11013. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  11014. _this.info.render.calls ++;
  11015. }
  11016. };
  11017. function setupMorphTargets ( material, geometryGroup, object ) {
  11018. // set base
  11019. var attributes = material.program.attributes;
  11020. if ( object.morphTargetBase !== -1 ) {
  11021. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  11022. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11023. } else if ( attributes.position >= 0 ) {
  11024. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11025. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11026. }
  11027. if ( object.morphTargetForcedOrder.length ) {
  11028. // set forced order
  11029. var m = 0;
  11030. var order = object.morphTargetForcedOrder;
  11031. var influences = object.morphTargetInfluences;
  11032. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  11033. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  11034. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11035. if ( material.morphNormals ) {
  11036. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  11037. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11038. }
  11039. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  11040. m ++;
  11041. }
  11042. } else {
  11043. // find the most influencing
  11044. var influence, activeInfluenceIndices = [];
  11045. var influences = object.morphTargetInfluences;
  11046. var i, il = influences.length;
  11047. for ( i = 0; i < il; i ++ ) {
  11048. influence = influences[ i ];
  11049. if ( influence > 0 ) {
  11050. activeInfluenceIndices.push( [ i, influence ] );
  11051. }
  11052. }
  11053. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  11054. activeInfluenceIndices.sort( numericalSort );
  11055. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  11056. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  11057. activeInfluenceIndices.sort( numericalSort );
  11058. } else if ( activeInfluenceIndices.length === 0 ) {
  11059. activeInfluenceIndices.push( [ 0, 0 ] );
  11060. };
  11061. var influenceIndex, m = 0;
  11062. while ( m < material.numSupportedMorphTargets ) {
  11063. if ( activeInfluenceIndices[ m ] ) {
  11064. influenceIndex = activeInfluenceIndices[ m ][ 0 ];
  11065. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  11066. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11067. if ( material.morphNormals ) {
  11068. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  11069. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11070. }
  11071. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  11072. } else {
  11073. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11074. if ( material.morphNormals ) {
  11075. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11076. }
  11077. object.__webglMorphTargetInfluences[ m ] = 0;
  11078. }
  11079. m ++;
  11080. }
  11081. }
  11082. // load updated influences uniform
  11083. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  11084. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  11085. }
  11086. };
  11087. // Sorting
  11088. function painterSort ( a, b ) {
  11089. return b.z - a.z;
  11090. };
  11091. function numericalSort ( a, b ) {
  11092. return b[ 1 ] - a[ 1 ];
  11093. };
  11094. // Rendering
  11095. this.render = function ( scene, camera, renderTarget, forceClear ) {
  11096. if ( camera instanceof THREE.Camera === false ) {
  11097. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  11098. return;
  11099. }
  11100. var i, il,
  11101. webglObject, object,
  11102. renderList,
  11103. lights = scene.__lights,
  11104. fog = scene.fog;
  11105. // reset caching for this frame
  11106. _currentMaterialId = -1;
  11107. _lightsNeedUpdate = true;
  11108. // update scene graph
  11109. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  11110. // update camera matrices and frustum
  11111. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  11112. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  11113. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  11114. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  11115. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  11116. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  11117. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  11118. _frustum.setFromMatrix( _projScreenMatrix );
  11119. // update WebGL objects
  11120. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  11121. // custom render plugins (pre pass)
  11122. renderPlugins( this.renderPluginsPre, scene, camera );
  11123. //
  11124. _this.info.render.calls = 0;
  11125. _this.info.render.vertices = 0;
  11126. _this.info.render.faces = 0;
  11127. _this.info.render.points = 0;
  11128. this.setRenderTarget( renderTarget );
  11129. if ( this.autoClear || forceClear ) {
  11130. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  11131. }
  11132. // set matrices for regular objects (frustum culled)
  11133. renderList = scene.__webglObjects;
  11134. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11135. webglObject = renderList[ i ];
  11136. object = webglObject.object;
  11137. webglObject.render = false;
  11138. if ( object.visible ) {
  11139. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  11140. //object.matrixWorld.flattenToArray( object._modelMatrixArray );
  11141. setupMatrices( object, camera );
  11142. unrollBufferMaterial( webglObject );
  11143. webglObject.render = true;
  11144. if ( this.sortObjects ) {
  11145. if ( object.renderDepth ) {
  11146. webglObject.z = object.renderDepth;
  11147. } else {
  11148. _vector3.copy( object.matrixWorld.getPosition() );
  11149. _projScreenMatrix.multiplyVector3( _vector3 );
  11150. webglObject.z = _vector3.z;
  11151. }
  11152. }
  11153. }
  11154. }
  11155. }
  11156. if ( this.sortObjects ) {
  11157. renderList.sort( painterSort );
  11158. }
  11159. // set matrices for immediate objects
  11160. renderList = scene.__webglObjectsImmediate;
  11161. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11162. webglObject = renderList[ i ];
  11163. object = webglObject.object;
  11164. if ( object.visible ) {
  11165. /*
  11166. if ( object.matrixAutoUpdate ) {
  11167. object.matrixWorld.flattenToArray( object._modelMatrixArray );
  11168. }
  11169. */
  11170. setupMatrices( object, camera );
  11171. unrollImmediateBufferMaterial( webglObject );
  11172. }
  11173. }
  11174. if ( scene.overrideMaterial ) {
  11175. var material = scene.overrideMaterial;
  11176. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11177. this.setDepthTest( material.depthTest );
  11178. this.setDepthWrite( material.depthWrite );
  11179. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11180. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  11181. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  11182. } else {
  11183. // opaque pass (front-to-back order)
  11184. this.setBlending( THREE.NormalBlending );
  11185. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false );
  11186. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false );
  11187. // transparent pass (back-to-front order)
  11188. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true );
  11189. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true );
  11190. }
  11191. // custom render plugins (post pass)
  11192. renderPlugins( this.renderPluginsPost, scene, camera );
  11193. // Generate mipmap if we're using any kind of mipmap filtering
  11194. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  11195. updateRenderTargetMipmap( renderTarget );
  11196. }
  11197. // Ensure depth buffer writing is enabled so it can be cleared on next render
  11198. this.setDepthTest( true );
  11199. this.setDepthWrite( true );
  11200. // _gl.finish();
  11201. };
  11202. function renderPlugins( plugins, scene, camera ) {
  11203. if ( ! plugins.length ) return;
  11204. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  11205. // reset state for plugin (to start from clean slate)
  11206. _currentProgram = null;
  11207. _currentCamera = null;
  11208. _oldBlending = -1;
  11209. _oldDepthTest = -1;
  11210. _oldDepthWrite = -1;
  11211. _oldDoubleSided = -1;
  11212. _oldFlipSided = -1;
  11213. _currentGeometryGroupHash = -1;
  11214. _currentMaterialId = -1;
  11215. _lightsNeedUpdate = true;
  11216. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  11217. // reset state after plugin (anything could have changed)
  11218. _currentProgram = null;
  11219. _currentCamera = null;
  11220. _oldBlending = -1;
  11221. _oldDepthTest = -1;
  11222. _oldDepthWrite = -1;
  11223. _oldDoubleSided = -1;
  11224. _oldFlipSided = -1;
  11225. _currentGeometryGroupHash = -1;
  11226. _currentMaterialId = -1;
  11227. _lightsNeedUpdate = true;
  11228. }
  11229. };
  11230. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11231. var webglObject, object, buffer, material, start, end, delta;
  11232. if ( reverse ) {
  11233. start = renderList.length - 1;
  11234. end = -1;
  11235. delta = -1;
  11236. } else {
  11237. start = 0;
  11238. end = renderList.length;
  11239. delta = 1;
  11240. }
  11241. for ( var i = start; i !== end; i += delta ) {
  11242. webglObject = renderList[ i ];
  11243. if ( webglObject.render ) {
  11244. object = webglObject.object;
  11245. buffer = webglObject.buffer;
  11246. if ( overrideMaterial ) {
  11247. material = overrideMaterial;
  11248. } else {
  11249. material = webglObject[ materialType ];
  11250. if ( ! material ) continue;
  11251. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11252. _this.setDepthTest( material.depthTest );
  11253. _this.setDepthWrite( material.depthWrite );
  11254. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11255. }
  11256. _this.setMaterialFaces( material );
  11257. if ( buffer instanceof THREE.BufferGeometry ) {
  11258. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  11259. } else {
  11260. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  11261. }
  11262. }
  11263. }
  11264. };
  11265. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11266. var webglObject, object, material, program;
  11267. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  11268. webglObject = renderList[ i ];
  11269. object = webglObject.object;
  11270. if ( object.visible ) {
  11271. if ( overrideMaterial ) {
  11272. material = overrideMaterial;
  11273. } else {
  11274. material = webglObject[ materialType ];
  11275. if ( ! material ) continue;
  11276. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11277. _this.setDepthTest( material.depthTest );
  11278. _this.setDepthWrite( material.depthWrite );
  11279. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11280. }
  11281. _this.renderImmediateObject( camera, lights, fog, material, object );
  11282. }
  11283. }
  11284. };
  11285. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  11286. var program = setProgram( camera, lights, fog, material, object );
  11287. _currentGeometryGroupHash = -1;
  11288. _this.setMaterialFaces( material );
  11289. if ( object.immediateRenderCallback ) {
  11290. object.immediateRenderCallback( program, _gl, _frustum );
  11291. } else {
  11292. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  11293. }
  11294. };
  11295. function unrollImmediateBufferMaterial ( globject ) {
  11296. var object = globject.object,
  11297. material = object.material;
  11298. if ( material.transparent ) {
  11299. globject.transparent = material;
  11300. globject.opaque = null;
  11301. } else {
  11302. globject.opaque = material;
  11303. globject.transparent = null;
  11304. }
  11305. };
  11306. function unrollBufferMaterial ( globject ) {
  11307. var object = globject.object,
  11308. buffer = globject.buffer,
  11309. material, materialIndex, meshMaterial;
  11310. meshMaterial = object.material;
  11311. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  11312. materialIndex = buffer.materialIndex;
  11313. if ( materialIndex >= 0 ) {
  11314. material = object.geometry.materials[ materialIndex ];
  11315. if ( material.transparent ) {
  11316. globject.transparent = material;
  11317. globject.opaque = null;
  11318. } else {
  11319. globject.opaque = material;
  11320. globject.transparent = null;
  11321. }
  11322. }
  11323. } else {
  11324. material = meshMaterial;
  11325. if ( material ) {
  11326. if ( material.transparent ) {
  11327. globject.transparent = material;
  11328. globject.opaque = null;
  11329. } else {
  11330. globject.opaque = material;
  11331. globject.transparent = null;
  11332. }
  11333. }
  11334. }
  11335. };
  11336. // Geometry splitting
  11337. function sortFacesByMaterial ( geometry ) {
  11338. var f, fl, face, materialIndex, vertices,
  11339. materialHash, groupHash,
  11340. hash_map = {};
  11341. var numMorphTargets = geometry.morphTargets.length;
  11342. var numMorphNormals = geometry.morphNormals.length;
  11343. geometry.geometryGroups = {};
  11344. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  11345. face = geometry.faces[ f ];
  11346. materialIndex = face.materialIndex;
  11347. materialHash = ( materialIndex !== undefined ) ? materialIndex : -1;
  11348. if ( hash_map[ materialHash ] === undefined ) {
  11349. hash_map[ materialHash ] = { 'hash': materialHash, 'counter': 0 };
  11350. }
  11351. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  11352. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  11353. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  11354. }
  11355. vertices = face instanceof THREE.Face3 ? 3 : 4;
  11356. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  11357. hash_map[ materialHash ].counter += 1;
  11358. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  11359. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  11360. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  11361. }
  11362. }
  11363. if ( face instanceof THREE.Face3 ) {
  11364. geometry.geometryGroups[ groupHash ].faces3.push( f );
  11365. } else {
  11366. geometry.geometryGroups[ groupHash ].faces4.push( f );
  11367. }
  11368. geometry.geometryGroups[ groupHash ].vertices += vertices;
  11369. }
  11370. geometry.geometryGroupsList = [];
  11371. for ( var g in geometry.geometryGroups ) {
  11372. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  11373. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  11374. }
  11375. };
  11376. // Objects refresh
  11377. this.initWebGLObjects = function ( scene ) {
  11378. if ( !scene.__webglObjects ) {
  11379. scene.__webglObjects = [];
  11380. scene.__webglObjectsImmediate = [];
  11381. scene.__webglSprites = [];
  11382. scene.__webglFlares = [];
  11383. }
  11384. while ( scene.__objectsAdded.length ) {
  11385. addObject( scene.__objectsAdded[ 0 ], scene );
  11386. scene.__objectsAdded.splice( 0, 1 );
  11387. }
  11388. while ( scene.__objectsRemoved.length ) {
  11389. removeObject( scene.__objectsRemoved[ 0 ], scene );
  11390. scene.__objectsRemoved.splice( 0, 1 );
  11391. }
  11392. // update must be called after objects adding / removal
  11393. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  11394. updateObject( scene.__webglObjects[ o ].object );
  11395. }
  11396. };
  11397. // Objects adding
  11398. function addObject ( object, scene ) {
  11399. var g, geometry, geometryGroup;
  11400. if ( ! object.__webglInit ) {
  11401. object.__webglInit = true;
  11402. object._modelViewMatrix = new THREE.Matrix4();
  11403. object._normalMatrix = new THREE.Matrix3();
  11404. if ( object instanceof THREE.Mesh ) {
  11405. geometry = object.geometry;
  11406. if ( geometry instanceof THREE.Geometry ) {
  11407. if ( geometry.geometryGroups === undefined ) {
  11408. sortFacesByMaterial( geometry );
  11409. }
  11410. // create separate VBOs per geometry chunk
  11411. for ( g in geometry.geometryGroups ) {
  11412. geometryGroup = geometry.geometryGroups[ g ];
  11413. // initialise VBO on the first access
  11414. if ( ! geometryGroup.__webglVertexBuffer ) {
  11415. createMeshBuffers( geometryGroup );
  11416. initMeshBuffers( geometryGroup, object );
  11417. geometry.verticesNeedUpdate = true;
  11418. geometry.morphTargetsNeedUpdate = true;
  11419. geometry.elementsNeedUpdate = true;
  11420. geometry.uvsNeedUpdate = true;
  11421. geometry.normalsNeedUpdate = true;
  11422. geometry.tangentsNeedUpdate = true;
  11423. geometry.colorsNeedUpdate = true;
  11424. }
  11425. }
  11426. } else if ( geometry instanceof THREE.BufferGeometry ) {
  11427. initDirectBuffers( geometry );
  11428. }
  11429. } else if ( object instanceof THREE.Ribbon ) {
  11430. geometry = object.geometry;
  11431. if( ! geometry.__webglVertexBuffer ) {
  11432. createRibbonBuffers( geometry );
  11433. initRibbonBuffers( geometry );
  11434. geometry.verticesNeedUpdate = true;
  11435. geometry.colorsNeedUpdate = true;
  11436. }
  11437. } else if ( object instanceof THREE.Line ) {
  11438. geometry = object.geometry;
  11439. if( ! geometry.__webglVertexBuffer ) {
  11440. createLineBuffers( geometry );
  11441. initLineBuffers( geometry, object );
  11442. geometry.verticesNeedUpdate = true;
  11443. geometry.colorsNeedUpdate = true;
  11444. }
  11445. } else if ( object instanceof THREE.ParticleSystem ) {
  11446. geometry = object.geometry;
  11447. if ( ! geometry.__webglVertexBuffer ) {
  11448. createParticleBuffers( geometry );
  11449. initParticleBuffers( geometry, object );
  11450. geometry.verticesNeedUpdate = true;
  11451. geometry.colorsNeedUpdate = true;
  11452. }
  11453. }
  11454. }
  11455. if ( ! object.__webglActive ) {
  11456. if ( object instanceof THREE.Mesh ) {
  11457. geometry = object.geometry;
  11458. if ( geometry instanceof THREE.BufferGeometry ) {
  11459. addBuffer( scene.__webglObjects, geometry, object );
  11460. } else {
  11461. for ( g in geometry.geometryGroups ) {
  11462. geometryGroup = geometry.geometryGroups[ g ];
  11463. addBuffer( scene.__webglObjects, geometryGroup, object );
  11464. }
  11465. }
  11466. } else if ( object instanceof THREE.Ribbon ||
  11467. object instanceof THREE.Line ||
  11468. object instanceof THREE.ParticleSystem ) {
  11469. geometry = object.geometry;
  11470. addBuffer( scene.__webglObjects, geometry, object );
  11471. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  11472. addBufferImmediate( scene.__webglObjectsImmediate, object );
  11473. } else if ( object instanceof THREE.Sprite ) {
  11474. scene.__webglSprites.push( object );
  11475. } else if ( object instanceof THREE.LensFlare ) {
  11476. scene.__webglFlares.push( object );
  11477. }
  11478. object.__webglActive = true;
  11479. }
  11480. };
  11481. function addBuffer ( objlist, buffer, object ) {
  11482. objlist.push(
  11483. {
  11484. buffer: buffer,
  11485. object: object,
  11486. opaque: null,
  11487. transparent: null
  11488. }
  11489. );
  11490. };
  11491. function addBufferImmediate ( objlist, object ) {
  11492. objlist.push(
  11493. {
  11494. object: object,
  11495. opaque: null,
  11496. transparent: null
  11497. }
  11498. );
  11499. };
  11500. // Objects updates
  11501. function updateObject ( object ) {
  11502. var geometry = object.geometry,
  11503. geometryGroup, customAttributesDirty, material;
  11504. if ( object instanceof THREE.Mesh ) {
  11505. if ( geometry instanceof THREE.BufferGeometry ) {
  11506. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  11507. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  11508. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  11509. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  11510. }
  11511. geometry.verticesNeedUpdate = false;
  11512. geometry.elementsNeedUpdate = false;
  11513. geometry.uvsNeedUpdate = false;
  11514. geometry.normalsNeedUpdate = false;
  11515. geometry.colorsNeedUpdate = false;
  11516. geometry.tangentsNeedUpdate = false;
  11517. } else {
  11518. // check all geometry groups
  11519. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  11520. geometryGroup = geometry.geometryGroupsList[ i ];
  11521. material = getBufferMaterial( object, geometryGroup );
  11522. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11523. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  11524. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  11525. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  11526. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  11527. }
  11528. }
  11529. geometry.verticesNeedUpdate = false;
  11530. geometry.morphTargetsNeedUpdate = false;
  11531. geometry.elementsNeedUpdate = false;
  11532. geometry.uvsNeedUpdate = false;
  11533. geometry.normalsNeedUpdate = false;
  11534. geometry.colorsNeedUpdate = false;
  11535. geometry.tangentsNeedUpdate = false;
  11536. material.attributes && clearCustomAttributes( material );
  11537. }
  11538. } else if ( object instanceof THREE.Ribbon ) {
  11539. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  11540. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  11541. }
  11542. geometry.verticesNeedUpdate = false;
  11543. geometry.colorsNeedUpdate = false;
  11544. } else if ( object instanceof THREE.Line ) {
  11545. material = getBufferMaterial( object, geometryGroup );
  11546. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11547. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || customAttributesDirty ) {
  11548. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  11549. }
  11550. geometry.verticesNeedUpdate = false;
  11551. geometry.colorsNeedUpdate = false;
  11552. material.attributes && clearCustomAttributes( material );
  11553. } else if ( object instanceof THREE.ParticleSystem ) {
  11554. material = getBufferMaterial( object, geometryGroup );
  11555. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11556. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  11557. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  11558. }
  11559. geometry.verticesNeedUpdate = false;
  11560. geometry.colorsNeedUpdate = false;
  11561. material.attributes && clearCustomAttributes( material );
  11562. }
  11563. };
  11564. // Objects updates - custom attributes check
  11565. function areCustomAttributesDirty ( material ) {
  11566. for ( var a in material.attributes ) {
  11567. if ( material.attributes[ a ].needsUpdate ) return true;
  11568. }
  11569. return false;
  11570. };
  11571. function clearCustomAttributes ( material ) {
  11572. for ( var a in material.attributes ) {
  11573. material.attributes[ a ].needsUpdate = false;
  11574. }
  11575. };
  11576. // Objects removal
  11577. function removeObject ( object, scene ) {
  11578. if ( object instanceof THREE.Mesh ||
  11579. object instanceof THREE.ParticleSystem ||
  11580. object instanceof THREE.Ribbon ||
  11581. object instanceof THREE.Line ) {
  11582. removeInstances( scene.__webglObjects, object );
  11583. } else if ( object instanceof THREE.Sprite ) {
  11584. removeInstancesDirect( scene.__webglSprites, object );
  11585. } else if ( object instanceof THREE.LensFlare ) {
  11586. removeInstancesDirect( scene.__webglFlares, object );
  11587. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  11588. removeInstances( scene.__webglObjectsImmediate, object );
  11589. }
  11590. object.__webglActive = false;
  11591. };
  11592. function removeInstances ( objlist, object ) {
  11593. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  11594. if ( objlist[ o ].object === object ) {
  11595. objlist.splice( o, 1 );
  11596. }
  11597. }
  11598. };
  11599. function removeInstancesDirect ( objlist, object ) {
  11600. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  11601. if ( objlist[ o ] === object ) {
  11602. objlist.splice( o, 1 );
  11603. }
  11604. }
  11605. };
  11606. // Materials
  11607. this.initMaterial = function ( material, lights, fog, object ) {
  11608. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  11609. if ( material instanceof THREE.MeshDepthMaterial ) {
  11610. shaderID = 'depth';
  11611. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  11612. shaderID = 'normal';
  11613. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  11614. shaderID = 'basic';
  11615. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  11616. shaderID = 'lambert';
  11617. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  11618. shaderID = 'phong';
  11619. } else if ( material instanceof THREE.LineBasicMaterial ) {
  11620. shaderID = 'basic';
  11621. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  11622. shaderID = 'particle_basic';
  11623. }
  11624. if ( shaderID ) {
  11625. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  11626. }
  11627. // heuristics to create shader parameters according to lights in the scene
  11628. // (not to blow over maxLights budget)
  11629. maxLightCount = allocateLights( lights );
  11630. maxShadows = allocateShadows( lights );
  11631. maxBones = allocateBones( object );
  11632. parameters = {
  11633. map: !!material.map,
  11634. envMap: !!material.envMap,
  11635. lightMap: !!material.lightMap,
  11636. bumpMap: !!material.bumpMap,
  11637. specularMap: !!material.specularMap,
  11638. vertexColors: material.vertexColors,
  11639. fog: fog,
  11640. useFog: material.fog,
  11641. sizeAttenuation: material.sizeAttenuation,
  11642. skinning: material.skinning,
  11643. maxBones: maxBones,
  11644. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  11645. boneTextureWidth: object && object.boneTextureWidth,
  11646. boneTextureHeight: object && object.boneTextureHeight,
  11647. morphTargets: material.morphTargets,
  11648. morphNormals: material.morphNormals,
  11649. maxMorphTargets: this.maxMorphTargets,
  11650. maxMorphNormals: this.maxMorphNormals,
  11651. maxDirLights: maxLightCount.directional,
  11652. maxPointLights: maxLightCount.point,
  11653. maxSpotLights: maxLightCount.spot,
  11654. maxHemiLights: maxLightCount.hemi,
  11655. maxShadows: maxShadows,
  11656. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  11657. shadowMapSoft: this.shadowMapSoft,
  11658. shadowMapDebug: this.shadowMapDebug,
  11659. shadowMapCascade: this.shadowMapCascade,
  11660. alphaTest: material.alphaTest,
  11661. metal: material.metal,
  11662. perPixel: material.perPixel,
  11663. wrapAround: material.wrapAround,
  11664. doubleSided: material.side === THREE.DoubleSide
  11665. };
  11666. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, parameters );
  11667. var attributes = material.program.attributes;
  11668. if ( attributes.position >= 0 ) _gl.enableVertexAttribArray( attributes.position );
  11669. if ( attributes.color >= 0 ) _gl.enableVertexAttribArray( attributes.color );
  11670. if ( attributes.normal >= 0 ) _gl.enableVertexAttribArray( attributes.normal );
  11671. if ( attributes.tangent >= 0 ) _gl.enableVertexAttribArray( attributes.tangent );
  11672. if ( material.skinning &&
  11673. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  11674. _gl.enableVertexAttribArray( attributes.skinIndex );
  11675. _gl.enableVertexAttribArray( attributes.skinWeight );
  11676. }
  11677. if ( material.attributes ) {
  11678. for ( a in material.attributes ) {
  11679. if( attributes[ a ] !== undefined && attributes[ a ] >= 0 ) _gl.enableVertexAttribArray( attributes[ a ] );
  11680. }
  11681. }
  11682. if ( material.morphTargets ) {
  11683. material.numSupportedMorphTargets = 0;
  11684. var id, base = "morphTarget";
  11685. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  11686. id = base + i;
  11687. if ( attributes[ id ] >= 0 ) {
  11688. _gl.enableVertexAttribArray( attributes[ id ] );
  11689. material.numSupportedMorphTargets ++;
  11690. }
  11691. }
  11692. }
  11693. if ( material.morphNormals ) {
  11694. material.numSupportedMorphNormals = 0;
  11695. var id, base = "morphNormal";
  11696. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  11697. id = base + i;
  11698. if ( attributes[ id ] >= 0 ) {
  11699. _gl.enableVertexAttribArray( attributes[ id ] );
  11700. material.numSupportedMorphNormals ++;
  11701. }
  11702. }
  11703. }
  11704. material.uniformsList = [];
  11705. for ( u in material.uniforms ) {
  11706. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  11707. }
  11708. };
  11709. function setMaterialShaders( material, shaders ) {
  11710. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  11711. material.vertexShader = shaders.vertexShader;
  11712. material.fragmentShader = shaders.fragmentShader;
  11713. };
  11714. function setProgram( camera, lights, fog, material, object ) {
  11715. _usedTextureUnits = 0;
  11716. if ( material.needsUpdate ) {
  11717. if ( material.program ) _this.deallocateMaterial( material );
  11718. _this.initMaterial( material, lights, fog, object );
  11719. material.needsUpdate = false;
  11720. }
  11721. if ( material.morphTargets ) {
  11722. if ( ! object.__webglMorphTargetInfluences ) {
  11723. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  11724. }
  11725. }
  11726. var refreshMaterial = false;
  11727. var program = material.program,
  11728. p_uniforms = program.uniforms,
  11729. m_uniforms = material.uniforms;
  11730. if ( program !== _currentProgram ) {
  11731. _gl.useProgram( program );
  11732. _currentProgram = program;
  11733. refreshMaterial = true;
  11734. }
  11735. if ( material.id !== _currentMaterialId ) {
  11736. _currentMaterialId = material.id;
  11737. refreshMaterial = true;
  11738. }
  11739. if ( refreshMaterial || camera !== _currentCamera ) {
  11740. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  11741. if ( camera !== _currentCamera ) _currentCamera = camera;
  11742. }
  11743. // skinning uniforms must be set even if material didn't change
  11744. // auto-setting of texture unit for bone texture must go before other textures
  11745. // not sure why, but otherwise weird things happen
  11746. if ( material.skinning ) {
  11747. if ( _supportsBoneTextures && object.useVertexTexture ) {
  11748. if ( p_uniforms.boneTexture !== null ) {
  11749. var textureUnit = getTextureUnit();
  11750. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  11751. _this.setTexture( object.boneTexture, textureUnit );
  11752. }
  11753. } else {
  11754. if ( p_uniforms.boneGlobalMatrices !== null ) {
  11755. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  11756. }
  11757. }
  11758. }
  11759. if ( refreshMaterial ) {
  11760. // refresh uniforms common to several materials
  11761. if ( fog && material.fog ) {
  11762. refreshUniformsFog( m_uniforms, fog );
  11763. }
  11764. if ( material instanceof THREE.MeshPhongMaterial ||
  11765. material instanceof THREE.MeshLambertMaterial ||
  11766. material.lights ) {
  11767. if ( _lightsNeedUpdate ) {
  11768. setupLights( program, lights );
  11769. _lightsNeedUpdate = false;
  11770. }
  11771. refreshUniformsLights( m_uniforms, _lights );
  11772. }
  11773. if ( material instanceof THREE.MeshBasicMaterial ||
  11774. material instanceof THREE.MeshLambertMaterial ||
  11775. material instanceof THREE.MeshPhongMaterial ) {
  11776. refreshUniformsCommon( m_uniforms, material );
  11777. }
  11778. // refresh single material specific uniforms
  11779. if ( material instanceof THREE.LineBasicMaterial ) {
  11780. refreshUniformsLine( m_uniforms, material );
  11781. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  11782. refreshUniformsParticle( m_uniforms, material );
  11783. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  11784. refreshUniformsPhong( m_uniforms, material );
  11785. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  11786. refreshUniformsLambert( m_uniforms, material );
  11787. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  11788. m_uniforms.mNear.value = camera.near;
  11789. m_uniforms.mFar.value = camera.far;
  11790. m_uniforms.opacity.value = material.opacity;
  11791. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  11792. m_uniforms.opacity.value = material.opacity;
  11793. }
  11794. if ( object.receiveShadow && ! material._shadowPass ) {
  11795. refreshUniformsShadow( m_uniforms, lights );
  11796. }
  11797. // load common uniforms
  11798. loadUniformsGeneric( program, material.uniformsList );
  11799. // load material specific uniforms
  11800. // (shader material also gets them for the sake of genericity)
  11801. if ( material instanceof THREE.ShaderMaterial ||
  11802. material instanceof THREE.MeshPhongMaterial ||
  11803. material.envMap ) {
  11804. if ( p_uniforms.cameraPosition !== null ) {
  11805. var position = camera.matrixWorld.getPosition();
  11806. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  11807. }
  11808. }
  11809. if ( material instanceof THREE.MeshPhongMaterial ||
  11810. material instanceof THREE.MeshLambertMaterial ||
  11811. material instanceof THREE.ShaderMaterial ||
  11812. material.skinning ) {
  11813. if ( p_uniforms.viewMatrix !== null ) {
  11814. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera._viewMatrixArray );
  11815. }
  11816. }
  11817. }
  11818. loadUniformsMatrices( p_uniforms, object );
  11819. if ( p_uniforms.modelMatrix !== null ) {
  11820. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  11821. }
  11822. return program;
  11823. };
  11824. // Uniforms (refresh uniforms objects)
  11825. function refreshUniformsCommon ( uniforms, material ) {
  11826. uniforms.opacity.value = material.opacity;
  11827. if ( _this.gammaInput ) {
  11828. uniforms.diffuse.value.copyGammaToLinear( material.color );
  11829. } else {
  11830. uniforms.diffuse.value = material.color;
  11831. }
  11832. uniforms.map.value = material.map;
  11833. uniforms.lightMap.value = material.lightMap;
  11834. uniforms.specularMap.value = material.specularMap;
  11835. if ( material.bumpMap ) {
  11836. uniforms.bumpMap.value = material.bumpMap;
  11837. uniforms.bumpScale.value = material.bumpScale;
  11838. }
  11839. // uv repeat and offset setting priorities
  11840. // 1. color map
  11841. // 2. specular map
  11842. // 3. bump map
  11843. var uvScaleMap;
  11844. if ( material.map ) {
  11845. uvScaleMap = material.map;
  11846. } else if ( material.specularMap ) {
  11847. uvScaleMap = material.specularMap;
  11848. } else if ( material.bumpMap ) {
  11849. uvScaleMap = material.bumpMap;
  11850. }
  11851. if ( uvScaleMap !== undefined ) {
  11852. var offset = uvScaleMap.offset;
  11853. var repeat = uvScaleMap.repeat;
  11854. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  11855. }
  11856. uniforms.envMap.value = material.envMap;
  11857. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  11858. if ( _this.gammaInput ) {
  11859. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  11860. uniforms.reflectivity.value = material.reflectivity;
  11861. } else {
  11862. uniforms.reflectivity.value = material.reflectivity;
  11863. }
  11864. uniforms.refractionRatio.value = material.refractionRatio;
  11865. uniforms.combine.value = material.combine;
  11866. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  11867. };
  11868. function refreshUniformsLine ( uniforms, material ) {
  11869. uniforms.diffuse.value = material.color;
  11870. uniforms.opacity.value = material.opacity;
  11871. };
  11872. function refreshUniformsParticle ( uniforms, material ) {
  11873. uniforms.psColor.value = material.color;
  11874. uniforms.opacity.value = material.opacity;
  11875. uniforms.size.value = material.size;
  11876. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  11877. uniforms.map.value = material.map;
  11878. };
  11879. function refreshUniformsFog ( uniforms, fog ) {
  11880. uniforms.fogColor.value = fog.color;
  11881. if ( fog instanceof THREE.Fog ) {
  11882. uniforms.fogNear.value = fog.near;
  11883. uniforms.fogFar.value = fog.far;
  11884. } else if ( fog instanceof THREE.FogExp2 ) {
  11885. uniforms.fogDensity.value = fog.density;
  11886. }
  11887. };
  11888. function refreshUniformsPhong ( uniforms, material ) {
  11889. uniforms.shininess.value = material.shininess;
  11890. if ( _this.gammaInput ) {
  11891. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  11892. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  11893. uniforms.specular.value.copyGammaToLinear( material.specular );
  11894. } else {
  11895. uniforms.ambient.value = material.ambient;
  11896. uniforms.emissive.value = material.emissive;
  11897. uniforms.specular.value = material.specular;
  11898. }
  11899. if ( material.wrapAround ) {
  11900. uniforms.wrapRGB.value.copy( material.wrapRGB );
  11901. }
  11902. };
  11903. function refreshUniformsLambert ( uniforms, material ) {
  11904. if ( _this.gammaInput ) {
  11905. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  11906. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  11907. } else {
  11908. uniforms.ambient.value = material.ambient;
  11909. uniforms.emissive.value = material.emissive;
  11910. }
  11911. if ( material.wrapAround ) {
  11912. uniforms.wrapRGB.value.copy( material.wrapRGB );
  11913. }
  11914. };
  11915. function refreshUniformsLights ( uniforms, lights ) {
  11916. uniforms.ambientLightColor.value = lights.ambient;
  11917. uniforms.directionalLightColor.value = lights.directional.colors;
  11918. uniforms.directionalLightDirection.value = lights.directional.positions;
  11919. uniforms.pointLightColor.value = lights.point.colors;
  11920. uniforms.pointLightPosition.value = lights.point.positions;
  11921. uniforms.pointLightDistance.value = lights.point.distances;
  11922. uniforms.spotLightColor.value = lights.spot.colors;
  11923. uniforms.spotLightPosition.value = lights.spot.positions;
  11924. uniforms.spotLightDistance.value = lights.spot.distances;
  11925. uniforms.spotLightDirection.value = lights.spot.directions;
  11926. uniforms.spotLightAngle.value = lights.spot.angles;
  11927. uniforms.spotLightExponent.value = lights.spot.exponents;
  11928. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  11929. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  11930. uniforms.hemisphereLightPosition.value = lights.hemi.positions;
  11931. };
  11932. function refreshUniformsShadow ( uniforms, lights ) {
  11933. if ( uniforms.shadowMatrix ) {
  11934. var j = 0;
  11935. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  11936. var light = lights[ i ];
  11937. if ( ! light.castShadow ) continue;
  11938. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  11939. uniforms.shadowMap.value[ j ] = light.shadowMap;
  11940. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  11941. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  11942. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  11943. uniforms.shadowBias.value[ j ] = light.shadowBias;
  11944. j ++;
  11945. }
  11946. }
  11947. }
  11948. };
  11949. // Uniforms (load to GPU)
  11950. function loadUniformsMatrices ( uniforms, object ) {
  11951. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  11952. if ( uniforms.normalMatrix ) {
  11953. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  11954. }
  11955. };
  11956. function getTextureUnit() {
  11957. var textureUnit = _usedTextureUnits;
  11958. if ( textureUnit >= _maxTextures ) {
  11959. console.warn( "Trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  11960. }
  11961. _usedTextureUnits += 1;
  11962. return textureUnit;
  11963. };
  11964. function loadUniformsGeneric ( program, uniforms ) {
  11965. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  11966. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  11967. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  11968. if ( !location ) continue;
  11969. uniform = uniforms[ j ][ 0 ];
  11970. type = uniform.type;
  11971. value = uniform.value;
  11972. if ( type === "i" ) { // single integer
  11973. _gl.uniform1i( location, value );
  11974. } else if ( type === "f" ) { // single float
  11975. _gl.uniform1f( location, value );
  11976. } else if ( type === "v2" ) { // single THREE.Vector2
  11977. _gl.uniform2f( location, value.x, value.y );
  11978. } else if ( type === "v3" ) { // single THREE.Vector3
  11979. _gl.uniform3f( location, value.x, value.y, value.z );
  11980. } else if ( type === "v4" ) { // single THREE.Vector4
  11981. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  11982. } else if ( type === "c" ) { // single THREE.Color
  11983. _gl.uniform3f( location, value.r, value.g, value.b );
  11984. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  11985. _gl.uniform1iv( location, value );
  11986. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  11987. _gl.uniform3iv( location, value );
  11988. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  11989. _gl.uniform1fv( location, value );
  11990. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  11991. _gl.uniform3fv( location, value );
  11992. } else if ( type === "v2v" ) { // array of THREE.Vector2
  11993. if ( uniform._array === undefined ) {
  11994. uniform._array = new Float32Array( 2 * value.length );
  11995. }
  11996. for ( i = 0, il = value.length; i < il; i ++ ) {
  11997. offset = i * 2;
  11998. uniform._array[ offset ] = value[ i ].x;
  11999. uniform._array[ offset + 1 ] = value[ i ].y;
  12000. }
  12001. _gl.uniform2fv( location, uniform._array );
  12002. } else if ( type === "v3v" ) { // array of THREE.Vector3
  12003. if ( uniform._array === undefined ) {
  12004. uniform._array = new Float32Array( 3 * value.length );
  12005. }
  12006. for ( i = 0, il = value.length; i < il; i ++ ) {
  12007. offset = i * 3;
  12008. uniform._array[ offset ] = value[ i ].x;
  12009. uniform._array[ offset + 1 ] = value[ i ].y;
  12010. uniform._array[ offset + 2 ] = value[ i ].z;
  12011. }
  12012. _gl.uniform3fv( location, uniform._array );
  12013. } else if ( type === "v4v" ) { // array of THREE.Vector4
  12014. if ( uniform._array === undefined ) {
  12015. uniform._array = new Float32Array( 4 * value.length );
  12016. }
  12017. for ( i = 0, il = value.length; i < il; i ++ ) {
  12018. offset = i * 4;
  12019. uniform._array[ offset ] = value[ i ].x;
  12020. uniform._array[ offset + 1 ] = value[ i ].y;
  12021. uniform._array[ offset + 2 ] = value[ i ].z;
  12022. uniform._array[ offset + 3 ] = value[ i ].w;
  12023. }
  12024. _gl.uniform4fv( location, uniform._array );
  12025. } else if ( type === "m4") { // single THREE.Matrix4
  12026. if ( uniform._array === undefined ) {
  12027. uniform._array = new Float32Array( 16 );
  12028. }
  12029. value.flattenToArray( uniform._array );
  12030. _gl.uniformMatrix4fv( location, false, uniform._array );
  12031. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  12032. if ( uniform._array === undefined ) {
  12033. uniform._array = new Float32Array( 16 * value.length );
  12034. }
  12035. for ( i = 0, il = value.length; i < il; i ++ ) {
  12036. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  12037. }
  12038. _gl.uniformMatrix4fv( location, false, uniform._array );
  12039. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  12040. texture = value;
  12041. textureUnit = getTextureUnit();
  12042. _gl.uniform1i( location, textureUnit );
  12043. if ( !texture ) continue;
  12044. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  12045. setCubeTexture( texture, textureUnit );
  12046. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  12047. setCubeTextureDynamic( texture, textureUnit );
  12048. } else {
  12049. _this.setTexture( texture, textureUnit );
  12050. }
  12051. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  12052. if ( uniform._array === undefined ) {
  12053. uniform._array = [];
  12054. }
  12055. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12056. uniform._array[ i ] = getTextureUnit();
  12057. }
  12058. _gl.uniform1iv( location, uniform._array );
  12059. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12060. texture = uniform.value[ i ];
  12061. textureUnit = uniform._array[ i ];
  12062. if ( !texture ) continue;
  12063. _this.setTexture( texture, textureUnit );
  12064. }
  12065. }
  12066. }
  12067. };
  12068. function setupMatrices ( object, camera ) {
  12069. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  12070. object._normalMatrix.getInverse( object._modelViewMatrix );
  12071. object._normalMatrix.transpose();
  12072. };
  12073. //
  12074. function setColorGamma( array, offset, color, intensitySq ) {
  12075. array[ offset ] = color.r * color.r * intensitySq;
  12076. array[ offset + 1 ] = color.g * color.g * intensitySq;
  12077. array[ offset + 2 ] = color.b * color.b * intensitySq;
  12078. };
  12079. function setColorLinear( array, offset, color, intensity ) {
  12080. array[ offset ] = color.r * intensity;
  12081. array[ offset + 1 ] = color.g * intensity;
  12082. array[ offset + 2 ] = color.b * intensity;
  12083. };
  12084. function setupLights ( program, lights ) {
  12085. var l, ll, light, n,
  12086. r = 0, g = 0, b = 0,
  12087. color, skyColor, groundColor,
  12088. intensity, intensitySq,
  12089. position,
  12090. distance,
  12091. zlights = _lights,
  12092. dirColors = zlights.directional.colors,
  12093. dirPositions = zlights.directional.positions,
  12094. pointColors = zlights.point.colors,
  12095. pointPositions = zlights.point.positions,
  12096. pointDistances = zlights.point.distances,
  12097. spotColors = zlights.spot.colors,
  12098. spotPositions = zlights.spot.positions,
  12099. spotDistances = zlights.spot.distances,
  12100. spotDirections = zlights.spot.directions,
  12101. spotAngles = zlights.spot.angles,
  12102. spotExponents = zlights.spot.exponents,
  12103. hemiSkyColors = zlights.hemi.skyColors,
  12104. hemiGroundColors = zlights.hemi.groundColors,
  12105. hemiPositions = zlights.hemi.positions,
  12106. dirLength = 0,
  12107. pointLength = 0,
  12108. spotLength = 0,
  12109. hemiLength = 0,
  12110. dirOffset = 0,
  12111. pointOffset = 0,
  12112. spotOffset = 0,
  12113. hemiOffset = 0;
  12114. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12115. light = lights[ l ];
  12116. if ( light.onlyShadow || ! light.visible ) continue;
  12117. color = light.color;
  12118. intensity = light.intensity;
  12119. distance = light.distance;
  12120. if ( light instanceof THREE.AmbientLight ) {
  12121. if ( _this.gammaInput ) {
  12122. r += color.r * color.r;
  12123. g += color.g * color.g;
  12124. b += color.b * color.b;
  12125. } else {
  12126. r += color.r;
  12127. g += color.g;
  12128. b += color.b;
  12129. }
  12130. } else if ( light instanceof THREE.DirectionalLight ) {
  12131. dirOffset = dirLength * 3;
  12132. if ( _this.gammaInput ) {
  12133. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  12134. } else {
  12135. setColorLinear( dirColors, dirOffset, color, intensity );
  12136. }
  12137. _direction.copy( light.matrixWorld.getPosition() );
  12138. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12139. _direction.normalize();
  12140. dirPositions[ dirOffset ] = _direction.x;
  12141. dirPositions[ dirOffset + 1 ] = _direction.y;
  12142. dirPositions[ dirOffset + 2 ] = _direction.z;
  12143. dirLength += 1;
  12144. } else if( light instanceof THREE.PointLight ) {
  12145. pointOffset = pointLength * 3;
  12146. if ( _this.gammaInput ) {
  12147. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  12148. } else {
  12149. setColorLinear( pointColors, pointOffset, color, intensity );
  12150. }
  12151. position = light.matrixWorld.getPosition();
  12152. pointPositions[ pointOffset ] = position.x;
  12153. pointPositions[ pointOffset + 1 ] = position.y;
  12154. pointPositions[ pointOffset + 2 ] = position.z;
  12155. pointDistances[ pointLength ] = distance;
  12156. pointLength += 1;
  12157. } else if( light instanceof THREE.SpotLight ) {
  12158. spotOffset = spotLength * 3;
  12159. if ( _this.gammaInput ) {
  12160. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  12161. } else {
  12162. setColorLinear( spotColors, spotOffset, color, intensity );
  12163. }
  12164. position = light.matrixWorld.getPosition();
  12165. spotPositions[ spotOffset ] = position.x;
  12166. spotPositions[ spotOffset + 1 ] = position.y;
  12167. spotPositions[ spotOffset + 2 ] = position.z;
  12168. spotDistances[ spotLength ] = distance;
  12169. _direction.copy( position );
  12170. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12171. _direction.normalize();
  12172. spotDirections[ spotOffset ] = _direction.x;
  12173. spotDirections[ spotOffset + 1 ] = _direction.y;
  12174. spotDirections[ spotOffset + 2 ] = _direction.z;
  12175. spotAngles[ spotLength ] = Math.cos( light.angle );
  12176. spotExponents[ spotLength ] = light.exponent;
  12177. spotLength += 1;
  12178. } else if ( light instanceof THREE.HemisphereLight ) {
  12179. skyColor = light.color;
  12180. groundColor = light.groundColor;
  12181. hemiOffset = hemiLength * 3;
  12182. if ( _this.gammaInput ) {
  12183. intensitySq = intensity * intensity;
  12184. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  12185. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  12186. } else {
  12187. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  12188. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  12189. }
  12190. position = light.matrixWorld.getPosition();
  12191. hemiPositions[ hemiOffset ] = position.x;
  12192. hemiPositions[ hemiOffset + 1 ] = position.y;
  12193. hemiPositions[ hemiOffset + 2 ] = position.z;
  12194. hemiLength += 1;
  12195. }
  12196. }
  12197. // null eventual remains from removed lights
  12198. // (this is to avoid if in shader)
  12199. for ( l = dirLength * 3, ll = dirColors.length; l < ll; l ++ ) dirColors[ l ] = 0.0;
  12200. for ( l = pointLength * 3, ll = pointColors.length; l < ll; l ++ ) pointColors[ l ] = 0.0;
  12201. for ( l = spotLength * 3, ll = spotColors.length; l < ll; l ++ ) spotColors[ l ] = 0.0;
  12202. for ( l = hemiLength * 3, ll = hemiSkyColors.length; l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  12203. for ( l = hemiLength * 3, ll = hemiGroundColors.length; l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  12204. zlights.directional.length = dirLength;
  12205. zlights.point.length = pointLength;
  12206. zlights.spot.length = spotLength;
  12207. zlights.hemi.length = hemiLength;
  12208. zlights.ambient[ 0 ] = r;
  12209. zlights.ambient[ 1 ] = g;
  12210. zlights.ambient[ 2 ] = b;
  12211. };
  12212. // GL state setting
  12213. this.setFaceCulling = function ( cullFace, frontFace ) {
  12214. if ( cullFace ) {
  12215. if ( !frontFace || frontFace === "ccw" ) {
  12216. _gl.frontFace( _gl.CCW );
  12217. } else {
  12218. _gl.frontFace( _gl.CW );
  12219. }
  12220. if( cullFace === "back" ) {
  12221. _gl.cullFace( _gl.BACK );
  12222. } else if( cullFace === "front" ) {
  12223. _gl.cullFace( _gl.FRONT );
  12224. } else {
  12225. _gl.cullFace( _gl.FRONT_AND_BACK );
  12226. }
  12227. _gl.enable( _gl.CULL_FACE );
  12228. } else {
  12229. _gl.disable( _gl.CULL_FACE );
  12230. }
  12231. };
  12232. this.setMaterialFaces = function ( material ) {
  12233. var doubleSided = material.side === THREE.DoubleSide;
  12234. var flipSided = material.side === THREE.BackSide;
  12235. if ( _oldDoubleSided !== doubleSided ) {
  12236. if ( doubleSided ) {
  12237. _gl.disable( _gl.CULL_FACE );
  12238. } else {
  12239. _gl.enable( _gl.CULL_FACE );
  12240. }
  12241. _oldDoubleSided = doubleSided;
  12242. }
  12243. if ( _oldFlipSided !== flipSided ) {
  12244. if ( flipSided ) {
  12245. _gl.frontFace( _gl.CW );
  12246. } else {
  12247. _gl.frontFace( _gl.CCW );
  12248. }
  12249. _oldFlipSided = flipSided;
  12250. }
  12251. };
  12252. this.setDepthTest = function ( depthTest ) {
  12253. if ( _oldDepthTest !== depthTest ) {
  12254. if ( depthTest ) {
  12255. _gl.enable( _gl.DEPTH_TEST );
  12256. } else {
  12257. _gl.disable( _gl.DEPTH_TEST );
  12258. }
  12259. _oldDepthTest = depthTest;
  12260. }
  12261. };
  12262. this.setDepthWrite = function ( depthWrite ) {
  12263. if ( _oldDepthWrite !== depthWrite ) {
  12264. _gl.depthMask( depthWrite );
  12265. _oldDepthWrite = depthWrite;
  12266. }
  12267. };
  12268. function setLineWidth ( width ) {
  12269. if ( width !== _oldLineWidth ) {
  12270. _gl.lineWidth( width );
  12271. _oldLineWidth = width;
  12272. }
  12273. };
  12274. function setPolygonOffset ( polygonoffset, factor, units ) {
  12275. if ( _oldPolygonOffset !== polygonoffset ) {
  12276. if ( polygonoffset ) {
  12277. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  12278. } else {
  12279. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  12280. }
  12281. _oldPolygonOffset = polygonoffset;
  12282. }
  12283. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  12284. _gl.polygonOffset( factor, units );
  12285. _oldPolygonOffsetFactor = factor;
  12286. _oldPolygonOffsetUnits = units;
  12287. }
  12288. };
  12289. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  12290. if ( blending !== _oldBlending ) {
  12291. if ( blending === THREE.NoBlending ) {
  12292. _gl.disable( _gl.BLEND );
  12293. } else if ( blending === THREE.AdditiveBlending ) {
  12294. _gl.enable( _gl.BLEND );
  12295. _gl.blendEquation( _gl.FUNC_ADD );
  12296. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  12297. } else if ( blending === THREE.SubtractiveBlending ) {
  12298. // TODO: Find blendFuncSeparate() combination
  12299. _gl.enable( _gl.BLEND );
  12300. _gl.blendEquation( _gl.FUNC_ADD );
  12301. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  12302. } else if ( blending === THREE.MultiplyBlending ) {
  12303. // TODO: Find blendFuncSeparate() combination
  12304. _gl.enable( _gl.BLEND );
  12305. _gl.blendEquation( _gl.FUNC_ADD );
  12306. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  12307. } else if ( blending === THREE.CustomBlending ) {
  12308. _gl.enable( _gl.BLEND );
  12309. } else {
  12310. _gl.enable( _gl.BLEND );
  12311. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  12312. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  12313. }
  12314. _oldBlending = blending;
  12315. }
  12316. if ( blending === THREE.CustomBlending ) {
  12317. if ( blendEquation !== _oldBlendEquation ) {
  12318. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  12319. _oldBlendEquation = blendEquation;
  12320. }
  12321. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  12322. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  12323. _oldBlendSrc = blendSrc;
  12324. _oldBlendDst = blendDst;
  12325. }
  12326. } else {
  12327. _oldBlendEquation = null;
  12328. _oldBlendSrc = null;
  12329. _oldBlendDst = null;
  12330. }
  12331. };
  12332. // Shaders
  12333. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, parameters ) {
  12334. var p, pl, program, code;
  12335. var chunks = [];
  12336. // Generate code
  12337. if ( shaderID ) {
  12338. chunks.push( shaderID );
  12339. } else {
  12340. chunks.push( fragmentShader );
  12341. chunks.push( vertexShader );
  12342. }
  12343. for ( p in parameters ) {
  12344. chunks.push( p );
  12345. chunks.push( parameters[ p ] );
  12346. }
  12347. code = chunks.join();
  12348. // Check if code has been already compiled
  12349. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  12350. var programInfo = _programs[ p ];
  12351. if ( programInfo.code === code ) {
  12352. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  12353. programInfo.usedTimes ++;
  12354. return programInfo.program;
  12355. }
  12356. }
  12357. //console.log( "building new program " );
  12358. //
  12359. program = _gl.createProgram();
  12360. var prefix_vertex = [
  12361. "precision " + _precision + " float;",
  12362. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  12363. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  12364. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  12365. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  12366. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  12367. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  12368. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  12369. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  12370. "#define MAX_SHADOWS " + parameters.maxShadows,
  12371. "#define MAX_BONES " + parameters.maxBones,
  12372. parameters.map ? "#define USE_MAP" : "",
  12373. parameters.envMap ? "#define USE_ENVMAP" : "",
  12374. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  12375. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  12376. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  12377. parameters.vertexColors ? "#define USE_COLOR" : "",
  12378. parameters.skinning ? "#define USE_SKINNING" : "",
  12379. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  12380. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  12381. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  12382. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  12383. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  12384. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  12385. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  12386. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  12387. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  12388. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  12389. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  12390. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  12391. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  12392. "uniform mat4 modelMatrix;",
  12393. "uniform mat4 modelViewMatrix;",
  12394. "uniform mat4 projectionMatrix;",
  12395. "uniform mat4 viewMatrix;",
  12396. "uniform mat3 normalMatrix;",
  12397. "uniform vec3 cameraPosition;",
  12398. "attribute vec3 position;",
  12399. "attribute vec3 normal;",
  12400. "attribute vec2 uv;",
  12401. "attribute vec2 uv2;",
  12402. "#ifdef USE_COLOR",
  12403. "attribute vec3 color;",
  12404. "#endif",
  12405. "#ifdef USE_MORPHTARGETS",
  12406. "attribute vec3 morphTarget0;",
  12407. "attribute vec3 morphTarget1;",
  12408. "attribute vec3 morphTarget2;",
  12409. "attribute vec3 morphTarget3;",
  12410. "#ifdef USE_MORPHNORMALS",
  12411. "attribute vec3 morphNormal0;",
  12412. "attribute vec3 morphNormal1;",
  12413. "attribute vec3 morphNormal2;",
  12414. "attribute vec3 morphNormal3;",
  12415. "#else",
  12416. "attribute vec3 morphTarget4;",
  12417. "attribute vec3 morphTarget5;",
  12418. "attribute vec3 morphTarget6;",
  12419. "attribute vec3 morphTarget7;",
  12420. "#endif",
  12421. "#endif",
  12422. "#ifdef USE_SKINNING",
  12423. "attribute vec4 skinIndex;",
  12424. "attribute vec4 skinWeight;",
  12425. "#endif",
  12426. ""
  12427. ].join("\n");
  12428. var prefix_fragment = [
  12429. "precision " + _precision + " float;",
  12430. parameters.bumpMap ? "#extension GL_OES_standard_derivatives : enable" : "",
  12431. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  12432. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  12433. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  12434. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  12435. "#define MAX_SHADOWS " + parameters.maxShadows,
  12436. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  12437. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  12438. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  12439. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  12440. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  12441. ( parameters.useFog && parameters.fog instanceof THREE.FogExp2 ) ? "#define FOG_EXP2" : "",
  12442. parameters.map ? "#define USE_MAP" : "",
  12443. parameters.envMap ? "#define USE_ENVMAP" : "",
  12444. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  12445. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  12446. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  12447. parameters.vertexColors ? "#define USE_COLOR" : "",
  12448. parameters.metal ? "#define METAL" : "",
  12449. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  12450. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  12451. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  12452. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  12453. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  12454. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  12455. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  12456. "uniform mat4 viewMatrix;",
  12457. "uniform vec3 cameraPosition;",
  12458. ""
  12459. ].join("\n");
  12460. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  12461. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  12462. _gl.attachShader( program, glVertexShader );
  12463. _gl.attachShader( program, glFragmentShader );
  12464. _gl.linkProgram( program );
  12465. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  12466. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  12467. }
  12468. // clean up
  12469. _gl.deleteShader( glFragmentShader );
  12470. _gl.deleteShader( glVertexShader );
  12471. //console.log( prefix_fragment + fragmentShader );
  12472. //console.log( prefix_vertex + vertexShader );
  12473. program.uniforms = {};
  12474. program.attributes = {};
  12475. var identifiers, u, a, i;
  12476. // cache uniform locations
  12477. identifiers = [
  12478. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  12479. 'morphTargetInfluences'
  12480. ];
  12481. if ( parameters.useVertexTexture ) {
  12482. identifiers.push( 'boneTexture' );
  12483. } else {
  12484. identifiers.push( 'boneGlobalMatrices' );
  12485. }
  12486. for ( u in uniforms ) {
  12487. identifiers.push( u );
  12488. }
  12489. cacheUniformLocations( program, identifiers );
  12490. // cache attributes locations
  12491. identifiers = [
  12492. "position", "normal", "uv", "uv2", "tangent", "color",
  12493. "skinIndex", "skinWeight"
  12494. ];
  12495. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  12496. identifiers.push( "morphTarget" + i );
  12497. }
  12498. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  12499. identifiers.push( "morphNormal" + i );
  12500. }
  12501. for ( a in attributes ) {
  12502. identifiers.push( a );
  12503. }
  12504. cacheAttributeLocations( program, identifiers );
  12505. program.id = _programs_counter ++;
  12506. _programs.push( { program: program, code: code, usedTimes: 1 } );
  12507. _this.info.memory.programs = _programs.length;
  12508. return program;
  12509. };
  12510. // Shader parameters cache
  12511. function cacheUniformLocations ( program, identifiers ) {
  12512. var i, l, id;
  12513. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  12514. id = identifiers[ i ];
  12515. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  12516. }
  12517. };
  12518. function cacheAttributeLocations ( program, identifiers ) {
  12519. var i, l, id;
  12520. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  12521. id = identifiers[ i ];
  12522. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  12523. }
  12524. };
  12525. function addLineNumbers ( string ) {
  12526. var chunks = string.split( "\n" );
  12527. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  12528. // Chrome reports shader errors on lines
  12529. // starting counting from 1
  12530. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  12531. }
  12532. return chunks.join( "\n" );
  12533. };
  12534. function getShader ( type, string ) {
  12535. var shader;
  12536. if ( type === "fragment" ) {
  12537. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  12538. } else if ( type === "vertex" ) {
  12539. shader = _gl.createShader( _gl.VERTEX_SHADER );
  12540. }
  12541. _gl.shaderSource( shader, string );
  12542. _gl.compileShader( shader );
  12543. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  12544. console.error( _gl.getShaderInfoLog( shader ) );
  12545. console.error( addLineNumbers( string ) );
  12546. return null;
  12547. }
  12548. return shader;
  12549. };
  12550. // Textures
  12551. function isPowerOfTwo ( value ) {
  12552. return ( value & ( value - 1 ) ) === 0;
  12553. };
  12554. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  12555. if ( isImagePowerOfTwo ) {
  12556. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  12557. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  12558. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  12559. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  12560. } else {
  12561. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  12562. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  12563. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  12564. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  12565. }
  12566. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  12567. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  12568. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  12569. texture.__oldAnisotropy = texture.anisotropy;
  12570. }
  12571. }
  12572. };
  12573. this.setTexture = function ( texture, slot ) {
  12574. if ( texture.needsUpdate ) {
  12575. if ( ! texture.__webglInit ) {
  12576. texture.__webglInit = true;
  12577. texture.__webglTexture = _gl.createTexture();
  12578. _this.info.memory.textures ++;
  12579. }
  12580. _gl.activeTexture( _gl.TEXTURE0 + slot );
  12581. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  12582. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  12583. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  12584. var image = texture.image,
  12585. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  12586. glFormat = paramThreeToGL( texture.format ),
  12587. glType = paramThreeToGL( texture.type );
  12588. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  12589. if ( texture instanceof THREE.DataTexture ) {
  12590. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  12591. } else {
  12592. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  12593. }
  12594. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  12595. texture.needsUpdate = false;
  12596. if ( texture.onUpdate ) texture.onUpdate();
  12597. } else {
  12598. _gl.activeTexture( _gl.TEXTURE0 + slot );
  12599. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  12600. }
  12601. };
  12602. function clampToMaxSize ( image, maxSize ) {
  12603. if ( image.width <= maxSize && image.height <= maxSize ) {
  12604. return image;
  12605. }
  12606. // Warning: Scaling through the canvas will only work with images that use
  12607. // premultiplied alpha.
  12608. var maxDimension = Math.max( image.width, image.height );
  12609. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  12610. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  12611. var canvas = document.createElement( 'canvas' );
  12612. canvas.width = newWidth;
  12613. canvas.height = newHeight;
  12614. var ctx = canvas.getContext( "2d" );
  12615. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  12616. return canvas;
  12617. }
  12618. function setCubeTexture ( texture, slot ) {
  12619. if ( texture.image.length === 6 ) {
  12620. if ( texture.needsUpdate ) {
  12621. if ( ! texture.image.__webglTextureCube ) {
  12622. texture.image.__webglTextureCube = _gl.createTexture();
  12623. }
  12624. _gl.activeTexture( _gl.TEXTURE0 + slot );
  12625. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  12626. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  12627. var cubeImage = [];
  12628. for ( var i = 0; i < 6; i ++ ) {
  12629. if ( _this.autoScaleCubemaps ) {
  12630. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  12631. } else {
  12632. cubeImage[ i ] = texture.image[ i ];
  12633. }
  12634. }
  12635. var image = cubeImage[ 0 ],
  12636. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  12637. glFormat = paramThreeToGL( texture.format ),
  12638. glType = paramThreeToGL( texture.type );
  12639. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  12640. for ( var i = 0; i < 6; i ++ ) {
  12641. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  12642. }
  12643. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  12644. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  12645. }
  12646. texture.needsUpdate = false;
  12647. if ( texture.onUpdate ) texture.onUpdate();
  12648. } else {
  12649. _gl.activeTexture( _gl.TEXTURE0 + slot );
  12650. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  12651. }
  12652. }
  12653. };
  12654. function setCubeTextureDynamic ( texture, slot ) {
  12655. _gl.activeTexture( _gl.TEXTURE0 + slot );
  12656. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  12657. };
  12658. // Render targets
  12659. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  12660. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  12661. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  12662. };
  12663. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  12664. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  12665. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  12666. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  12667. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  12668. /* For some reason this is not working. Defaulting to RGBA4.
  12669. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  12670. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  12671. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  12672. */
  12673. } else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  12674. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  12675. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  12676. } else {
  12677. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  12678. }
  12679. };
  12680. this.setRenderTarget = function ( renderTarget ) {
  12681. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  12682. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  12683. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  12684. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  12685. renderTarget.__webglTexture = _gl.createTexture();
  12686. // Setup texture, create render and frame buffers
  12687. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  12688. glFormat = paramThreeToGL( renderTarget.format ),
  12689. glType = paramThreeToGL( renderTarget.type );
  12690. if ( isCube ) {
  12691. renderTarget.__webglFramebuffer = [];
  12692. renderTarget.__webglRenderbuffer = [];
  12693. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  12694. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  12695. for ( var i = 0; i < 6; i ++ ) {
  12696. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  12697. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  12698. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  12699. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  12700. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  12701. }
  12702. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  12703. } else {
  12704. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  12705. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  12706. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  12707. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  12708. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  12709. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  12710. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  12711. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  12712. }
  12713. // Release everything
  12714. if ( isCube ) {
  12715. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  12716. } else {
  12717. _gl.bindTexture( _gl.TEXTURE_2D, null );
  12718. }
  12719. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  12720. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null);
  12721. }
  12722. var framebuffer, width, height, vx, vy;
  12723. if ( renderTarget ) {
  12724. if ( isCube ) {
  12725. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  12726. } else {
  12727. framebuffer = renderTarget.__webglFramebuffer;
  12728. }
  12729. width = renderTarget.width;
  12730. height = renderTarget.height;
  12731. vx = 0;
  12732. vy = 0;
  12733. } else {
  12734. framebuffer = null;
  12735. width = _viewportWidth;
  12736. height = _viewportHeight;
  12737. vx = _viewportX;
  12738. vy = _viewportY;
  12739. }
  12740. if ( framebuffer !== _currentFramebuffer ) {
  12741. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  12742. _gl.viewport( vx, vy, width, height );
  12743. _currentFramebuffer = framebuffer;
  12744. }
  12745. _currentWidth = width;
  12746. _currentHeight = height;
  12747. };
  12748. function updateRenderTargetMipmap ( renderTarget ) {
  12749. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  12750. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  12751. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  12752. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  12753. } else {
  12754. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  12755. _gl.generateMipmap( _gl.TEXTURE_2D );
  12756. _gl.bindTexture( _gl.TEXTURE_2D, null );
  12757. }
  12758. };
  12759. // Fallback filters for non-power-of-2 textures
  12760. function filterFallback ( f ) {
  12761. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  12762. return _gl.NEAREST;
  12763. }
  12764. return _gl.LINEAR;
  12765. };
  12766. // Map three.js constants to WebGL constants
  12767. function paramThreeToGL ( p ) {
  12768. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  12769. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  12770. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  12771. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  12772. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  12773. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  12774. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  12775. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  12776. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  12777. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  12778. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  12779. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  12780. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  12781. if ( p === THREE.ByteType ) return _gl.BYTE;
  12782. if ( p === THREE.ShortType ) return _gl.SHORT;
  12783. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  12784. if ( p === THREE.IntType ) return _gl.INT;
  12785. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  12786. if ( p === THREE.FloatType ) return _gl.FLOAT;
  12787. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  12788. if ( p === THREE.RGBFormat ) return _gl.RGB;
  12789. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  12790. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  12791. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  12792. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  12793. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  12794. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  12795. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  12796. if ( p === THREE.OneFactor ) return _gl.ONE;
  12797. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  12798. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  12799. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  12800. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  12801. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  12802. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  12803. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  12804. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  12805. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  12806. return 0;
  12807. };
  12808. // Allocations
  12809. function allocateBones ( object ) {
  12810. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  12811. return 1024;
  12812. } else {
  12813. // default for when object is not specified
  12814. // ( for example when prebuilding shader
  12815. // to be used with multiple objects )
  12816. //
  12817. // - leave some extra space for other uniforms
  12818. // - limit here is ANGLE's 254 max uniform vectors
  12819. // (up to 54 should be safe)
  12820. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  12821. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  12822. var maxBones = nVertexMatrices;
  12823. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  12824. maxBones = Math.min( object.bones.length, maxBones );
  12825. if ( maxBones < object.bones.length ) {
  12826. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  12827. }
  12828. }
  12829. return maxBones;
  12830. }
  12831. };
  12832. function allocateLights ( lights ) {
  12833. var l, ll, light, dirLights, pointLights, spotLights, hemiLights, maxDirLights, maxPointLights, maxSpotLights, maxHemiLights;
  12834. dirLights = pointLights = spotLights = hemiLights = maxDirLights = maxPointLights = maxSpotLights = maxHemiLights = 0;
  12835. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12836. light = lights[ l ];
  12837. if ( light.onlyShadow ) continue;
  12838. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  12839. if ( light instanceof THREE.PointLight ) pointLights ++;
  12840. if ( light instanceof THREE.SpotLight ) spotLights ++;
  12841. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  12842. }
  12843. if ( ( pointLights + spotLights + dirLights + hemiLights) <= _maxLights ) {
  12844. maxDirLights = dirLights;
  12845. maxPointLights = pointLights;
  12846. maxSpotLights = spotLights;
  12847. maxHemiLights = hemiLights;
  12848. } else {
  12849. maxDirLights = Math.ceil( _maxLights * dirLights / ( pointLights + dirLights ) );
  12850. maxPointLights = _maxLights - maxDirLights;
  12851. // these are not really correct
  12852. maxSpotLights = maxPointLights;
  12853. maxHemiLights = maxDirLights;
  12854. }
  12855. return { 'directional' : maxDirLights, 'point' : maxPointLights, 'spot': maxSpotLights, 'hemi': maxHemiLights };
  12856. };
  12857. function allocateShadows ( lights ) {
  12858. var l, ll, light, maxShadows = 0;
  12859. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  12860. light = lights[ l ];
  12861. if ( ! light.castShadow ) continue;
  12862. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  12863. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  12864. }
  12865. return maxShadows;
  12866. };
  12867. // Initialization
  12868. function initGL () {
  12869. try {
  12870. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  12871. throw 'Error creating WebGL context.';
  12872. }
  12873. } catch ( error ) {
  12874. console.error( error );
  12875. }
  12876. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  12877. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  12878. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  12879. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  12880. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  12881. if ( ! _glExtensionTextureFloat ) {
  12882. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  12883. }
  12884. if ( ! _glExtensionStandardDerivatives ) {
  12885. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  12886. }
  12887. if ( ! _glExtensionTextureFilterAnisotropic ) {
  12888. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  12889. }
  12890. };
  12891. function setDefaultGLState () {
  12892. _gl.clearColor( 0, 0, 0, 1 );
  12893. _gl.clearDepth( 1 );
  12894. _gl.clearStencil( 0 );
  12895. _gl.enable( _gl.DEPTH_TEST );
  12896. _gl.depthFunc( _gl.LEQUAL );
  12897. _gl.frontFace( _gl.CCW );
  12898. _gl.cullFace( _gl.BACK );
  12899. _gl.enable( _gl.CULL_FACE );
  12900. _gl.enable( _gl.BLEND );
  12901. _gl.blendEquation( _gl.FUNC_ADD );
  12902. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  12903. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12904. };
  12905. // default plugins (order is important)
  12906. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  12907. this.addPrePlugin( this.shadowMapPlugin );
  12908. this.addPostPlugin( new THREE.SpritePlugin() );
  12909. this.addPostPlugin( new THREE.LensFlarePlugin() );
  12910. };
  12911. /**
  12912. * @author szimek / https://github.com/szimek/
  12913. * @author alteredq / http://alteredqualia.com/
  12914. */
  12915. THREE.WebGLRenderTarget = function ( width, height, options ) {
  12916. this.width = width;
  12917. this.height = height;
  12918. options = options || {};
  12919. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  12920. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  12921. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  12922. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  12923. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  12924. this.offset = new THREE.Vector2( 0, 0 );
  12925. this.repeat = new THREE.Vector2( 1, 1 );
  12926. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  12927. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  12928. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  12929. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  12930. this.generateMipmaps = true;
  12931. };
  12932. THREE.WebGLRenderTarget.prototype.clone = function() {
  12933. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  12934. tmp.wrapS = this.wrapS;
  12935. tmp.wrapT = this.wrapT;
  12936. tmp.magFilter = this.magFilter;
  12937. tmp.anisotropy = this.anisotropy;
  12938. tmp.minFilter = this.minFilter;
  12939. tmp.offset.copy( this.offset );
  12940. tmp.repeat.copy( this.repeat );
  12941. tmp.format = this.format;
  12942. tmp.type = this.type;
  12943. tmp.depthBuffer = this.depthBuffer;
  12944. tmp.stencilBuffer = this.stencilBuffer;
  12945. tmp.generateMipmaps = this.generateMipmaps;
  12946. return tmp;
  12947. };
  12948. /**
  12949. * @author alteredq / http://alteredqualia.com
  12950. */
  12951. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  12952. THREE.WebGLRenderTarget.call( this, width, height, options );
  12953. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  12954. };
  12955. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  12956. /**
  12957. * @author mrdoob / http://mrdoob.com/
  12958. */
  12959. THREE.RenderableVertex = function () {
  12960. this.positionWorld = new THREE.Vector3();
  12961. this.positionScreen = new THREE.Vector4();
  12962. this.visible = true;
  12963. };
  12964. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  12965. this.positionWorld.copy( vertex.positionWorld );
  12966. this.positionScreen.copy( vertex.positionScreen );
  12967. }
  12968. /**
  12969. * @author mrdoob / http://mrdoob.com/
  12970. */
  12971. THREE.RenderableFace3 = function () {
  12972. this.v1 = new THREE.RenderableVertex();
  12973. this.v2 = new THREE.RenderableVertex();
  12974. this.v3 = new THREE.RenderableVertex();
  12975. this.centroidWorld = new THREE.Vector3();
  12976. this.centroidScreen = new THREE.Vector3();
  12977. this.normalWorld = new THREE.Vector3();
  12978. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  12979. this.vertexNormalsLength = 0;
  12980. this.material = null;
  12981. this.uvs = [[]];
  12982. this.z = null;
  12983. };
  12984. /**
  12985. * @author mrdoob / http://mrdoob.com/
  12986. */
  12987. THREE.RenderableFace4 = function () {
  12988. this.v1 = new THREE.RenderableVertex();
  12989. this.v2 = new THREE.RenderableVertex();
  12990. this.v3 = new THREE.RenderableVertex();
  12991. this.v4 = new THREE.RenderableVertex();
  12992. this.centroidWorld = new THREE.Vector3();
  12993. this.centroidScreen = new THREE.Vector3();
  12994. this.normalWorld = new THREE.Vector3();
  12995. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  12996. this.vertexNormalsLength = 0;
  12997. this.material = null;
  12998. this.uvs = [[]];
  12999. this.z = null;
  13000. };
  13001. /**
  13002. * @author mrdoob / http://mrdoob.com/
  13003. */
  13004. THREE.RenderableObject = function () {
  13005. this.object = null;
  13006. this.z = null;
  13007. };
  13008. /**
  13009. * @author mrdoob / http://mrdoob.com/
  13010. */
  13011. THREE.RenderableParticle = function () {
  13012. this.object = null;
  13013. this.x = null;
  13014. this.y = null;
  13015. this.z = null;
  13016. this.rotation = null;
  13017. this.scale = new THREE.Vector2();
  13018. this.material = null;
  13019. };
  13020. /**
  13021. * @author mrdoob / http://mrdoob.com/
  13022. */
  13023. THREE.RenderableLine = function () {
  13024. this.z = null;
  13025. this.v1 = new THREE.RenderableVertex();
  13026. this.v2 = new THREE.RenderableVertex();
  13027. this.material = null;
  13028. };
  13029. /**
  13030. * @author alteredq / http://alteredqualia.com/
  13031. */
  13032. THREE.ColorUtils = {
  13033. adjustHSV : function ( color, h, s, v ) {
  13034. var hsv = THREE.ColorUtils.__hsv;
  13035. THREE.ColorUtils.rgbToHsv( color, hsv );
  13036. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  13037. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  13038. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  13039. color.setHSV( hsv.h, hsv.s, hsv.v );
  13040. },
  13041. // based on MochiKit implementation by Bob Ippolito
  13042. rgbToHsv : function ( color, hsv ) {
  13043. var r = color.r;
  13044. var g = color.g;
  13045. var b = color.b;
  13046. var max = Math.max( Math.max( r, g ), b );
  13047. var min = Math.min( Math.min( r, g ), b );
  13048. var hue;
  13049. var saturation;
  13050. var value = max;
  13051. if ( min === max ) {
  13052. hue = 0;
  13053. saturation = 0;
  13054. } else {
  13055. var delta = ( max - min );
  13056. saturation = delta / max;
  13057. if ( r === max ) {
  13058. hue = ( g - b ) / delta;
  13059. } else if ( g === max ) {
  13060. hue = 2 + ( ( b - r ) / delta );
  13061. } else {
  13062. hue = 4 + ( ( r - g ) / delta );
  13063. }
  13064. hue /= 6;
  13065. if ( hue < 0 ) {
  13066. hue += 1;
  13067. }
  13068. if ( hue > 1 ) {
  13069. hue -= 1;
  13070. }
  13071. }
  13072. if ( hsv === undefined ) {
  13073. hsv = { h: 0, s: 0, v: 0 };
  13074. }
  13075. hsv.h = hue;
  13076. hsv.s = saturation;
  13077. hsv.v = value;
  13078. return hsv;
  13079. }
  13080. };
  13081. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  13082. * @author mrdoob / http://mrdoob.com/
  13083. * @author alteredq / http://alteredqualia.com/
  13084. */
  13085. THREE.GeometryUtils = {
  13086. // Merge two geometries or geometry and geometry from object (using object's transform)
  13087. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  13088. var matrix, matrixRotation,
  13089. vertexOffset = geometry1.vertices.length,
  13090. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  13091. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  13092. vertices1 = geometry1.vertices,
  13093. vertices2 = geometry2.vertices,
  13094. faces1 = geometry1.faces,
  13095. faces2 = geometry2.faces,
  13096. uvs1 = geometry1.faceVertexUvs[ 0 ],
  13097. uvs2 = geometry2.faceVertexUvs[ 0 ];
  13098. var geo1MaterialsMap = {};
  13099. for ( var i = 0; i < geometry1.materials.length; i ++ ) {
  13100. var id = geometry1.materials[ i ].id;
  13101. geo1MaterialsMap[ id ] = i;
  13102. }
  13103. if ( object2 instanceof THREE.Mesh ) {
  13104. object2.matrixAutoUpdate && object2.updateMatrix();
  13105. matrix = object2.matrix;
  13106. matrixRotation = new THREE.Matrix4();
  13107. matrixRotation.extractRotation( matrix, object2.scale );
  13108. }
  13109. // vertices
  13110. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  13111. var vertex = vertices2[ i ];
  13112. var vertexCopy = vertex.clone();
  13113. if ( matrix ) matrix.multiplyVector3( vertexCopy );
  13114. vertices1.push( vertexCopy );
  13115. }
  13116. // faces
  13117. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  13118. var face = faces2[ i ], faceCopy, normal, color,
  13119. faceVertexNormals = face.vertexNormals,
  13120. faceVertexColors = face.vertexColors;
  13121. if ( face instanceof THREE.Face3 ) {
  13122. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  13123. } else if ( face instanceof THREE.Face4 ) {
  13124. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  13125. }
  13126. faceCopy.normal.copy( face.normal );
  13127. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  13128. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  13129. normal = faceVertexNormals[ j ].clone();
  13130. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  13131. faceCopy.vertexNormals.push( normal );
  13132. }
  13133. faceCopy.color.copy( face.color );
  13134. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  13135. color = faceVertexColors[ j ];
  13136. faceCopy.vertexColors.push( color.clone() );
  13137. }
  13138. if ( face.materialIndex !== undefined ) {
  13139. var material2 = geometry2.materials[ face.materialIndex ];
  13140. var materialId2 = material2.id;
  13141. var materialIndex = geo1MaterialsMap[ materialId2 ];
  13142. if ( materialIndex === undefined ) {
  13143. materialIndex = geometry1.materials.length;
  13144. geo1MaterialsMap[ materialId2 ] = materialIndex;
  13145. geometry1.materials.push( material2 );
  13146. }
  13147. faceCopy.materialIndex = materialIndex;
  13148. }
  13149. faceCopy.centroid.copy( face.centroid );
  13150. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  13151. faces1.push( faceCopy );
  13152. }
  13153. // uvs
  13154. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  13155. var uv = uvs2[ i ], uvCopy = [];
  13156. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  13157. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  13158. }
  13159. uvs1.push( uvCopy );
  13160. }
  13161. },
  13162. clone: function ( geometry ) {
  13163. var cloneGeo = new THREE.Geometry();
  13164. var i, il;
  13165. var vertices = geometry.vertices,
  13166. faces = geometry.faces,
  13167. uvs = geometry.faceVertexUvs[ 0 ];
  13168. // materials
  13169. if ( geometry.materials ) {
  13170. cloneGeo.materials = geometry.materials.slice();
  13171. }
  13172. // vertices
  13173. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  13174. var vertex = vertices[ i ];
  13175. cloneGeo.vertices.push( vertex.clone() );
  13176. }
  13177. // faces
  13178. for ( i = 0, il = faces.length; i < il; i ++ ) {
  13179. var face = faces[ i ];
  13180. cloneGeo.faces.push( face.clone() );
  13181. }
  13182. // uvs
  13183. for ( i = 0, il = uvs.length; i < il; i ++ ) {
  13184. var uv = uvs[ i ], uvCopy = [];
  13185. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  13186. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  13187. }
  13188. cloneGeo.faceVertexUvs[ 0 ].push( uvCopy );
  13189. }
  13190. return cloneGeo;
  13191. },
  13192. // Get random point in triangle (via barycentric coordinates)
  13193. // (uniform distribution)
  13194. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  13195. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  13196. var a, b, c,
  13197. point = new THREE.Vector3(),
  13198. tmp = THREE.GeometryUtils.__v1;
  13199. a = THREE.GeometryUtils.random();
  13200. b = THREE.GeometryUtils.random();
  13201. if ( ( a + b ) > 1 ) {
  13202. a = 1 - a;
  13203. b = 1 - b;
  13204. }
  13205. c = 1 - a - b;
  13206. point.copy( vectorA );
  13207. point.multiplyScalar( a );
  13208. tmp.copy( vectorB );
  13209. tmp.multiplyScalar( b );
  13210. point.addSelf( tmp );
  13211. tmp.copy( vectorC );
  13212. tmp.multiplyScalar( c );
  13213. point.addSelf( tmp );
  13214. return point;
  13215. },
  13216. // Get random point in face (triangle / quad)
  13217. // (uniform distribution)
  13218. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  13219. var vA, vB, vC, vD;
  13220. if ( face instanceof THREE.Face3 ) {
  13221. vA = geometry.vertices[ face.a ];
  13222. vB = geometry.vertices[ face.b ];
  13223. vC = geometry.vertices[ face.c ];
  13224. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  13225. } else if ( face instanceof THREE.Face4 ) {
  13226. vA = geometry.vertices[ face.a ];
  13227. vB = geometry.vertices[ face.b ];
  13228. vC = geometry.vertices[ face.c ];
  13229. vD = geometry.vertices[ face.d ];
  13230. var area1, area2;
  13231. if ( useCachedAreas ) {
  13232. if ( face._area1 && face._area2 ) {
  13233. area1 = face._area1;
  13234. area2 = face._area2;
  13235. } else {
  13236. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  13237. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13238. face._area1 = area1;
  13239. face._area2 = area2;
  13240. }
  13241. } else {
  13242. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  13243. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13244. }
  13245. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  13246. if ( r < area1 ) {
  13247. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  13248. } else {
  13249. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  13250. }
  13251. }
  13252. },
  13253. // Get uniformly distributed random points in mesh
  13254. // - create array with cumulative sums of face areas
  13255. // - pick random number from 0 to total area
  13256. // - find corresponding place in area array by binary search
  13257. // - get random point in face
  13258. randomPointsInGeometry: function ( geometry, n ) {
  13259. var face, i,
  13260. faces = geometry.faces,
  13261. vertices = geometry.vertices,
  13262. il = faces.length,
  13263. totalArea = 0,
  13264. cumulativeAreas = [],
  13265. vA, vB, vC, vD;
  13266. // precompute face areas
  13267. for ( i = 0; i < il; i ++ ) {
  13268. face = faces[ i ];
  13269. if ( face instanceof THREE.Face3 ) {
  13270. vA = vertices[ face.a ];
  13271. vB = vertices[ face.b ];
  13272. vC = vertices[ face.c ];
  13273. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  13274. } else if ( face instanceof THREE.Face4 ) {
  13275. vA = vertices[ face.a ];
  13276. vB = vertices[ face.b ];
  13277. vC = vertices[ face.c ];
  13278. vD = vertices[ face.d ];
  13279. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  13280. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13281. face._area = face._area1 + face._area2;
  13282. }
  13283. totalArea += face._area;
  13284. cumulativeAreas[ i ] = totalArea;
  13285. }
  13286. // binary search cumulative areas array
  13287. function binarySearchIndices( value ) {
  13288. function binarySearch( start, end ) {
  13289. // return closest larger index
  13290. // if exact number is not found
  13291. if ( end < start )
  13292. return start;
  13293. var mid = start + Math.floor( ( end - start ) / 2 );
  13294. if ( cumulativeAreas[ mid ] > value ) {
  13295. return binarySearch( start, mid - 1 );
  13296. } else if ( cumulativeAreas[ mid ] < value ) {
  13297. return binarySearch( mid + 1, end );
  13298. } else {
  13299. return mid;
  13300. }
  13301. }
  13302. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  13303. return result;
  13304. }
  13305. // pick random face weighted by face area
  13306. var r, index,
  13307. result = [];
  13308. var stats = {};
  13309. for ( i = 0; i < n; i ++ ) {
  13310. r = THREE.GeometryUtils.random() * totalArea;
  13311. index = binarySearchIndices( r );
  13312. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  13313. if ( ! stats[ index ] ) {
  13314. stats[ index ] = 1;
  13315. } else {
  13316. stats[ index ] += 1;
  13317. }
  13318. }
  13319. return result;
  13320. },
  13321. // Get triangle area (by Heron's formula)
  13322. // http://en.wikipedia.org/wiki/Heron%27s_formula
  13323. triangleArea: function ( vectorA, vectorB, vectorC ) {
  13324. var s, a, b, c,
  13325. tmp = THREE.GeometryUtils.__v1;
  13326. tmp.sub( vectorA, vectorB );
  13327. a = tmp.length();
  13328. tmp.sub( vectorA, vectorC );
  13329. b = tmp.length();
  13330. tmp.sub( vectorB, vectorC );
  13331. c = tmp.length();
  13332. s = 0.5 * ( a + b + c );
  13333. return Math.sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
  13334. },
  13335. // Center geometry so that 0,0,0 is in center of bounding box
  13336. center: function ( geometry ) {
  13337. geometry.computeBoundingBox();
  13338. var bb = geometry.boundingBox;
  13339. var offset = new THREE.Vector3();
  13340. offset.add( bb.min, bb.max );
  13341. offset.multiplyScalar( -0.5 );
  13342. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  13343. geometry.computeBoundingBox();
  13344. return offset;
  13345. },
  13346. // Normalize UVs to be from <0,1>
  13347. // (for now just the first set of UVs)
  13348. normalizeUVs: function ( geometry ) {
  13349. var uvSet = geometry.faceVertexUvs[ 0 ];
  13350. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  13351. var uvs = uvSet[ i ];
  13352. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  13353. // texture repeat
  13354. if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
  13355. if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );
  13356. }
  13357. }
  13358. },
  13359. triangulateQuads: function ( geometry ) {
  13360. var i, il, j, jl;
  13361. var faces = [];
  13362. var faceUvs = [];
  13363. var faceVertexUvs = [];
  13364. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  13365. faceUvs[ i ] = [];
  13366. }
  13367. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  13368. faceVertexUvs[ i ] = [];
  13369. }
  13370. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13371. var face = geometry.faces[ i ];
  13372. if ( face instanceof THREE.Face4 ) {
  13373. var a = face.a;
  13374. var b = face.b;
  13375. var c = face.c;
  13376. var d = face.d;
  13377. var triA = new THREE.Face3();
  13378. var triB = new THREE.Face3();
  13379. triA.color.copy( face.color );
  13380. triB.color.copy( face.color );
  13381. triA.materialIndex = face.materialIndex;
  13382. triB.materialIndex = face.materialIndex;
  13383. triA.a = a;
  13384. triA.b = b;
  13385. triA.c = d;
  13386. triB.a = b;
  13387. triB.b = c;
  13388. triB.c = d;
  13389. if ( face.vertexColors.length === 4 ) {
  13390. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  13391. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  13392. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  13393. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  13394. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  13395. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  13396. }
  13397. faces.push( triA, triB );
  13398. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13399. if ( geometry.faceVertexUvs[ j ].length ) {
  13400. var uvs = geometry.faceVertexUvs[ j ][ i ];
  13401. var uvA = uvs[ 0 ];
  13402. var uvB = uvs[ 1 ];
  13403. var uvC = uvs[ 2 ];
  13404. var uvD = uvs[ 3 ];
  13405. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  13406. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  13407. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  13408. }
  13409. }
  13410. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  13411. if ( geometry.faceUvs[ j ].length ) {
  13412. var faceUv = geometry.faceUvs[ j ][ i ];
  13413. faceUvs[ j ].push( faceUv, faceUv );
  13414. }
  13415. }
  13416. } else {
  13417. faces.push( face );
  13418. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  13419. faceUvs[ j ].push( geometry.faceUvs[ j ] );
  13420. }
  13421. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13422. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ] );
  13423. }
  13424. }
  13425. }
  13426. geometry.faces = faces;
  13427. geometry.faceUvs = faceUvs;
  13428. geometry.faceVertexUvs = faceVertexUvs;
  13429. geometry.computeCentroids();
  13430. geometry.computeFaceNormals();
  13431. geometry.computeVertexNormals();
  13432. if ( geometry.hasTangents ) geometry.computeTangents();
  13433. },
  13434. // Make all faces use unique vertices
  13435. // so that each face can be separated from others
  13436. explode: function( geometry ) {
  13437. var vertices = [];
  13438. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13439. var n = vertices.length;
  13440. var face = geometry.faces[ i ];
  13441. if ( face instanceof THREE.Face4 ) {
  13442. var a = face.a;
  13443. var b = face.b;
  13444. var c = face.c;
  13445. var d = face.d;
  13446. var va = geometry.vertices[ a ];
  13447. var vb = geometry.vertices[ b ];
  13448. var vc = geometry.vertices[ c ];
  13449. var vd = geometry.vertices[ d ];
  13450. vertices.push( va.clone() );
  13451. vertices.push( vb.clone() );
  13452. vertices.push( vc.clone() );
  13453. vertices.push( vd.clone() );
  13454. face.a = n;
  13455. face.b = n + 1;
  13456. face.c = n + 2;
  13457. face.d = n + 3;
  13458. } else {
  13459. var a = face.a;
  13460. var b = face.b;
  13461. var c = face.c;
  13462. var va = geometry.vertices[ a ];
  13463. var vb = geometry.vertices[ b ];
  13464. var vc = geometry.vertices[ c ];
  13465. vertices.push( va.clone() );
  13466. vertices.push( vb.clone() );
  13467. vertices.push( vc.clone() );
  13468. face.a = n;
  13469. face.b = n + 1;
  13470. face.c = n + 2;
  13471. }
  13472. }
  13473. geometry.vertices = vertices;
  13474. delete geometry.__tmpVertices;
  13475. },
  13476. // Break faces with edges longer than maxEdgeLength
  13477. // - not recursive
  13478. tessellate: function ( geometry, maxEdgeLength ) {
  13479. var i, il, face,
  13480. a, b, c, d,
  13481. va, vb, vc, vd,
  13482. dab, dbc, dac, dcd, dad,
  13483. m, m1, m2,
  13484. vm, vm1, vm2,
  13485. vnm, vnm1, vnm2,
  13486. vcm, vcm1, vcm2,
  13487. triA, triB,
  13488. quadA, quadB,
  13489. edge;
  13490. var faces = [];
  13491. var faceVertexUvs = [];
  13492. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  13493. faceVertexUvs[ i ] = [];
  13494. }
  13495. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13496. face = geometry.faces[ i ];
  13497. if ( face instanceof THREE.Face3 ) {
  13498. a = face.a;
  13499. b = face.b;
  13500. c = face.c;
  13501. va = geometry.vertices[ a ];
  13502. vb = geometry.vertices[ b ];
  13503. vc = geometry.vertices[ c ];
  13504. dab = va.distanceTo( vb );
  13505. dbc = vb.distanceTo( vc );
  13506. dac = va.distanceTo( vc );
  13507. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  13508. m = geometry.vertices.length;
  13509. triA = face.clone();
  13510. triB = face.clone();
  13511. if ( dab >= dbc && dab >= dac ) {
  13512. vm = va.clone();
  13513. vm.lerpSelf( vb, 0.5 );
  13514. triA.a = a;
  13515. triA.b = m;
  13516. triA.c = c;
  13517. triB.a = m;
  13518. triB.b = b;
  13519. triB.c = c;
  13520. if ( face.vertexNormals.length === 3 ) {
  13521. vnm = face.vertexNormals[ 0 ].clone();
  13522. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  13523. triA.vertexNormals[ 1 ].copy( vnm );
  13524. triB.vertexNormals[ 0 ].copy( vnm );
  13525. }
  13526. if ( face.vertexColors.length === 3 ) {
  13527. vcm = face.vertexColors[ 0 ].clone();
  13528. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  13529. triA.vertexColors[ 1 ].copy( vcm );
  13530. triB.vertexColors[ 0 ].copy( vcm );
  13531. }
  13532. edge = 0;
  13533. } else if ( dbc >= dab && dbc >= dac ) {
  13534. vm = vb.clone();
  13535. vm.lerpSelf( vc, 0.5 );
  13536. triA.a = a;
  13537. triA.b = b;
  13538. triA.c = m;
  13539. triB.a = m;
  13540. triB.b = c;
  13541. triB.c = a;
  13542. if ( face.vertexNormals.length === 3 ) {
  13543. vnm = face.vertexNormals[ 1 ].clone();
  13544. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  13545. triA.vertexNormals[ 2 ].copy( vnm );
  13546. triB.vertexNormals[ 0 ].copy( vnm );
  13547. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  13548. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  13549. }
  13550. if ( face.vertexColors.length === 3 ) {
  13551. vcm = face.vertexColors[ 1 ].clone();
  13552. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  13553. triA.vertexColors[ 2 ].copy( vcm );
  13554. triB.vertexColors[ 0 ].copy( vcm );
  13555. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  13556. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  13557. }
  13558. edge = 1;
  13559. } else {
  13560. vm = va.clone();
  13561. vm.lerpSelf( vc, 0.5 );
  13562. triA.a = a;
  13563. triA.b = b;
  13564. triA.c = m;
  13565. triB.a = m;
  13566. triB.b = b;
  13567. triB.c = c;
  13568. if ( face.vertexNormals.length === 3 ) {
  13569. vnm = face.vertexNormals[ 0 ].clone();
  13570. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  13571. triA.vertexNormals[ 2 ].copy( vnm );
  13572. triB.vertexNormals[ 0 ].copy( vnm );
  13573. }
  13574. if ( face.vertexColors.length === 3 ) {
  13575. vcm = face.vertexColors[ 0 ].clone();
  13576. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  13577. triA.vertexColors[ 2 ].copy( vcm );
  13578. triB.vertexColors[ 0 ].copy( vcm );
  13579. }
  13580. edge = 2;
  13581. }
  13582. faces.push( triA, triB );
  13583. geometry.vertices.push( vm );
  13584. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  13585. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13586. if ( geometry.faceVertexUvs[ j ].length ) {
  13587. uvs = geometry.faceVertexUvs[ j ][ i ];
  13588. uvA = uvs[ 0 ];
  13589. uvB = uvs[ 1 ];
  13590. uvC = uvs[ 2 ];
  13591. // AB
  13592. if ( edge === 0 ) {
  13593. uvM = uvA.clone();
  13594. uvM.lerpSelf( uvB, 0.5 );
  13595. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  13596. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  13597. // BC
  13598. } else if ( edge === 1 ) {
  13599. uvM = uvB.clone();
  13600. uvM.lerpSelf( uvC, 0.5 );
  13601. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  13602. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  13603. // AC
  13604. } else {
  13605. uvM = uvA.clone();
  13606. uvM.lerpSelf( uvC, 0.5 );
  13607. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  13608. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  13609. }
  13610. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  13611. }
  13612. }
  13613. } else {
  13614. faces.push( face );
  13615. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13616. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  13617. }
  13618. }
  13619. } else {
  13620. a = face.a;
  13621. b = face.b;
  13622. c = face.c;
  13623. d = face.d;
  13624. va = geometry.vertices[ a ];
  13625. vb = geometry.vertices[ b ];
  13626. vc = geometry.vertices[ c ];
  13627. vd = geometry.vertices[ d ];
  13628. dab = va.distanceTo( vb );
  13629. dbc = vb.distanceTo( vc );
  13630. dcd = vc.distanceTo( vd );
  13631. dad = va.distanceTo( vd );
  13632. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  13633. m1 = geometry.vertices.length;
  13634. m2 = geometry.vertices.length + 1;
  13635. quadA = face.clone();
  13636. quadB = face.clone();
  13637. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  13638. vm1 = va.clone();
  13639. vm1.lerpSelf( vb, 0.5 );
  13640. vm2 = vc.clone();
  13641. vm2.lerpSelf( vd, 0.5 );
  13642. quadA.a = a;
  13643. quadA.b = m1;
  13644. quadA.c = m2;
  13645. quadA.d = d;
  13646. quadB.a = m1;
  13647. quadB.b = b;
  13648. quadB.c = c;
  13649. quadB.d = m2;
  13650. if ( face.vertexNormals.length === 4 ) {
  13651. vnm1 = face.vertexNormals[ 0 ].clone();
  13652. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  13653. vnm2 = face.vertexNormals[ 2 ].clone();
  13654. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  13655. quadA.vertexNormals[ 1 ].copy( vnm1 );
  13656. quadA.vertexNormals[ 2 ].copy( vnm2 );
  13657. quadB.vertexNormals[ 0 ].copy( vnm1 );
  13658. quadB.vertexNormals[ 3 ].copy( vnm2 );
  13659. }
  13660. if ( face.vertexColors.length === 4 ) {
  13661. vcm1 = face.vertexColors[ 0 ].clone();
  13662. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  13663. vcm2 = face.vertexColors[ 2 ].clone();
  13664. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  13665. quadA.vertexColors[ 1 ].copy( vcm1 );
  13666. quadA.vertexColors[ 2 ].copy( vcm2 );
  13667. quadB.vertexColors[ 0 ].copy( vcm1 );
  13668. quadB.vertexColors[ 3 ].copy( vcm2 );
  13669. }
  13670. edge = 0;
  13671. } else {
  13672. vm1 = vb.clone();
  13673. vm1.lerpSelf( vc, 0.5 );
  13674. vm2 = vd.clone();
  13675. vm2.lerpSelf( va, 0.5 );
  13676. quadA.a = a;
  13677. quadA.b = b;
  13678. quadA.c = m1;
  13679. quadA.d = m2;
  13680. quadB.a = m2;
  13681. quadB.b = m1;
  13682. quadB.c = c;
  13683. quadB.d = d;
  13684. if ( face.vertexNormals.length === 4 ) {
  13685. vnm1 = face.vertexNormals[ 1 ].clone();
  13686. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  13687. vnm2 = face.vertexNormals[ 3 ].clone();
  13688. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  13689. quadA.vertexNormals[ 2 ].copy( vnm1 );
  13690. quadA.vertexNormals[ 3 ].copy( vnm2 );
  13691. quadB.vertexNormals[ 0 ].copy( vnm2 );
  13692. quadB.vertexNormals[ 1 ].copy( vnm1 );
  13693. }
  13694. if ( face.vertexColors.length === 4 ) {
  13695. vcm1 = face.vertexColors[ 1 ].clone();
  13696. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  13697. vcm2 = face.vertexColors[ 3 ].clone();
  13698. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  13699. quadA.vertexColors[ 2 ].copy( vcm1 );
  13700. quadA.vertexColors[ 3 ].copy( vcm2 );
  13701. quadB.vertexColors[ 0 ].copy( vcm2 );
  13702. quadB.vertexColors[ 1 ].copy( vcm1 );
  13703. }
  13704. edge = 1;
  13705. }
  13706. faces.push( quadA, quadB );
  13707. geometry.vertices.push( vm1, vm2 );
  13708. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  13709. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13710. if ( geometry.faceVertexUvs[ j ].length ) {
  13711. uvs = geometry.faceVertexUvs[ j ][ i ];
  13712. uvA = uvs[ 0 ];
  13713. uvB = uvs[ 1 ];
  13714. uvC = uvs[ 2 ];
  13715. uvD = uvs[ 3 ];
  13716. // AB + CD
  13717. if ( edge === 0 ) {
  13718. uvM1 = uvA.clone();
  13719. uvM1.lerpSelf( uvB, 0.5 );
  13720. uvM2 = uvC.clone();
  13721. uvM2.lerpSelf( uvD, 0.5 );
  13722. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  13723. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  13724. // BC + AD
  13725. } else {
  13726. uvM1 = uvB.clone();
  13727. uvM1.lerpSelf( uvC, 0.5 );
  13728. uvM2 = uvD.clone();
  13729. uvM2.lerpSelf( uvA, 0.5 );
  13730. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  13731. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  13732. }
  13733. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  13734. }
  13735. }
  13736. } else {
  13737. faces.push( face );
  13738. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13739. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  13740. }
  13741. }
  13742. }
  13743. }
  13744. geometry.faces = faces;
  13745. geometry.faceVertexUvs = faceVertexUvs;
  13746. }
  13747. };
  13748. THREE.GeometryUtils.random = THREE.Math.random16;
  13749. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  13750. /**
  13751. * @author alteredq / http://alteredqualia.com/
  13752. * @author mrdoob / http://mrdoob.com/
  13753. */
  13754. THREE.ImageUtils = {
  13755. crossOrigin: 'anonymous',
  13756. loadTexture: function ( url, mapping, onLoad, onError ) {
  13757. var image = new Image();
  13758. var texture = new THREE.Texture( image, mapping );
  13759. var loader = new THREE.ImageLoader();
  13760. loader.addEventListener( 'load', function ( event ) {
  13761. texture.image = event.content;
  13762. texture.needsUpdate = true;
  13763. if ( onLoad ) onLoad( texture );
  13764. } );
  13765. loader.addEventListener( 'error', function ( event ) {
  13766. if ( onError ) onError( event.message );
  13767. } );
  13768. loader.crossOrigin = this.crossOrigin;
  13769. loader.load( url, image );
  13770. return texture;
  13771. },
  13772. loadTextureCube: function ( array, mapping, onLoad ) {
  13773. var i, l, images = [];
  13774. var texture = new THREE.Texture( images, mapping );
  13775. texture.flipY = false;
  13776. images.loadCount = 0;
  13777. for ( i = 0, l = array.length; i < l; ++ i ) {
  13778. images[ i ] = new Image();
  13779. images[ i ].onload = function () {
  13780. images.loadCount += 1;
  13781. if ( images.loadCount === 6 ) {
  13782. texture.needsUpdate = true;
  13783. if ( onLoad ) onLoad();
  13784. }
  13785. };
  13786. images[ i ].crossOrigin = this.crossOrigin;
  13787. images[ i ].src = array[ i ];
  13788. }
  13789. return texture;
  13790. },
  13791. getNormalMap: function ( image, depth ) {
  13792. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  13793. var cross = function ( a, b ) {
  13794. 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 ] ];
  13795. }
  13796. var subtract = function ( a, b ) {
  13797. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  13798. }
  13799. var normalize = function ( a ) {
  13800. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  13801. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  13802. }
  13803. depth = depth | 1;
  13804. var width = image.width;
  13805. var height = image.height;
  13806. var canvas = document.createElement( 'canvas' );
  13807. canvas.width = width;
  13808. canvas.height = height;
  13809. var context = canvas.getContext( '2d' );
  13810. context.drawImage( image, 0, 0 );
  13811. var data = context.getImageData( 0, 0, width, height ).data;
  13812. var imageData = context.createImageData( width, height );
  13813. var output = imageData.data;
  13814. for ( var x = 0; x < width; x ++ ) {
  13815. for ( var y = 0; y < height; y ++ ) {
  13816. var ly = y - 1 < 0 ? 0 : y - 1;
  13817. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  13818. var lx = x - 1 < 0 ? 0 : x - 1;
  13819. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  13820. var points = [];
  13821. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  13822. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  13823. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  13824. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  13825. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  13826. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  13827. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  13828. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  13829. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  13830. var normals = [];
  13831. var num_points = points.length;
  13832. for ( var i = 0; i < num_points; i ++ ) {
  13833. var v1 = points[ i ];
  13834. var v2 = points[ ( i + 1 ) % num_points ];
  13835. v1 = subtract( v1, origin );
  13836. v2 = subtract( v2, origin );
  13837. normals.push( normalize( cross( v1, v2 ) ) );
  13838. }
  13839. var normal = [ 0, 0, 0 ];
  13840. for ( var i = 0; i < normals.length; i ++ ) {
  13841. normal[ 0 ] += normals[ i ][ 0 ];
  13842. normal[ 1 ] += normals[ i ][ 1 ];
  13843. normal[ 2 ] += normals[ i ][ 2 ];
  13844. }
  13845. normal[ 0 ] /= normals.length;
  13846. normal[ 1 ] /= normals.length;
  13847. normal[ 2 ] /= normals.length;
  13848. var idx = ( y * width + x ) * 4;
  13849. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  13850. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  13851. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  13852. output[ idx + 3 ] = 255;
  13853. }
  13854. }
  13855. context.putImageData( imageData, 0, 0 );
  13856. return canvas;
  13857. },
  13858. generateDataTexture: function ( width, height, color ) {
  13859. var size = width * height;
  13860. var data = new Uint8Array( 3 * size );
  13861. var r = Math.floor( color.r * 255 );
  13862. var g = Math.floor( color.g * 255 );
  13863. var b = Math.floor( color.b * 255 );
  13864. for ( var i = 0; i < size; i ++ ) {
  13865. data[ i * 3 ] = r;
  13866. data[ i * 3 + 1 ] = g;
  13867. data[ i * 3 + 2 ] = b;
  13868. }
  13869. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  13870. texture.needsUpdate = true;
  13871. return texture;
  13872. }
  13873. };
  13874. /**
  13875. * @author alteredq / http://alteredqualia.com/
  13876. */
  13877. THREE.SceneUtils = {
  13878. showHierarchy : function ( root, visible ) {
  13879. THREE.SceneUtils.traverseHierarchy( root, function( node ) { node.visible = visible; } );
  13880. },
  13881. traverseHierarchy : function ( root, callback ) {
  13882. var n, i, l = root.children.length;
  13883. for ( i = 0; i < l; i ++ ) {
  13884. n = root.children[ i ];
  13885. callback( n );
  13886. THREE.SceneUtils.traverseHierarchy( n, callback );
  13887. }
  13888. },
  13889. createMultiMaterialObject : function ( geometry, materials ) {
  13890. var i, il = materials.length,
  13891. group = new THREE.Object3D();
  13892. for ( i = 0; i < il; i ++ ) {
  13893. var object = new THREE.Mesh( geometry, materials[ i ] );
  13894. group.add( object );
  13895. }
  13896. return group;
  13897. },
  13898. cloneObject: function ( source ) {
  13899. var object;
  13900. // subclass specific properties
  13901. // (must process in order from more specific subclasses to more abstract classes)
  13902. if ( source instanceof THREE.MorphAnimMesh ) {
  13903. object = new THREE.MorphAnimMesh( source.geometry, source.material );
  13904. object.duration = source.duration;
  13905. object.mirroredLoop = source.mirroredLoop;
  13906. object.time = source.time;
  13907. object.lastKeyframe = source.lastKeyframe;
  13908. object.currentKeyframe = source.currentKeyframe;
  13909. object.direction = source.direction;
  13910. object.directionBackwards = source.directionBackwards;
  13911. } else if ( source instanceof THREE.SkinnedMesh ) {
  13912. object = new THREE.SkinnedMesh( source.geometry, source.material );
  13913. } else if ( source instanceof THREE.Mesh ) {
  13914. object = new THREE.Mesh( source.geometry, source.material );
  13915. } else if ( source instanceof THREE.Line ) {
  13916. object = new THREE.Line( source.geometry, source.material, source.type );
  13917. } else if ( source instanceof THREE.Ribbon ) {
  13918. object = new THREE.Ribbon( source.geometry, source.material );
  13919. } else if ( source instanceof THREE.ParticleSystem ) {
  13920. object = new THREE.ParticleSystem( source.geometry, source.material );
  13921. object.sortParticles = source.sortParticles;
  13922. } else if ( source instanceof THREE.Particle ) {
  13923. object = new THREE.Particle( source.material );
  13924. } else if ( source instanceof THREE.Sprite ) {
  13925. object = new THREE.Sprite( {} );
  13926. object.color.copy( source.color );
  13927. object.map = source.map;
  13928. object.blending = source.blending;
  13929. object.useScreenCoordinates = source.useScreenCoordinates;
  13930. object.mergeWith3D = source.mergeWith3D;
  13931. object.affectedByDistance = source.affectedByDistance;
  13932. object.scaleByViewport = source.scaleByViewport;
  13933. object.alignment = source.alignment;
  13934. object.rotation3d.copy( source.rotation3d );
  13935. object.rotation = source.rotation;
  13936. object.opacity = source.opacity;
  13937. object.uvOffset.copy( source.uvOffset );
  13938. object.uvScale.copy( source.uvScale);
  13939. } else if ( source instanceof THREE.LOD ) {
  13940. object = new THREE.LOD();
  13941. /*
  13942. } else if ( source instanceof THREE.MarchingCubes ) {
  13943. object = new THREE.MarchingCubes( source.resolution, source.material );
  13944. object.field.set( source.field );
  13945. object.isolation = source.isolation;
  13946. */
  13947. } else if ( source instanceof THREE.Object3D ) {
  13948. object = new THREE.Object3D();
  13949. }
  13950. // base class properties
  13951. object.name = source.name;
  13952. object.parent = source.parent;
  13953. object.up.copy( source.up );
  13954. object.position.copy( source.position );
  13955. // because of Sprite madness
  13956. if ( object.rotation instanceof THREE.Vector3 )
  13957. object.rotation.copy( source.rotation );
  13958. object.eulerOrder = source.eulerOrder;
  13959. object.scale.copy( source.scale );
  13960. object.dynamic = source.dynamic;
  13961. object.renderDepth = source.renderDepth;
  13962. object.rotationAutoUpdate = source.rotationAutoUpdate;
  13963. object.matrix.copy( source.matrix );
  13964. object.matrixWorld.copy( source.matrixWorld );
  13965. object.matrixRotationWorld.copy( source.matrixRotationWorld );
  13966. object.matrixAutoUpdate = source.matrixAutoUpdate;
  13967. object.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  13968. object.quaternion.copy( source.quaternion );
  13969. object.useQuaternion = source.useQuaternion;
  13970. object.boundRadius = source.boundRadius;
  13971. object.boundRadiusScale = source.boundRadiusScale;
  13972. object.visible = source.visible;
  13973. object.castShadow = source.castShadow;
  13974. object.receiveShadow = source.receiveShadow;
  13975. object.frustumCulled = source.frustumCulled;
  13976. // children
  13977. for ( var i = 0; i < source.children.length; i ++ ) {
  13978. var child = THREE.SceneUtils.cloneObject( source.children[ i ] );
  13979. object.children[ i ] = child;
  13980. child.parent = object;
  13981. }
  13982. // LODs need to be patched separately to use cloned children
  13983. if ( source instanceof THREE.LOD ) {
  13984. for ( var i = 0; i < source.LODs.length; i ++ ) {
  13985. var lod = source.LODs[ i ];
  13986. object.LODs[ i ] = { visibleAtDistance: lod.visibleAtDistance, object3D: object.children[ i ] };
  13987. }
  13988. }
  13989. return object;
  13990. },
  13991. detach : function ( child, parent, scene ) {
  13992. child.applyMatrix( parent.matrixWorld );
  13993. parent.remove( child );
  13994. scene.add( child );
  13995. },
  13996. attach: function ( child, scene, parent ) {
  13997. var matrixWorldInverse = new THREE.Matrix4();
  13998. matrixWorldInverse.getInverse( parent.matrixWorld );
  13999. child.applyMatrix( matrixWorldInverse );
  14000. scene.remove( child );
  14001. parent.add( child );
  14002. }
  14003. };
  14004. /**
  14005. * @author alteredq / http://alteredqualia.com/
  14006. * @author mrdoob / http://mrdoob.com/
  14007. *
  14008. * ShaderUtils currently contains:
  14009. *
  14010. * fresnel
  14011. * normal
  14012. * cube
  14013. *
  14014. */
  14015. if ( THREE.WebGLRenderer ) {
  14016. THREE.ShaderUtils = {
  14017. lib: {
  14018. /* -------------------------------------------------------------------------
  14019. // Fresnel shader
  14020. // - based on Nvidia Cg tutorial
  14021. ------------------------------------------------------------------------- */
  14022. 'fresnel': {
  14023. uniforms: {
  14024. "mRefractionRatio": { type: "f", value: 1.02 },
  14025. "mFresnelBias": { type: "f", value: 0.1 },
  14026. "mFresnelPower": { type: "f", value: 2.0 },
  14027. "mFresnelScale": { type: "f", value: 1.0 },
  14028. "tCube": { type: "t", value: null }
  14029. },
  14030. fragmentShader: [
  14031. "uniform samplerCube tCube;",
  14032. "varying vec3 vReflect;",
  14033. "varying vec3 vRefract[3];",
  14034. "varying float vReflectionFactor;",
  14035. "void main() {",
  14036. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  14037. "vec4 refractedColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
  14038. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  14039. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  14040. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  14041. "refractedColor.a = 1.0;",
  14042. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  14043. "}"
  14044. ].join("\n"),
  14045. vertexShader: [
  14046. "uniform float mRefractionRatio;",
  14047. "uniform float mFresnelBias;",
  14048. "uniform float mFresnelScale;",
  14049. "uniform float mFresnelPower;",
  14050. "varying vec3 vReflect;",
  14051. "varying vec3 vRefract[3];",
  14052. "varying float vReflectionFactor;",
  14053. "void main() {",
  14054. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  14055. "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
  14056. "vec3 nWorld = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
  14057. "vec3 I = mPosition.xyz - cameraPosition;",
  14058. "vReflect = reflect( I, nWorld );",
  14059. "vRefract[0] = refract( normalize( I ), nWorld, mRefractionRatio );",
  14060. "vRefract[1] = refract( normalize( I ), nWorld, mRefractionRatio * 0.99 );",
  14061. "vRefract[2] = refract( normalize( I ), nWorld, mRefractionRatio * 0.98 );",
  14062. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), nWorld ), mFresnelPower );",
  14063. "gl_Position = projectionMatrix * mvPosition;",
  14064. "}"
  14065. ].join("\n")
  14066. },
  14067. /* -------------------------------------------------------------------------
  14068. // Normal map shader
  14069. // - Blinn-Phong
  14070. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  14071. // - point and directional lights (use with "lights: true" material option)
  14072. ------------------------------------------------------------------------- */
  14073. 'normal' : {
  14074. uniforms: THREE.UniformsUtils.merge( [
  14075. THREE.UniformsLib[ "fog" ],
  14076. THREE.UniformsLib[ "lights" ],
  14077. THREE.UniformsLib[ "shadowmap" ],
  14078. {
  14079. "enableAO" : { type: "i", value: 0 },
  14080. "enableDiffuse" : { type: "i", value: 0 },
  14081. "enableSpecular" : { type: "i", value: 0 },
  14082. "enableReflection": { type: "i", value: 0 },
  14083. "enableDisplacement": { type: "i", value: 0 },
  14084. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  14085. "tDiffuse" : { type: "t", value: null },
  14086. "tCube" : { type: "t", value: null },
  14087. "tNormal" : { type: "t", value: null },
  14088. "tSpecular" : { type: "t", value: null },
  14089. "tAO" : { type: "t", value: null },
  14090. "uNormalScale": { type: "f", value: 1.0 },
  14091. "uDisplacementBias": { type: "f", value: 0.0 },
  14092. "uDisplacementScale": { type: "f", value: 1.0 },
  14093. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  14094. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  14095. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  14096. "uShininess": { type: "f", value: 30 },
  14097. "uOpacity": { type: "f", value: 1 },
  14098. "useRefract": { type: "i", value: 0 },
  14099. "uRefractionRatio": { type: "f", value: 0.98 },
  14100. "uReflectivity": { type: "f", value: 0.5 },
  14101. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  14102. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  14103. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  14104. }
  14105. ] ),
  14106. fragmentShader: [
  14107. "uniform vec3 uAmbientColor;",
  14108. "uniform vec3 uDiffuseColor;",
  14109. "uniform vec3 uSpecularColor;",
  14110. "uniform float uShininess;",
  14111. "uniform float uOpacity;",
  14112. "uniform bool enableDiffuse;",
  14113. "uniform bool enableSpecular;",
  14114. "uniform bool enableAO;",
  14115. "uniform bool enableReflection;",
  14116. "uniform sampler2D tDiffuse;",
  14117. "uniform sampler2D tNormal;",
  14118. "uniform sampler2D tSpecular;",
  14119. "uniform sampler2D tAO;",
  14120. "uniform samplerCube tCube;",
  14121. "uniform float uNormalScale;",
  14122. "uniform bool useRefract;",
  14123. "uniform float uRefractionRatio;",
  14124. "uniform float uReflectivity;",
  14125. "varying vec3 vTangent;",
  14126. "varying vec3 vBinormal;",
  14127. "varying vec3 vNormal;",
  14128. "varying vec2 vUv;",
  14129. "uniform vec3 ambientLightColor;",
  14130. "#if MAX_DIR_LIGHTS > 0",
  14131. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  14132. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  14133. "#endif",
  14134. "#if MAX_POINT_LIGHTS > 0",
  14135. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  14136. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  14137. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  14138. "#endif",
  14139. "#if MAX_SPOT_LIGHTS > 0",
  14140. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  14141. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  14142. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  14143. "uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
  14144. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  14145. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  14146. "#endif",
  14147. "#ifdef WRAP_AROUND",
  14148. "uniform vec3 wrapRGB;",
  14149. "#endif",
  14150. "varying vec3 vWorldPosition;",
  14151. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14152. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14153. "void main() {",
  14154. "vec3 vViewPosition = cameraPosition - vWorldPosition;",
  14155. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  14156. "vec3 specularTex = vec3( 1.0 );",
  14157. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  14158. "normalTex.xy *= uNormalScale;",
  14159. "normalTex = normalize( normalTex );",
  14160. "if( enableDiffuse ) {",
  14161. "#ifdef GAMMA_INPUT",
  14162. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  14163. "texelColor.xyz *= texelColor.xyz;",
  14164. "gl_FragColor = gl_FragColor * texelColor;",
  14165. "#else",
  14166. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  14167. "#endif",
  14168. "}",
  14169. "if( enableAO ) {",
  14170. "#ifdef GAMMA_INPUT",
  14171. "vec4 aoColor = texture2D( tAO, vUv );",
  14172. "aoColor.xyz *= aoColor.xyz;",
  14173. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  14174. "#else",
  14175. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  14176. "#endif",
  14177. "}",
  14178. "if( enableSpecular )",
  14179. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  14180. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  14181. "vec3 finalNormal = tsb * normalTex;",
  14182. "vec3 normal = normalize( finalNormal );",
  14183. "vec3 viewPosition = normalize( vViewPosition );",
  14184. // point lights
  14185. "#if MAX_POINT_LIGHTS > 0",
  14186. "vec3 pointDiffuse = vec3( 0.0 );",
  14187. "vec3 pointSpecular = vec3( 0.0 );",
  14188. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  14189. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  14190. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  14191. "float pointDistance = 1.0;",
  14192. "if ( pointLightDistance[ i ] > 0.0 )",
  14193. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  14194. "pointVector = normalize( pointVector );",
  14195. // diffuse
  14196. "#ifdef WRAP_AROUND",
  14197. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  14198. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  14199. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  14200. "#else",
  14201. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  14202. "#endif",
  14203. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  14204. // specular
  14205. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  14206. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  14207. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  14208. "#ifdef PHYSICALLY_BASED_SHADING",
  14209. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14210. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14211. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  14212. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  14213. "#else",
  14214. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  14215. "#endif",
  14216. "}",
  14217. "#endif",
  14218. // spot lights
  14219. "#if MAX_SPOT_LIGHTS > 0",
  14220. "vec3 spotDiffuse = vec3( 0.0 );",
  14221. "vec3 spotSpecular = vec3( 0.0 );",
  14222. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  14223. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  14224. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  14225. "float spotDistance = 1.0;",
  14226. "if ( spotLightDistance[ i ] > 0.0 )",
  14227. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  14228. "spotVector = normalize( spotVector );",
  14229. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  14230. "if ( spotEffect > spotLightAngle[ i ] ) {",
  14231. "spotEffect = pow( spotEffect, spotLightExponent[ i ] );",
  14232. // diffuse
  14233. "#ifdef WRAP_AROUND",
  14234. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  14235. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  14236. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  14237. "#else",
  14238. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  14239. "#endif",
  14240. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  14241. // specular
  14242. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  14243. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  14244. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  14245. "#ifdef PHYSICALLY_BASED_SHADING",
  14246. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14247. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14248. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  14249. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  14250. "#else",
  14251. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  14252. "#endif",
  14253. "}",
  14254. "}",
  14255. "#endif",
  14256. // directional lights
  14257. "#if MAX_DIR_LIGHTS > 0",
  14258. "vec3 dirDiffuse = vec3( 0.0 );",
  14259. "vec3 dirSpecular = vec3( 0.0 );",
  14260. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  14261. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  14262. "vec3 dirVector = normalize( lDirection.xyz );",
  14263. // diffuse
  14264. "#ifdef WRAP_AROUND",
  14265. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  14266. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  14267. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  14268. "#else",
  14269. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  14270. "#endif",
  14271. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  14272. // specular
  14273. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  14274. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  14275. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  14276. "#ifdef PHYSICALLY_BASED_SHADING",
  14277. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14278. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14279. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  14280. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  14281. "#else",
  14282. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  14283. "#endif",
  14284. "}",
  14285. "#endif",
  14286. // all lights contribution summation
  14287. "vec3 totalDiffuse = vec3( 0.0 );",
  14288. "vec3 totalSpecular = vec3( 0.0 );",
  14289. "#if MAX_DIR_LIGHTS > 0",
  14290. "totalDiffuse += dirDiffuse;",
  14291. "totalSpecular += dirSpecular;",
  14292. "#endif",
  14293. "#if MAX_POINT_LIGHTS > 0",
  14294. "totalDiffuse += pointDiffuse;",
  14295. "totalSpecular += pointSpecular;",
  14296. "#endif",
  14297. "#if MAX_SPOT_LIGHTS > 0",
  14298. "totalDiffuse += spotDiffuse;",
  14299. "totalSpecular += spotSpecular;",
  14300. "#endif",
  14301. "#ifdef METAL",
  14302. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  14303. "#else",
  14304. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  14305. "#endif",
  14306. "if ( enableReflection ) {",
  14307. "vec3 vReflect;",
  14308. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  14309. "if ( useRefract ) {",
  14310. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  14311. "} else {",
  14312. "vReflect = reflect( cameraToVertex, normal );",
  14313. "}",
  14314. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  14315. "#ifdef GAMMA_INPUT",
  14316. "cubeColor.xyz *= cubeColor.xyz;",
  14317. "#endif",
  14318. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  14319. "}",
  14320. THREE.ShaderChunk[ "shadowmap_fragment" ],
  14321. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  14322. THREE.ShaderChunk[ "fog_fragment" ],
  14323. "}"
  14324. ].join("\n"),
  14325. vertexShader: [
  14326. "attribute vec4 tangent;",
  14327. "uniform vec2 uOffset;",
  14328. "uniform vec2 uRepeat;",
  14329. "uniform bool enableDisplacement;",
  14330. "#ifdef VERTEX_TEXTURES",
  14331. "uniform sampler2D tDisplacement;",
  14332. "uniform float uDisplacementScale;",
  14333. "uniform float uDisplacementBias;",
  14334. "#endif",
  14335. "varying vec3 vTangent;",
  14336. "varying vec3 vBinormal;",
  14337. "varying vec3 vNormal;",
  14338. "varying vec2 vUv;",
  14339. "varying vec3 vWorldPosition;",
  14340. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14341. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  14342. "void main() {",
  14343. THREE.ShaderChunk[ "skinbase_vertex" ],
  14344. THREE.ShaderChunk[ "skinnormal_vertex" ],
  14345. // normal, tangent and binormal vectors
  14346. "#ifdef USE_SKINNING",
  14347. "vNormal = normalMatrix * skinnedNormal.xyz;",
  14348. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  14349. "vTangent = normalMatrix * skinnedTangent.xyz;",
  14350. "#else",
  14351. "vNormal = normalMatrix * normal;",
  14352. "vTangent = normalMatrix * tangent.xyz;",
  14353. "#endif",
  14354. "vBinormal = cross( vNormal, vTangent ) * tangent.w;",
  14355. "vUv = uv * uRepeat + uOffset;",
  14356. // displacement mapping
  14357. "vec3 displacedPosition;",
  14358. "#ifdef VERTEX_TEXTURES",
  14359. "if ( enableDisplacement ) {",
  14360. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  14361. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  14362. "displacedPosition = position + normalize( normal ) * df;",
  14363. "} else {",
  14364. "#ifdef USE_SKINNING",
  14365. "vec4 skinVertex = vec4( position, 1.0 );",
  14366. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  14367. "skinned += boneMatY * skinVertex * skinWeight.y;",
  14368. "displacedPosition = skinned.xyz;",
  14369. "#else",
  14370. "displacedPosition = position;",
  14371. "#endif",
  14372. "}",
  14373. "#else",
  14374. "#ifdef USE_SKINNING",
  14375. "vec4 skinVertex = vec4( position, 1.0 );",
  14376. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  14377. "skinned += boneMatY * skinVertex * skinWeight.y;",
  14378. "displacedPosition = skinned.xyz;",
  14379. "#else",
  14380. "displacedPosition = position;",
  14381. "#endif",
  14382. "#endif",
  14383. //
  14384. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  14385. "vec4 mPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  14386. "gl_Position = projectionMatrix * mvPosition;",
  14387. //
  14388. "vWorldPosition = mPosition.xyz;",
  14389. // shadows
  14390. "#ifdef USE_SHADOWMAP",
  14391. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  14392. "vShadowCoord[ i ] = shadowMatrix[ i ] * mPosition;",
  14393. "}",
  14394. "#endif",
  14395. "}"
  14396. ].join("\n")
  14397. },
  14398. /* -------------------------------------------------------------------------
  14399. // Cube map shader
  14400. ------------------------------------------------------------------------- */
  14401. 'cube': {
  14402. uniforms: { "tCube": { type: "t", value: null },
  14403. "tFlip": { type: "f", value: -1 } },
  14404. vertexShader: [
  14405. "varying vec3 vViewPosition;",
  14406. "void main() {",
  14407. "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
  14408. "vViewPosition = cameraPosition - mPosition.xyz;",
  14409. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  14410. "}"
  14411. ].join("\n"),
  14412. fragmentShader: [
  14413. "uniform samplerCube tCube;",
  14414. "uniform float tFlip;",
  14415. "varying vec3 vViewPosition;",
  14416. "void main() {",
  14417. "vec3 wPos = cameraPosition - vViewPosition;",
  14418. "gl_FragColor = textureCube( tCube, vec3( tFlip * wPos.x, wPos.yz ) );",
  14419. "}"
  14420. ].join("\n")
  14421. }
  14422. }
  14423. };
  14424. };
  14425. /**
  14426. * @author zz85 / http://www.lab4games.net/zz85/blog
  14427. * @author alteredq / http://alteredqualia.com/
  14428. *
  14429. * For Text operations in three.js (See TextGeometry)
  14430. *
  14431. * It uses techniques used in:
  14432. *
  14433. * typeface.js and canvastext
  14434. * For converting fonts and rendering with javascript
  14435. * http://typeface.neocracy.org
  14436. *
  14437. * Triangulation ported from AS3
  14438. * Simple Polygon Triangulation
  14439. * http://actionsnippet.com/?p=1462
  14440. *
  14441. * A Method to triangulate shapes with holes
  14442. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  14443. *
  14444. */
  14445. THREE.FontUtils = {
  14446. faces : {},
  14447. // Just for now. face[weight][style]
  14448. face : "helvetiker",
  14449. weight: "normal",
  14450. style : "normal",
  14451. size : 150,
  14452. divisions : 10,
  14453. getFace : function() {
  14454. return this.faces[ this.face ][ this.weight ][ this.style ];
  14455. },
  14456. loadFace : function( data ) {
  14457. var family = data.familyName.toLowerCase();
  14458. var ThreeFont = this;
  14459. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  14460. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  14461. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  14462. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  14463. return data;
  14464. },
  14465. drawText : function( text ) {
  14466. var characterPts = [], allPts = [];
  14467. // RenderText
  14468. var i, p,
  14469. face = this.getFace(),
  14470. scale = this.size / face.resolution,
  14471. offset = 0,
  14472. chars = String( text ).split( '' ),
  14473. length = chars.length;
  14474. var fontPaths = [];
  14475. for ( i = 0; i < length; i ++ ) {
  14476. var path = new THREE.Path();
  14477. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  14478. offset += ret.offset;
  14479. fontPaths.push( ret.path );
  14480. }
  14481. // get the width
  14482. var width = offset / 2;
  14483. //
  14484. // for ( p = 0; p < allPts.length; p++ ) {
  14485. //
  14486. // allPts[ p ].x -= width;
  14487. //
  14488. // }
  14489. //var extract = this.extractPoints( allPts, characterPts );
  14490. //extract.contour = allPts;
  14491. //extract.paths = fontPaths;
  14492. //extract.offset = width;
  14493. return { paths : fontPaths, offset : width };
  14494. },
  14495. extractGlyphPoints : function( c, face, scale, offset, path ) {
  14496. var pts = [];
  14497. var i, i2, divisions,
  14498. outline, action, length,
  14499. scaleX, scaleY,
  14500. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  14501. laste,
  14502. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  14503. if ( !glyph ) return;
  14504. if ( glyph.o ) {
  14505. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  14506. length = outline.length;
  14507. scaleX = scale;
  14508. scaleY = scale;
  14509. for ( i = 0; i < length; ) {
  14510. action = outline[ i ++ ];
  14511. //console.log( action );
  14512. switch( action ) {
  14513. case 'm':
  14514. // Move To
  14515. x = outline[ i++ ] * scaleX + offset;
  14516. y = outline[ i++ ] * scaleY;
  14517. path.moveTo( x, y );
  14518. break;
  14519. case 'l':
  14520. // Line To
  14521. x = outline[ i++ ] * scaleX + offset;
  14522. y = outline[ i++ ] * scaleY;
  14523. path.lineTo(x,y);
  14524. break;
  14525. case 'q':
  14526. // QuadraticCurveTo
  14527. cpx = outline[ i++ ] * scaleX + offset;
  14528. cpy = outline[ i++ ] * scaleY;
  14529. cpx1 = outline[ i++ ] * scaleX + offset;
  14530. cpy1 = outline[ i++ ] * scaleY;
  14531. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  14532. laste = pts[ pts.length - 1 ];
  14533. if ( laste ) {
  14534. cpx0 = laste.x;
  14535. cpy0 = laste.y;
  14536. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  14537. var t = i2 / divisions;
  14538. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  14539. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  14540. }
  14541. }
  14542. break;
  14543. case 'b':
  14544. // Cubic Bezier Curve
  14545. cpx = outline[ i++ ] * scaleX + offset;
  14546. cpy = outline[ i++ ] * scaleY;
  14547. cpx1 = outline[ i++ ] * scaleX + offset;
  14548. cpy1 = outline[ i++ ] * -scaleY;
  14549. cpx2 = outline[ i++ ] * scaleX + offset;
  14550. cpy2 = outline[ i++ ] * -scaleY;
  14551. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  14552. laste = pts[ pts.length - 1 ];
  14553. if ( laste ) {
  14554. cpx0 = laste.x;
  14555. cpy0 = laste.y;
  14556. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  14557. var t = i2 / divisions;
  14558. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  14559. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  14560. }
  14561. }
  14562. break;
  14563. }
  14564. }
  14565. }
  14566. return { offset: glyph.ha*scale, path:path};
  14567. }
  14568. };
  14569. THREE.FontUtils.generateShapes = function( text, parameters ) {
  14570. // Parameters
  14571. parameters = parameters || {};
  14572. var size = parameters.size !== undefined ? parameters.size : 100;
  14573. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  14574. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  14575. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  14576. var style = parameters.style !== undefined ? parameters.style : "normal";
  14577. THREE.FontUtils.size = size;
  14578. THREE.FontUtils.divisions = curveSegments;
  14579. THREE.FontUtils.face = font;
  14580. THREE.FontUtils.weight = weight;
  14581. THREE.FontUtils.style = style;
  14582. // Get a Font data json object
  14583. var data = THREE.FontUtils.drawText( text );
  14584. var paths = data.paths;
  14585. var shapes = [];
  14586. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  14587. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  14588. }
  14589. return shapes;
  14590. };
  14591. /**
  14592. * This code is a quick port of code written in C++ which was submitted to
  14593. * flipcode.com by John W. Ratcliff // July 22, 2000
  14594. * See original code and more information here:
  14595. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  14596. *
  14597. * ported to actionscript by Zevan Rosser
  14598. * www.actionsnippet.com
  14599. *
  14600. * ported to javascript by Joshua Koo
  14601. * http://www.lab4games.net/zz85/blog
  14602. *
  14603. */
  14604. ( function( namespace ) {
  14605. var EPSILON = 0.0000000001;
  14606. // takes in an contour array and returns
  14607. var process = function( contour, indices ) {
  14608. var n = contour.length;
  14609. if ( n < 3 ) return null;
  14610. var result = [],
  14611. verts = [],
  14612. vertIndices = [];
  14613. /* we want a counter-clockwise polygon in verts */
  14614. var u, v, w;
  14615. if ( area( contour ) > 0.0 ) {
  14616. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  14617. } else {
  14618. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  14619. }
  14620. var nv = n;
  14621. /* remove nv - 2 vertices, creating 1 triangle every time */
  14622. var count = 2 * nv; /* error detection */
  14623. for( v = nv - 1; nv > 2; ) {
  14624. /* if we loop, it is probably a non-simple polygon */
  14625. if ( ( count-- ) <= 0 ) {
  14626. //** Triangulate: ERROR - probable bad polygon!
  14627. //throw ( "Warning, unable to triangulate polygon!" );
  14628. //return null;
  14629. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  14630. console.log( "Warning, unable to triangulate polygon!" );
  14631. if ( indices ) return vertIndices;
  14632. return result;
  14633. }
  14634. /* three consecutive vertices in current polygon, <u,v,w> */
  14635. u = v; if ( nv <= u ) u = 0; /* previous */
  14636. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  14637. w = v + 1; if ( nv <= w ) w = 0; /* next */
  14638. if ( snip( contour, u, v, w, nv, verts ) ) {
  14639. var a, b, c, s, t;
  14640. /* true names of the vertices */
  14641. a = verts[ u ];
  14642. b = verts[ v ];
  14643. c = verts[ w ];
  14644. /* output Triangle */
  14645. /*
  14646. result.push( contour[ a ] );
  14647. result.push( contour[ b ] );
  14648. result.push( contour[ c ] );
  14649. */
  14650. result.push( [ contour[ a ],
  14651. contour[ b ],
  14652. contour[ c ] ] );
  14653. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  14654. /* remove v from the remaining polygon */
  14655. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  14656. verts[ s ] = verts[ t ];
  14657. }
  14658. nv--;
  14659. /* reset error detection counter */
  14660. count = 2 * nv;
  14661. }
  14662. }
  14663. if ( indices ) return vertIndices;
  14664. return result;
  14665. };
  14666. // calculate area of the contour polygon
  14667. var area = function ( contour ) {
  14668. var n = contour.length;
  14669. var a = 0.0;
  14670. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  14671. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  14672. }
  14673. return a * 0.5;
  14674. };
  14675. // see if p is inside triangle abc
  14676. var insideTriangle = function( ax, ay,
  14677. bx, by,
  14678. cx, cy,
  14679. px, py ) {
  14680. var aX, aY, bX, bY;
  14681. var cX, cY, apx, apy;
  14682. var bpx, bpy, cpx, cpy;
  14683. var cCROSSap, bCROSScp, aCROSSbp;
  14684. aX = cx - bx; aY = cy - by;
  14685. bX = ax - cx; bY = ay - cy;
  14686. cX = bx - ax; cY = by - ay;
  14687. apx= px -ax; apy= py - ay;
  14688. bpx= px - bx; bpy= py - by;
  14689. cpx= px - cx; cpy= py - cy;
  14690. aCROSSbp = aX*bpy - aY*bpx;
  14691. cCROSSap = cX*apy - cY*apx;
  14692. bCROSScp = bX*cpy - bY*cpx;
  14693. return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
  14694. };
  14695. var snip = function ( contour, u, v, w, n, verts ) {
  14696. var p;
  14697. var ax, ay, bx, by;
  14698. var cx, cy, px, py;
  14699. ax = contour[ verts[ u ] ].x;
  14700. ay = contour[ verts[ u ] ].y;
  14701. bx = contour[ verts[ v ] ].x;
  14702. by = contour[ verts[ v ] ].y;
  14703. cx = contour[ verts[ w ] ].x;
  14704. cy = contour[ verts[ w ] ].y;
  14705. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  14706. for ( p = 0; p < n; p++ ) {
  14707. if( (p == u) || (p == v) || (p == w) ) continue;
  14708. px = contour[ verts[ p ] ].x
  14709. py = contour[ verts[ p ] ].y
  14710. if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;
  14711. }
  14712. return true;
  14713. };
  14714. namespace.Triangulate = process;
  14715. namespace.Triangulate.area = area;
  14716. return namespace;
  14717. })(THREE.FontUtils);
  14718. // To use the typeface.js face files, hook up the API
  14719. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  14720. * @author zz85 / http://www.lab4games.net/zz85/blog
  14721. * Extensible curve object
  14722. *
  14723. * Some common of Curve methods
  14724. * .getPoint(t), getTangent(t)
  14725. * .getPointAt(u), getTagentAt(u)
  14726. * .getPoints(), .getSpacedPoints()
  14727. * .getLength()
  14728. * .updateArcLengths()
  14729. *
  14730. * This file contains following classes:
  14731. *
  14732. * -- 2d classes --
  14733. * THREE.Curve
  14734. * THREE.LineCurve
  14735. * THREE.QuadraticBezierCurve
  14736. * THREE.CubicBezierCurve
  14737. * THREE.SplineCurve
  14738. * THREE.ArcCurve
  14739. * THREE.EllipseCurve
  14740. *
  14741. * -- 3d classes --
  14742. * THREE.LineCurve3
  14743. * THREE.QuadraticBezierCurve3
  14744. * THREE.CubicBezierCurve3
  14745. * THREE.SplineCurve3
  14746. * THREE.ClosedSplineCurve3
  14747. *
  14748. * A series of curves can be represented as a THREE.CurvePath
  14749. *
  14750. **/
  14751. /**************************************************************
  14752. * Abstract Curve base class
  14753. **************************************************************/
  14754. THREE.Curve = function () {
  14755. };
  14756. // Virtual base class method to overwrite and implement in subclasses
  14757. // - t [0 .. 1]
  14758. THREE.Curve.prototype.getPoint = function ( t ) {
  14759. console.log( "Warning, getPoint() not implemented!" );
  14760. return null;
  14761. };
  14762. // Get point at relative position in curve according to arc length
  14763. // - u [0 .. 1]
  14764. THREE.Curve.prototype.getPointAt = function ( u ) {
  14765. var t = this.getUtoTmapping( u );
  14766. return this.getPoint( t );
  14767. };
  14768. // Get sequence of points using getPoint( t )
  14769. THREE.Curve.prototype.getPoints = function ( divisions ) {
  14770. if ( !divisions ) divisions = 5;
  14771. var d, pts = [];
  14772. for ( d = 0; d <= divisions; d ++ ) {
  14773. pts.push( this.getPoint( d / divisions ) );
  14774. }
  14775. return pts;
  14776. };
  14777. // Get sequence of points using getPointAt( u )
  14778. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  14779. if ( !divisions ) divisions = 5;
  14780. var d, pts = [];
  14781. for ( d = 0; d <= divisions; d ++ ) {
  14782. pts.push( this.getPointAt( d / divisions ) );
  14783. }
  14784. return pts;
  14785. };
  14786. // Get total curve arc length
  14787. THREE.Curve.prototype.getLength = function () {
  14788. var lengths = this.getLengths();
  14789. return lengths[ lengths.length - 1 ];
  14790. };
  14791. // Get list of cumulative segment lengths
  14792. THREE.Curve.prototype.getLengths = function ( divisions ) {
  14793. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  14794. if ( this.cacheArcLengths
  14795. && ( this.cacheArcLengths.length == divisions + 1 )
  14796. && !this.needsUpdate) {
  14797. //console.log( "cached", this.cacheArcLengths );
  14798. return this.cacheArcLengths;
  14799. }
  14800. this.needsUpdate = false;
  14801. var cache = [];
  14802. var current, last = this.getPoint( 0 );
  14803. var p, sum = 0;
  14804. cache.push( 0 );
  14805. for ( p = 1; p <= divisions; p ++ ) {
  14806. current = this.getPoint ( p / divisions );
  14807. sum += current.distanceTo( last );
  14808. cache.push( sum );
  14809. last = current;
  14810. }
  14811. this.cacheArcLengths = cache;
  14812. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  14813. };
  14814. THREE.Curve.prototype.updateArcLengths = function() {
  14815. this.needsUpdate = true;
  14816. this.getLengths();
  14817. };
  14818. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  14819. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  14820. var arcLengths = this.getLengths();
  14821. var i = 0, il = arcLengths.length;
  14822. var targetArcLength; // The targeted u distance value to get
  14823. if ( distance ) {
  14824. targetArcLength = distance;
  14825. } else {
  14826. targetArcLength = u * arcLengths[ il - 1 ];
  14827. }
  14828. //var time = Date.now();
  14829. // binary search for the index with largest value smaller than target u distance
  14830. var low = 0, high = il - 1, comparison;
  14831. while ( low <= high ) {
  14832. 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
  14833. comparison = arcLengths[ i ] - targetArcLength;
  14834. if ( comparison < 0 ) {
  14835. low = i + 1;
  14836. continue;
  14837. } else if ( comparison > 0 ) {
  14838. high = i - 1;
  14839. continue;
  14840. } else {
  14841. high = i;
  14842. break;
  14843. // DONE
  14844. }
  14845. }
  14846. i = high;
  14847. //console.log('b' , i, low, high, Date.now()- time);
  14848. if ( arcLengths[ i ] == targetArcLength ) {
  14849. var t = i / ( il - 1 );
  14850. return t;
  14851. }
  14852. // we could get finer grain at lengths, or use simple interpolatation between two points
  14853. var lengthBefore = arcLengths[ i ];
  14854. var lengthAfter = arcLengths[ i + 1 ];
  14855. var segmentLength = lengthAfter - lengthBefore;
  14856. // determine where we are between the 'before' and 'after' points
  14857. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  14858. // add that fractional amount to t
  14859. var t = ( i + segmentFraction ) / ( il -1 );
  14860. return t;
  14861. };
  14862. // In 2D space, there are actually 2 normal vectors,
  14863. // and in 3D space, infinte
  14864. // TODO this should be depreciated.
  14865. THREE.Curve.prototype.getNormalVector = function( t ) {
  14866. var vec = this.getTangent( t );
  14867. return new THREE.Vector2( -vec.y , vec.x );
  14868. };
  14869. // Returns a unit vector tangent at t
  14870. // In case any sub curve does not implement its tangent / normal finding,
  14871. // we get 2 points with a small delta and find a gradient of the 2 points
  14872. // which seems to make a reasonable approximation
  14873. THREE.Curve.prototype.getTangent = function( t ) {
  14874. var delta = 0.0001;
  14875. var t1 = t - delta;
  14876. var t2 = t + delta;
  14877. // Capping in case of danger
  14878. if ( t1 < 0 ) t1 = 0;
  14879. if ( t2 > 1 ) t2 = 1;
  14880. var pt1 = this.getPoint( t1 );
  14881. var pt2 = this.getPoint( t2 );
  14882. var vec = pt2.clone().subSelf(pt1);
  14883. return vec.normalize();
  14884. };
  14885. THREE.Curve.prototype.getTangentAt = function ( u ) {
  14886. var t = this.getUtoTmapping( u );
  14887. return this.getTangent( t );
  14888. };
  14889. /**************************************************************
  14890. * Line
  14891. **************************************************************/
  14892. THREE.LineCurve = function ( v1, v2 ) {
  14893. this.v1 = v1;
  14894. this.v2 = v2;
  14895. };
  14896. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  14897. THREE.LineCurve.prototype.getPoint = function ( t ) {
  14898. var point = this.v2.clone().subSelf(this.v1);
  14899. point.multiplyScalar( t ).addSelf( this.v1 );
  14900. return point;
  14901. };
  14902. // Line curve is linear, so we can overwrite default getPointAt
  14903. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  14904. return this.getPoint( u );
  14905. };
  14906. THREE.LineCurve.prototype.getTangent = function( t ) {
  14907. var tangent = this.v2.clone().subSelf(this.v1);
  14908. return tangent.normalize();
  14909. };
  14910. /**************************************************************
  14911. * Quadratic Bezier curve
  14912. **************************************************************/
  14913. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  14914. this.v0 = v0;
  14915. this.v1 = v1;
  14916. this.v2 = v2;
  14917. };
  14918. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  14919. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  14920. var tx, ty;
  14921. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  14922. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  14923. return new THREE.Vector2( tx, ty );
  14924. };
  14925. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  14926. var tx, ty;
  14927. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  14928. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  14929. // returns unit vector
  14930. var tangent = new THREE.Vector2( tx, ty );
  14931. tangent.normalize();
  14932. return tangent;
  14933. };
  14934. /**************************************************************
  14935. * Cubic Bezier curve
  14936. **************************************************************/
  14937. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  14938. this.v0 = v0;
  14939. this.v1 = v1;
  14940. this.v2 = v2;
  14941. this.v3 = v3;
  14942. };
  14943. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  14944. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  14945. var tx, ty;
  14946. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  14947. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  14948. return new THREE.Vector2( tx, ty );
  14949. };
  14950. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  14951. var tx, ty;
  14952. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  14953. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  14954. var tangent = new THREE.Vector2( tx, ty );
  14955. tangent.normalize();
  14956. return tangent;
  14957. };
  14958. /**************************************************************
  14959. * Spline curve
  14960. **************************************************************/
  14961. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  14962. this.points = (points == undefined) ? [] : points;
  14963. };
  14964. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  14965. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  14966. var v = new THREE.Vector2();
  14967. var c = [];
  14968. var points = this.points, point, intPoint, weight;
  14969. point = ( points.length - 1 ) * t;
  14970. intPoint = Math.floor( point );
  14971. weight = point - intPoint;
  14972. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  14973. c[ 1 ] = intPoint;
  14974. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  14975. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  14976. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  14977. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  14978. return v;
  14979. };
  14980. /**************************************************************
  14981. * Ellipse curve
  14982. **************************************************************/
  14983. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  14984. aStartAngle, aEndAngle,
  14985. aClockwise ) {
  14986. this.aX = aX;
  14987. this.aY = aY;
  14988. this.xRadius = xRadius;
  14989. this.yRadius = yRadius;
  14990. this.aStartAngle = aStartAngle;
  14991. this.aEndAngle = aEndAngle;
  14992. this.aClockwise = aClockwise;
  14993. };
  14994. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  14995. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  14996. var deltaAngle = this.aEndAngle - this.aStartAngle;
  14997. if ( !this.aClockwise ) {
  14998. t = 1 - t;
  14999. }
  15000. var angle = this.aStartAngle + t * deltaAngle;
  15001. var tx = this.aX + this.xRadius * Math.cos( angle );
  15002. var ty = this.aY + this.yRadius * Math.sin( angle );
  15003. return new THREE.Vector2( tx, ty );
  15004. };
  15005. /**************************************************************
  15006. * Arc curve
  15007. **************************************************************/
  15008. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  15009. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  15010. };
  15011. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  15012. /**************************************************************
  15013. * Utils
  15014. **************************************************************/
  15015. THREE.Curve.Utils = {
  15016. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  15017. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  15018. },
  15019. // Puay Bing, thanks for helping with this derivative!
  15020. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  15021. return -3 * p0 * (1 - t) * (1 - t) +
  15022. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  15023. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  15024. 3 * t * t * p3;
  15025. },
  15026. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  15027. // To check if my formulas are correct
  15028. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  15029. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  15030. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  15031. var h11 = 3 * t * t - 2 * t; // t3 − t2
  15032. return h00 + h10 + h01 + h11;
  15033. },
  15034. // Catmull-Rom
  15035. interpolate: function( p0, p1, p2, p3, t ) {
  15036. var v0 = ( p2 - p0 ) * 0.5;
  15037. var v1 = ( p3 - p1 ) * 0.5;
  15038. var t2 = t * t;
  15039. var t3 = t * t2;
  15040. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  15041. }
  15042. };
  15043. // TODO: Transformation for Curves?
  15044. /**************************************************************
  15045. * 3D Curves
  15046. **************************************************************/
  15047. // A Factory method for creating new curve subclasses
  15048. THREE.Curve.create = function ( constructor, getPointFunc ) {
  15049. constructor.prototype = Object.create( THREE.Curve.prototype );
  15050. constructor.prototype.getPoint = getPointFunc;
  15051. return constructor;
  15052. };
  15053. /**************************************************************
  15054. * Line3D
  15055. **************************************************************/
  15056. THREE.LineCurve3 = THREE.Curve.create(
  15057. function ( v1, v2 ) {
  15058. this.v1 = v1;
  15059. this.v2 = v2;
  15060. },
  15061. function ( t ) {
  15062. var r = new THREE.Vector3();
  15063. r.sub( this.v2, this.v1 ); // diff
  15064. r.multiplyScalar( t );
  15065. r.addSelf( this.v1 );
  15066. return r;
  15067. }
  15068. );
  15069. /**************************************************************
  15070. * Quadratic Bezier 3D curve
  15071. **************************************************************/
  15072. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  15073. function ( v0, v1, v2 ) {
  15074. this.v0 = v0;
  15075. this.v1 = v1;
  15076. this.v2 = v2;
  15077. },
  15078. function ( t ) {
  15079. var tx, ty, tz;
  15080. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  15081. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  15082. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  15083. return new THREE.Vector3( tx, ty, tz );
  15084. }
  15085. );
  15086. /**************************************************************
  15087. * Cubic Bezier 3D curve
  15088. **************************************************************/
  15089. THREE.CubicBezierCurve3 = THREE.Curve.create(
  15090. function ( v0, v1, v2, v3 ) {
  15091. this.v0 = v0;
  15092. this.v1 = v1;
  15093. this.v2 = v2;
  15094. this.v3 = v3;
  15095. },
  15096. function ( t ) {
  15097. var tx, ty, tz;
  15098. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15099. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15100. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  15101. return new THREE.Vector3( tx, ty, tz );
  15102. }
  15103. );
  15104. /**************************************************************
  15105. * Spline 3D curve
  15106. **************************************************************/
  15107. THREE.SplineCurve3 = THREE.Curve.create(
  15108. function ( points /* array of Vector3 */) {
  15109. this.points = (points == undefined) ? [] : points;
  15110. },
  15111. function ( t ) {
  15112. var v = new THREE.Vector3();
  15113. var c = [];
  15114. var points = this.points, point, intPoint, weight;
  15115. point = ( points.length - 1 ) * t;
  15116. intPoint = Math.floor( point );
  15117. weight = point - intPoint;
  15118. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15119. c[ 1 ] = intPoint;
  15120. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  15121. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  15122. var pt0 = points[ c[0] ],
  15123. pt1 = points[ c[1] ],
  15124. pt2 = points[ c[2] ],
  15125. pt3 = points[ c[3] ];
  15126. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  15127. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  15128. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  15129. return v;
  15130. }
  15131. );
  15132. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  15133. // var v = new THREE.Vector3();
  15134. // var c = [];
  15135. // var points = this.points, point, intPoint, weight;
  15136. // point = ( points.length - 1 ) * t;
  15137. // intPoint = Math.floor( point );
  15138. // weight = point - intPoint;
  15139. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15140. // c[ 1 ] = intPoint;
  15141. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  15142. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  15143. // var pt0 = points[ c[0] ],
  15144. // pt1 = points[ c[1] ],
  15145. // pt2 = points[ c[2] ],
  15146. // pt3 = points[ c[3] ];
  15147. // // t = weight;
  15148. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  15149. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  15150. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  15151. // return v;
  15152. // }
  15153. /**************************************************************
  15154. * Closed Spline 3D curve
  15155. **************************************************************/
  15156. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  15157. function ( points /* array of Vector3 */) {
  15158. this.points = (points == undefined) ? [] : points;
  15159. },
  15160. function ( t ) {
  15161. var v = new THREE.Vector3();
  15162. var c = [];
  15163. var points = this.points, point, intPoint, weight;
  15164. point = ( points.length - 0 ) * t;
  15165. // This needs to be from 0-length +1
  15166. intPoint = Math.floor( point );
  15167. weight = point - intPoint;
  15168. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  15169. c[ 0 ] = ( intPoint - 1 ) % points.length;
  15170. c[ 1 ] = ( intPoint ) % points.length;
  15171. c[ 2 ] = ( intPoint + 1 ) % points.length;
  15172. c[ 3 ] = ( intPoint + 2 ) % points.length;
  15173. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  15174. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  15175. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  15176. return v;
  15177. }
  15178. );
  15179. /**
  15180. * @author zz85 / http://www.lab4games.net/zz85/blog
  15181. *
  15182. **/
  15183. /**************************************************************
  15184. * Curved Path - a curve path is simply a array of connected
  15185. * curves, but retains the api of a curve
  15186. **************************************************************/
  15187. THREE.CurvePath = function () {
  15188. this.curves = [];
  15189. this.bends = [];
  15190. this.autoClose = false; // Automatically closes the path
  15191. };
  15192. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  15193. THREE.CurvePath.prototype.add = function ( curve ) {
  15194. this.curves.push( curve );
  15195. };
  15196. THREE.CurvePath.prototype.checkConnection = function() {
  15197. // TODO
  15198. // If the ending of curve is not connected to the starting
  15199. // or the next curve, then, this is not a real path
  15200. };
  15201. THREE.CurvePath.prototype.closePath = function() {
  15202. // TODO Test
  15203. // and verify for vector3 (needs to implement equals)
  15204. // Add a line curve if start and end of lines are not connected
  15205. var startPoint = this.curves[0].getPoint(0);
  15206. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  15207. if (!startPoint.equals(endPoint)) {
  15208. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  15209. }
  15210. };
  15211. // To get accurate point with reference to
  15212. // entire path distance at time t,
  15213. // following has to be done:
  15214. // 1. Length of each sub path have to be known
  15215. // 2. Locate and identify type of curve
  15216. // 3. Get t for the curve
  15217. // 4. Return curve.getPointAt(t')
  15218. THREE.CurvePath.prototype.getPoint = function( t ) {
  15219. var d = t * this.getLength();
  15220. var curveLengths = this.getCurveLengths();
  15221. var i = 0, diff, curve;
  15222. // To think about boundaries points.
  15223. while ( i < curveLengths.length ) {
  15224. if ( curveLengths[ i ] >= d ) {
  15225. diff = curveLengths[ i ] - d;
  15226. curve = this.curves[ i ];
  15227. var u = 1 - diff / curve.getLength();
  15228. return curve.getPointAt( u );
  15229. break;
  15230. }
  15231. i ++;
  15232. }
  15233. return null;
  15234. // loop where sum != 0, sum > d , sum+1 <d
  15235. };
  15236. /*
  15237. THREE.CurvePath.prototype.getTangent = function( t ) {
  15238. };*/
  15239. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  15240. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  15241. // getPoint() depends on getLength
  15242. THREE.CurvePath.prototype.getLength = function() {
  15243. var lens = this.getCurveLengths();
  15244. return lens[ lens.length - 1 ];
  15245. };
  15246. // Compute lengths and cache them
  15247. // We cannot overwrite getLengths() because UtoT mapping uses it.
  15248. THREE.CurvePath.prototype.getCurveLengths = function() {
  15249. // We use cache values if curves and cache array are same length
  15250. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  15251. return this.cacheLengths;
  15252. };
  15253. // Get length of subsurve
  15254. // Push sums into cached array
  15255. var lengths = [], sums = 0;
  15256. var i, il = this.curves.length;
  15257. for ( i = 0; i < il; i ++ ) {
  15258. sums += this.curves[ i ].getLength();
  15259. lengths.push( sums );
  15260. }
  15261. this.cacheLengths = lengths;
  15262. return lengths;
  15263. };
  15264. // Returns min and max coordinates, as well as centroid
  15265. THREE.CurvePath.prototype.getBoundingBox = function () {
  15266. var points = this.getPoints();
  15267. var maxX, maxY, maxZ;
  15268. var minX, minY, minZ;
  15269. maxX = maxY = Number.NEGATIVE_INFINITY;
  15270. minX = minY = Number.POSITIVE_INFINITY;
  15271. var p, i, il, sum;
  15272. var v3 = points[0] instanceof THREE.Vector3;
  15273. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  15274. for ( i = 0, il = points.length; i < il; i ++ ) {
  15275. p = points[ i ];
  15276. if ( p.x > maxX ) maxX = p.x;
  15277. else if ( p.x < minX ) minX = p.x;
  15278. if ( p.y > maxY ) maxY = p.y;
  15279. else if ( p.y < minY ) minY = p.y;
  15280. if (v3) {
  15281. if ( p.z > maxZ ) maxZ = p.z;
  15282. else if ( p.z < minZ ) minZ = p.z;
  15283. }
  15284. sum.addSelf( p );
  15285. }
  15286. var ret = {
  15287. minX: minX,
  15288. minY: minY,
  15289. maxX: maxX,
  15290. maxY: maxY,
  15291. centroid: sum.divideScalar( il )
  15292. };
  15293. if (v3) {
  15294. ret.maxZ = maxZ;
  15295. ret.minZ = minZ;
  15296. }
  15297. return ret;
  15298. };
  15299. /**************************************************************
  15300. * Create Geometries Helpers
  15301. **************************************************************/
  15302. /// Generate geometry from path points (for Line or ParticleSystem objects)
  15303. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  15304. var pts = this.getPoints( divisions, true );
  15305. return this.createGeometry( pts );
  15306. };
  15307. // Generate geometry from equidistance sampling along the path
  15308. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  15309. var pts = this.getSpacedPoints( divisions, true );
  15310. return this.createGeometry( pts );
  15311. };
  15312. THREE.CurvePath.prototype.createGeometry = function( points ) {
  15313. var geometry = new THREE.Geometry();
  15314. for ( var i = 0; i < points.length; i ++ ) {
  15315. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  15316. }
  15317. return geometry;
  15318. };
  15319. /**************************************************************
  15320. * Bend / Wrap Helper Methods
  15321. **************************************************************/
  15322. // Wrap path / Bend modifiers?
  15323. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  15324. this.bends.push( bendpath );
  15325. };
  15326. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  15327. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  15328. var i, il;
  15329. if ( !bends ) {
  15330. bends = this.bends;
  15331. }
  15332. for ( i = 0, il = bends.length; i < il; i ++ ) {
  15333. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  15334. }
  15335. return oldPts;
  15336. };
  15337. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  15338. var oldPts = this.getSpacedPoints( segments );
  15339. var i, il;
  15340. if ( !bends ) {
  15341. bends = this.bends;
  15342. }
  15343. for ( i = 0, il = bends.length; i < il; i ++ ) {
  15344. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  15345. }
  15346. return oldPts;
  15347. };
  15348. // This returns getPoints() bend/wrapped around the contour of a path.
  15349. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  15350. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  15351. var bounds = this.getBoundingBox();
  15352. var i, il, p, oldX, oldY, xNorm;
  15353. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  15354. p = oldPts[ i ];
  15355. oldX = p.x;
  15356. oldY = p.y;
  15357. xNorm = oldX / bounds.maxX;
  15358. // If using actual distance, for length > path, requires line extrusions
  15359. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  15360. xNorm = path.getUtoTmapping( xNorm, oldX );
  15361. // check for out of bounds?
  15362. var pathPt = path.getPoint( xNorm );
  15363. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  15364. p.x = pathPt.x + normal.x;
  15365. p.y = pathPt.y + normal.y;
  15366. }
  15367. return oldPts;
  15368. };
  15369. /**
  15370. * @author alteredq / http://alteredqualia.com/
  15371. */
  15372. THREE.Gyroscope = function () {
  15373. THREE.Object3D.call( this );
  15374. };
  15375. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  15376. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  15377. this.matrixAutoUpdate && this.updateMatrix();
  15378. // update matrixWorld
  15379. if ( this.matrixWorldNeedsUpdate || force ) {
  15380. if ( this.parent ) {
  15381. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  15382. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  15383. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  15384. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  15385. } else {
  15386. this.matrixWorld.copy( this.matrix );
  15387. }
  15388. this.matrixWorldNeedsUpdate = false;
  15389. force = true;
  15390. }
  15391. // update children
  15392. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  15393. this.children[ i ].updateMatrixWorld( force );
  15394. }
  15395. };
  15396. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  15397. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  15398. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  15399. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  15400. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  15401. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  15402. /**
  15403. * @author zz85 / http://www.lab4games.net/zz85/blog
  15404. * Creates free form 2d path using series of points, lines or curves.
  15405. *
  15406. **/
  15407. THREE.Path = function ( points ) {
  15408. THREE.CurvePath.call(this);
  15409. this.actions = [];
  15410. if ( points ) {
  15411. this.fromPoints( points );
  15412. }
  15413. };
  15414. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  15415. THREE.PathActions = {
  15416. MOVE_TO: 'moveTo',
  15417. LINE_TO: 'lineTo',
  15418. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  15419. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  15420. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  15421. ARC: 'arc', // Circle
  15422. ELLIPSE: 'ellipse'
  15423. };
  15424. // TODO Clean up PATH API
  15425. // Create path using straight lines to connect all points
  15426. // - vectors: array of Vector2
  15427. THREE.Path.prototype.fromPoints = function ( vectors ) {
  15428. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  15429. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  15430. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  15431. };
  15432. };
  15433. // startPath() endPath()?
  15434. THREE.Path.prototype.moveTo = function ( x, y ) {
  15435. var args = Array.prototype.slice.call( arguments );
  15436. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  15437. };
  15438. THREE.Path.prototype.lineTo = function ( x, y ) {
  15439. var args = Array.prototype.slice.call( arguments );
  15440. var lastargs = this.actions[ this.actions.length - 1 ].args;
  15441. var x0 = lastargs[ lastargs.length - 2 ];
  15442. var y0 = lastargs[ lastargs.length - 1 ];
  15443. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  15444. this.curves.push( curve );
  15445. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  15446. };
  15447. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  15448. var args = Array.prototype.slice.call( arguments );
  15449. var lastargs = this.actions[ this.actions.length - 1 ].args;
  15450. var x0 = lastargs[ lastargs.length - 2 ];
  15451. var y0 = lastargs[ lastargs.length - 1 ];
  15452. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  15453. new THREE.Vector2( aCPx, aCPy ),
  15454. new THREE.Vector2( aX, aY ) );
  15455. this.curves.push( curve );
  15456. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  15457. };
  15458. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  15459. aCP2x, aCP2y,
  15460. aX, aY ) {
  15461. var args = Array.prototype.slice.call( arguments );
  15462. var lastargs = this.actions[ this.actions.length - 1 ].args;
  15463. var x0 = lastargs[ lastargs.length - 2 ];
  15464. var y0 = lastargs[ lastargs.length - 1 ];
  15465. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  15466. new THREE.Vector2( aCP1x, aCP1y ),
  15467. new THREE.Vector2( aCP2x, aCP2y ),
  15468. new THREE.Vector2( aX, aY ) );
  15469. this.curves.push( curve );
  15470. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  15471. };
  15472. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  15473. var args = Array.prototype.slice.call( arguments );
  15474. var lastargs = this.actions[ this.actions.length - 1 ].args;
  15475. var x0 = lastargs[ lastargs.length - 2 ];
  15476. var y0 = lastargs[ lastargs.length - 1 ];
  15477. //---
  15478. var npts = [ new THREE.Vector2( x0, y0 ) ];
  15479. Array.prototype.push.apply( npts, pts );
  15480. var curve = new THREE.SplineCurve( npts );
  15481. this.curves.push( curve );
  15482. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  15483. };
  15484. // FUTURE: Change the API or follow canvas API?
  15485. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  15486. aStartAngle, aEndAngle, aClockwise ) {
  15487. var lastargs = this.actions[ this.actions.length - 1].args;
  15488. var x0 = lastargs[ lastargs.length - 2 ];
  15489. var y0 = lastargs[ lastargs.length - 1 ];
  15490. this.absarc(aX + x0, aY + y0, aRadius,
  15491. aStartAngle, aEndAngle, aClockwise );
  15492. };
  15493. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  15494. aStartAngle, aEndAngle, aClockwise ) {
  15495. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  15496. };
  15497. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  15498. aStartAngle, aEndAngle, aClockwise ) {
  15499. var lastargs = this.actions[ this.actions.length - 1].args;
  15500. var x0 = lastargs[ lastargs.length - 2 ];
  15501. var y0 = lastargs[ lastargs.length - 1 ];
  15502. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  15503. aStartAngle, aEndAngle, aClockwise );
  15504. };
  15505. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  15506. aStartAngle, aEndAngle, aClockwise ) {
  15507. var args = Array.prototype.slice.call( arguments );
  15508. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  15509. aStartAngle, aEndAngle, aClockwise );
  15510. this.curves.push( curve );
  15511. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  15512. args.push(lastPoint.x);
  15513. args.push(lastPoint.y);
  15514. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  15515. };
  15516. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  15517. if ( ! divisions ) divisions = 40;
  15518. var points = [];
  15519. for ( var i = 0; i < divisions; i ++ ) {
  15520. points.push( this.getPoint( i / divisions ) );
  15521. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  15522. }
  15523. // if ( closedPath ) {
  15524. //
  15525. // points.push( points[ 0 ] );
  15526. //
  15527. // }
  15528. return points;
  15529. };
  15530. /* Return an array of vectors based on contour of the path */
  15531. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  15532. if (this.useSpacedPoints) {
  15533. console.log('tata');
  15534. return this.getSpacedPoints( divisions, closedPath );
  15535. }
  15536. divisions = divisions || 12;
  15537. var points = [];
  15538. var i, il, item, action, args;
  15539. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  15540. laste, j,
  15541. t, tx, ty;
  15542. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  15543. item = this.actions[ i ];
  15544. action = item.action;
  15545. args = item.args;
  15546. switch( action ) {
  15547. case THREE.PathActions.MOVE_TO:
  15548. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  15549. break;
  15550. case THREE.PathActions.LINE_TO:
  15551. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  15552. break;
  15553. case THREE.PathActions.QUADRATIC_CURVE_TO:
  15554. cpx = args[ 2 ];
  15555. cpy = args[ 3 ];
  15556. cpx1 = args[ 0 ];
  15557. cpy1 = args[ 1 ];
  15558. if ( points.length > 0 ) {
  15559. laste = points[ points.length - 1 ];
  15560. cpx0 = laste.x;
  15561. cpy0 = laste.y;
  15562. } else {
  15563. laste = this.actions[ i - 1 ].args;
  15564. cpx0 = laste[ laste.length - 2 ];
  15565. cpy0 = laste[ laste.length - 1 ];
  15566. }
  15567. for ( j = 1; j <= divisions; j ++ ) {
  15568. t = j / divisions;
  15569. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15570. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15571. points.push( new THREE.Vector2( tx, ty ) );
  15572. }
  15573. break;
  15574. case THREE.PathActions.BEZIER_CURVE_TO:
  15575. cpx = args[ 4 ];
  15576. cpy = args[ 5 ];
  15577. cpx1 = args[ 0 ];
  15578. cpy1 = args[ 1 ];
  15579. cpx2 = args[ 2 ];
  15580. cpy2 = args[ 3 ];
  15581. if ( points.length > 0 ) {
  15582. laste = points[ points.length - 1 ];
  15583. cpx0 = laste.x;
  15584. cpy0 = laste.y;
  15585. } else {
  15586. laste = this.actions[ i - 1 ].args;
  15587. cpx0 = laste[ laste.length - 2 ];
  15588. cpy0 = laste[ laste.length - 1 ];
  15589. }
  15590. for ( j = 1; j <= divisions; j ++ ) {
  15591. t = j / divisions;
  15592. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15593. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15594. points.push( new THREE.Vector2( tx, ty ) );
  15595. }
  15596. break;
  15597. case THREE.PathActions.CSPLINE_THRU:
  15598. laste = this.actions[ i - 1 ].args;
  15599. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  15600. var spts = [ last ];
  15601. var n = divisions * args[ 0 ].length;
  15602. spts = spts.concat( args[ 0 ] );
  15603. var spline = new THREE.SplineCurve( spts );
  15604. for ( j = 1; j <= n; j ++ ) {
  15605. points.push( spline.getPointAt( j / n ) ) ;
  15606. }
  15607. break;
  15608. case THREE.PathActions.ARC:
  15609. var aX = args[ 0 ], aY = args[ 1 ],
  15610. aRadius = args[ 2 ],
  15611. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  15612. aClockwise = !!args[ 5 ];
  15613. var deltaAngle = aEndAngle - aStartAngle;
  15614. var angle;
  15615. var tdivisions = divisions * 2;
  15616. for ( j = 1; j <= tdivisions; j ++ ) {
  15617. t = j / tdivisions;
  15618. if ( ! aClockwise ) {
  15619. t = 1 - t;
  15620. }
  15621. angle = aStartAngle + t * deltaAngle;
  15622. tx = aX + aRadius * Math.cos( angle );
  15623. ty = aY + aRadius * Math.sin( angle );
  15624. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  15625. points.push( new THREE.Vector2( tx, ty ) );
  15626. }
  15627. //console.log(points);
  15628. break;
  15629. case THREE.PathActions.ELLIPSE:
  15630. var aX = args[ 0 ], aY = args[ 1 ],
  15631. xRadius = args[ 2 ],
  15632. yRadius = args[ 3 ],
  15633. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  15634. aClockwise = !!args[ 6 ];
  15635. var deltaAngle = aEndAngle - aStartAngle;
  15636. var angle;
  15637. var tdivisions = divisions * 2;
  15638. for ( j = 1; j <= tdivisions; j ++ ) {
  15639. t = j / tdivisions;
  15640. if ( ! aClockwise ) {
  15641. t = 1 - t;
  15642. }
  15643. angle = aStartAngle + t * deltaAngle;
  15644. tx = aX + xRadius * Math.cos( angle );
  15645. ty = aY + yRadius * Math.sin( angle );
  15646. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  15647. points.push( new THREE.Vector2( tx, ty ) );
  15648. }
  15649. //console.log(points);
  15650. break;
  15651. } // end switch
  15652. }
  15653. // Normalize to remove the closing point by default.
  15654. var lastPoint = points[ points.length - 1];
  15655. var EPSILON = 0.0000000001;
  15656. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  15657. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  15658. points.splice( points.length - 1, 1);
  15659. if ( closedPath ) {
  15660. points.push( points[ 0 ] );
  15661. }
  15662. return points;
  15663. };
  15664. // Breaks path into shapes
  15665. THREE.Path.prototype.toShapes = function() {
  15666. var i, il, item, action, args;
  15667. var subPaths = [], lastPath = new THREE.Path();
  15668. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  15669. item = this.actions[ i ];
  15670. args = item.args;
  15671. action = item.action;
  15672. if ( action == THREE.PathActions.MOVE_TO ) {
  15673. if ( lastPath.actions.length != 0 ) {
  15674. subPaths.push( lastPath );
  15675. lastPath = new THREE.Path();
  15676. }
  15677. }
  15678. lastPath[ action ].apply( lastPath, args );
  15679. }
  15680. if ( lastPath.actions.length != 0 ) {
  15681. subPaths.push( lastPath );
  15682. }
  15683. // console.log(subPaths);
  15684. if ( subPaths.length == 0 ) return [];
  15685. var tmpPath, tmpShape, shapes = [];
  15686. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  15687. // console.log("Holes first", holesFirst);
  15688. if ( subPaths.length == 1) {
  15689. tmpPath = subPaths[0];
  15690. tmpShape = new THREE.Shape();
  15691. tmpShape.actions = tmpPath.actions;
  15692. tmpShape.curves = tmpPath.curves;
  15693. shapes.push( tmpShape );
  15694. return shapes;
  15695. };
  15696. if ( holesFirst ) {
  15697. tmpShape = new THREE.Shape();
  15698. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  15699. tmpPath = subPaths[ i ];
  15700. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  15701. tmpShape.actions = tmpPath.actions;
  15702. tmpShape.curves = tmpPath.curves;
  15703. shapes.push( tmpShape );
  15704. tmpShape = new THREE.Shape();
  15705. //console.log('cw', i);
  15706. } else {
  15707. tmpShape.holes.push( tmpPath );
  15708. //console.log('ccw', i);
  15709. }
  15710. }
  15711. } else {
  15712. // Shapes first
  15713. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  15714. tmpPath = subPaths[ i ];
  15715. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  15716. if ( tmpShape ) shapes.push( tmpShape );
  15717. tmpShape = new THREE.Shape();
  15718. tmpShape.actions = tmpPath.actions;
  15719. tmpShape.curves = tmpPath.curves;
  15720. } else {
  15721. tmpShape.holes.push( tmpPath );
  15722. }
  15723. }
  15724. shapes.push( tmpShape );
  15725. }
  15726. //console.log("shape", shapes);
  15727. return shapes;
  15728. };
  15729. /**
  15730. * @author zz85 / http://www.lab4games.net/zz85/blog
  15731. * Defines a 2d shape plane using paths.
  15732. **/
  15733. // STEP 1 Create a path.
  15734. // STEP 2 Turn path into shape.
  15735. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  15736. // STEP 3a - Extract points from each shape, turn to vertices
  15737. // STEP 3b - Triangulate each shape, add faces.
  15738. THREE.Shape = function ( ) {
  15739. THREE.Path.apply( this, arguments );
  15740. this.holes = [];
  15741. };
  15742. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  15743. // Convenience method to return ExtrudeGeometry
  15744. THREE.Shape.prototype.extrude = function ( options ) {
  15745. var extruded = new THREE.ExtrudeGeometry( this, options );
  15746. return extruded;
  15747. };
  15748. // Get points of holes
  15749. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  15750. var i, il = this.holes.length, holesPts = [];
  15751. for ( i = 0; i < il; i ++ ) {
  15752. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  15753. }
  15754. return holesPts;
  15755. };
  15756. // Get points of holes (spaced by regular distance)
  15757. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  15758. var i, il = this.holes.length, holesPts = [];
  15759. for ( i = 0; i < il; i ++ ) {
  15760. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  15761. }
  15762. return holesPts;
  15763. };
  15764. // Get points of shape and holes (keypoints based on segments parameter)
  15765. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  15766. return {
  15767. shape: this.getTransformedPoints( divisions ),
  15768. holes: this.getPointsHoles( divisions )
  15769. };
  15770. };
  15771. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  15772. if (this.useSpacedPoints) {
  15773. return this.extractAllSpacedPoints(divisions);
  15774. }
  15775. return this.extractAllPoints(divisions);
  15776. };
  15777. //
  15778. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  15779. //
  15780. // return {
  15781. //
  15782. // shape: this.transform( bend, divisions ),
  15783. // holes: this.getPointsHoles( divisions, bend )
  15784. //
  15785. // };
  15786. //
  15787. // };
  15788. // Get points of shape and holes (spaced by regular distance)
  15789. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  15790. return {
  15791. shape: this.getTransformedSpacedPoints( divisions ),
  15792. holes: this.getSpacedPointsHoles( divisions )
  15793. };
  15794. };
  15795. /**************************************************************
  15796. * Utils
  15797. **************************************************************/
  15798. THREE.Shape.Utils = {
  15799. /*
  15800. contour - array of vector2 for contour
  15801. holes - array of array of vector2
  15802. */
  15803. removeHoles: function ( contour, holes ) {
  15804. var shape = contour.concat(); // work on this shape
  15805. var allpoints = shape.concat();
  15806. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  15807. var prevShapeVert, nextShapeVert,
  15808. prevHoleVert, nextHoleVert,
  15809. holeIndex, shapeIndex,
  15810. shapeId, shapeGroup,
  15811. h, h2,
  15812. hole, shortest, d,
  15813. p, pts1, pts2,
  15814. tmpShape1, tmpShape2,
  15815. tmpHole1, tmpHole2,
  15816. verts = [];
  15817. for ( h = 0; h < holes.length; h ++ ) {
  15818. hole = holes[ h ];
  15819. /*
  15820. shapeholes[ h ].concat(); // preserves original
  15821. holes.push( hole );
  15822. */
  15823. Array.prototype.push.apply( allpoints, hole );
  15824. shortest = Number.POSITIVE_INFINITY;
  15825. // Find the shortest pair of pts between shape and hole
  15826. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  15827. // Using distanceToSquared() intead of distanceTo() should speed a little
  15828. // since running square roots operations are reduced.
  15829. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  15830. pts1 = hole[ h2 ];
  15831. var dist = [];
  15832. for ( p = 0; p < shape.length; p++ ) {
  15833. pts2 = shape[ p ];
  15834. d = pts1.distanceToSquared( pts2 );
  15835. dist.push( d );
  15836. if ( d < shortest ) {
  15837. shortest = d;
  15838. holeIndex = h2;
  15839. shapeIndex = p;
  15840. }
  15841. }
  15842. }
  15843. //console.log("shortest", shortest, dist);
  15844. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  15845. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  15846. var areaapts = [
  15847. hole[ holeIndex ],
  15848. shape[ shapeIndex ],
  15849. shape[ prevShapeVert ]
  15850. ];
  15851. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  15852. var areabpts = [
  15853. hole[ holeIndex ],
  15854. hole[ prevHoleVert ],
  15855. shape[ shapeIndex ]
  15856. ];
  15857. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  15858. var shapeOffset = 1;
  15859. var holeOffset = -1;
  15860. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  15861. shapeIndex += shapeOffset;
  15862. holeIndex += holeOffset;
  15863. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  15864. shapeIndex %= shape.length;
  15865. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  15866. holeIndex %= hole.length;
  15867. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  15868. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  15869. areaapts = [
  15870. hole[ holeIndex ],
  15871. shape[ shapeIndex ],
  15872. shape[ prevShapeVert ]
  15873. ];
  15874. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  15875. areabpts = [
  15876. hole[ holeIndex ],
  15877. hole[ prevHoleVert ],
  15878. shape[ shapeIndex ]
  15879. ];
  15880. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  15881. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  15882. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  15883. // In case areas are not correct.
  15884. //console.log("USE THIS");
  15885. shapeIndex = oldShapeIndex;
  15886. holeIndex = oldHoleIndex ;
  15887. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  15888. shapeIndex %= shape.length;
  15889. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  15890. holeIndex %= hole.length;
  15891. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  15892. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  15893. } else {
  15894. //console.log("USE THAT ")
  15895. }
  15896. tmpShape1 = shape.slice( 0, shapeIndex );
  15897. tmpShape2 = shape.slice( shapeIndex );
  15898. tmpHole1 = hole.slice( holeIndex );
  15899. tmpHole2 = hole.slice( 0, holeIndex );
  15900. // Should check orders here again?
  15901. var trianglea = [
  15902. hole[ holeIndex ],
  15903. shape[ shapeIndex ],
  15904. shape[ prevShapeVert ]
  15905. ];
  15906. var triangleb = [
  15907. hole[ holeIndex ] ,
  15908. hole[ prevHoleVert ],
  15909. shape[ shapeIndex ]
  15910. ];
  15911. verts.push( trianglea );
  15912. verts.push( triangleb );
  15913. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  15914. }
  15915. return {
  15916. shape:shape, /* shape with no holes */
  15917. isolatedPts: verts, /* isolated faces */
  15918. allpoints: allpoints
  15919. }
  15920. },
  15921. triangulateShape: function ( contour, holes ) {
  15922. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  15923. var shape = shapeWithoutHoles.shape,
  15924. allpoints = shapeWithoutHoles.allpoints,
  15925. isolatedPts = shapeWithoutHoles.isolatedPts;
  15926. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  15927. // 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.
  15928. //console.log( "triangles",triangles, triangles.length );
  15929. //console.log( "allpoints",allpoints, allpoints.length );
  15930. var i, il, f, face,
  15931. key, index,
  15932. allPointsMap = {},
  15933. isolatedPointsMap = {};
  15934. // prepare all points map
  15935. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  15936. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  15937. if ( allPointsMap[ key ] !== undefined ) {
  15938. console.log( "Duplicate point", key );
  15939. }
  15940. allPointsMap[ key ] = i;
  15941. }
  15942. // check all face vertices against all points map
  15943. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  15944. face = triangles[ i ];
  15945. for ( f = 0; f < 3; f ++ ) {
  15946. key = face[ f ].x + ":" + face[ f ].y;
  15947. index = allPointsMap[ key ];
  15948. if ( index !== undefined ) {
  15949. face[ f ] = index;
  15950. }
  15951. }
  15952. }
  15953. // check isolated points vertices against all points map
  15954. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  15955. face = isolatedPts[ i ];
  15956. for ( f = 0; f < 3; f ++ ) {
  15957. key = face[ f ].x + ":" + face[ f ].y;
  15958. index = allPointsMap[ key ];
  15959. if ( index !== undefined ) {
  15960. face[ f ] = index;
  15961. }
  15962. }
  15963. }
  15964. return triangles.concat( isolatedPts );
  15965. }, // end triangulate shapes
  15966. /*
  15967. triangulate2 : function( pts, holes ) {
  15968. // For use with Poly2Tri.js
  15969. var allpts = pts.concat();
  15970. var shape = [];
  15971. for (var p in pts) {
  15972. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  15973. }
  15974. var swctx = new js.poly2tri.SweepContext(shape);
  15975. for (var h in holes) {
  15976. var aHole = holes[h];
  15977. var newHole = []
  15978. for (i in aHole) {
  15979. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  15980. allpts.push(aHole[i]);
  15981. }
  15982. swctx.AddHole(newHole);
  15983. }
  15984. var find;
  15985. var findIndexForPt = function (pt) {
  15986. find = new THREE.Vector2(pt.x, pt.y);
  15987. var p;
  15988. for (p=0, pl = allpts.length; p<pl; p++) {
  15989. if (allpts[p].equals(find)) return p;
  15990. }
  15991. return -1;
  15992. };
  15993. // triangulate
  15994. js.poly2tri.sweep.Triangulate(swctx);
  15995. var triangles = swctx.GetTriangles();
  15996. var tr ;
  15997. var facesPts = [];
  15998. for (var t in triangles) {
  15999. tr = triangles[t];
  16000. facesPts.push([
  16001. findIndexForPt(tr.GetPoint(0)),
  16002. findIndexForPt(tr.GetPoint(1)),
  16003. findIndexForPt(tr.GetPoint(2))
  16004. ]);
  16005. }
  16006. // console.log(facesPts);
  16007. // console.log("triangles", triangles.length, triangles);
  16008. // Returns array of faces with 3 element each
  16009. return facesPts;
  16010. },
  16011. */
  16012. isClockWise: function ( pts ) {
  16013. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  16014. },
  16015. // Bezier Curves formulas obtained from
  16016. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  16017. // Quad Bezier Functions
  16018. b2p0: function ( t, p ) {
  16019. var k = 1 - t;
  16020. return k * k * p;
  16021. },
  16022. b2p1: function ( t, p ) {
  16023. return 2 * ( 1 - t ) * t * p;
  16024. },
  16025. b2p2: function ( t, p ) {
  16026. return t * t * p;
  16027. },
  16028. b2: function ( t, p0, p1, p2 ) {
  16029. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  16030. },
  16031. // Cubic Bezier Functions
  16032. b3p0: function ( t, p ) {
  16033. var k = 1 - t;
  16034. return k * k * k * p;
  16035. },
  16036. b3p1: function ( t, p ) {
  16037. var k = 1 - t;
  16038. return 3 * k * k * t * p;
  16039. },
  16040. b3p2: function ( t, p ) {
  16041. var k = 1 - t;
  16042. return 3 * k * t * t * p;
  16043. },
  16044. b3p3: function ( t, p ) {
  16045. return t * t * t * p;
  16046. },
  16047. b3: function ( t, p0, p1, p2, p3 ) {
  16048. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  16049. }
  16050. };
  16051. /**
  16052. * @author mikael emtinger / http://gomo.se/
  16053. */
  16054. THREE.AnimationHandler = (function() {
  16055. var playing = [];
  16056. var library = {};
  16057. var that = {};
  16058. //--- update ---
  16059. that.update = function( deltaTimeMS ) {
  16060. for( var i = 0; i < playing.length; i ++ )
  16061. playing[ i ].update( deltaTimeMS );
  16062. };
  16063. //--- add ---
  16064. that.addToUpdate = function( animation ) {
  16065. if ( playing.indexOf( animation ) === -1 )
  16066. playing.push( animation );
  16067. };
  16068. //--- remove ---
  16069. that.removeFromUpdate = function( animation ) {
  16070. var index = playing.indexOf( animation );
  16071. if( index !== -1 )
  16072. playing.splice( index, 1 );
  16073. };
  16074. //--- add ---
  16075. that.add = function( data ) {
  16076. if ( library[ data.name ] !== undefined )
  16077. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  16078. library[ data.name ] = data;
  16079. initData( data );
  16080. };
  16081. //--- get ---
  16082. that.get = function( name ) {
  16083. if ( typeof name === "string" ) {
  16084. if ( library[ name ] ) {
  16085. return library[ name ];
  16086. } else {
  16087. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  16088. return null;
  16089. }
  16090. } else {
  16091. // todo: add simple tween library
  16092. }
  16093. };
  16094. //--- parse ---
  16095. that.parse = function( root ) {
  16096. // setup hierarchy
  16097. var hierarchy = [];
  16098. if ( root instanceof THREE.SkinnedMesh ) {
  16099. for( var b = 0; b < root.bones.length; b++ ) {
  16100. hierarchy.push( root.bones[ b ] );
  16101. }
  16102. } else {
  16103. parseRecurseHierarchy( root, hierarchy );
  16104. }
  16105. return hierarchy;
  16106. };
  16107. var parseRecurseHierarchy = function( root, hierarchy ) {
  16108. hierarchy.push( root );
  16109. for( var c = 0; c < root.children.length; c++ )
  16110. parseRecurseHierarchy( root.children[ c ], hierarchy );
  16111. }
  16112. //--- init data ---
  16113. var initData = function( data ) {
  16114. if( data.initialized === true )
  16115. return;
  16116. // loop through all keys
  16117. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  16118. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16119. // remove minus times
  16120. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  16121. data.hierarchy[ h ].keys[ k ].time = 0;
  16122. // create quaternions
  16123. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  16124. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  16125. var quat = data.hierarchy[ h ].keys[ k ].rot;
  16126. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  16127. }
  16128. }
  16129. // prepare morph target keys
  16130. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  16131. // get all used
  16132. var usedMorphTargets = {};
  16133. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16134. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  16135. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  16136. usedMorphTargets[ morphTargetName ] = -1;
  16137. }
  16138. }
  16139. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  16140. // set all used on all frames
  16141. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16142. var influences = {};
  16143. for ( var morphTargetName in usedMorphTargets ) {
  16144. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  16145. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  16146. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  16147. break;
  16148. }
  16149. }
  16150. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  16151. influences[ morphTargetName ] = 0;
  16152. }
  16153. }
  16154. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  16155. }
  16156. }
  16157. // remove all keys that are on the same time
  16158. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16159. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  16160. data.hierarchy[ h ].keys.splice( k, 1 );
  16161. k --;
  16162. }
  16163. }
  16164. // set index
  16165. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16166. data.hierarchy[ h ].keys[ k ].index = k;
  16167. }
  16168. }
  16169. // JIT
  16170. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  16171. data.JIT = {};
  16172. data.JIT.hierarchy = [];
  16173. for( var h = 0; h < data.hierarchy.length; h ++ )
  16174. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  16175. // done
  16176. data.initialized = true;
  16177. };
  16178. // interpolation types
  16179. that.LINEAR = 0;
  16180. that.CATMULLROM = 1;
  16181. that.CATMULLROM_FORWARD = 2;
  16182. return that;
  16183. }());
  16184. /**
  16185. * @author mikael emtinger / http://gomo.se/
  16186. * @author mrdoob / http://mrdoob.com/
  16187. * @author alteredq / http://alteredqualia.com/
  16188. */
  16189. THREE.Animation = function ( root, name, interpolationType ) {
  16190. this.root = root;
  16191. this.data = THREE.AnimationHandler.get( name );
  16192. this.hierarchy = THREE.AnimationHandler.parse( root );
  16193. this.currentTime = 0;
  16194. this.timeScale = 1;
  16195. this.isPlaying = false;
  16196. this.isPaused = true;
  16197. this.loop = true;
  16198. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  16199. this.points = [];
  16200. this.target = new THREE.Vector3();
  16201. };
  16202. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  16203. if ( this.isPlaying === false ) {
  16204. this.isPlaying = true;
  16205. this.loop = loop !== undefined ? loop : true;
  16206. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  16207. // reset key cache
  16208. var h, hl = this.hierarchy.length,
  16209. object;
  16210. for ( h = 0; h < hl; h ++ ) {
  16211. object = this.hierarchy[ h ];
  16212. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16213. object.useQuaternion = true;
  16214. }
  16215. object.matrixAutoUpdate = true;
  16216. if ( object.animationCache === undefined ) {
  16217. object.animationCache = {};
  16218. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  16219. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  16220. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  16221. }
  16222. var prevKey = object.animationCache.prevKey;
  16223. var nextKey = object.animationCache.nextKey;
  16224. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  16225. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  16226. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  16227. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  16228. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  16229. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  16230. }
  16231. this.update( 0 );
  16232. }
  16233. this.isPaused = false;
  16234. THREE.AnimationHandler.addToUpdate( this );
  16235. };
  16236. THREE.Animation.prototype.pause = function() {
  16237. if ( this.isPaused === true ) {
  16238. THREE.AnimationHandler.addToUpdate( this );
  16239. } else {
  16240. THREE.AnimationHandler.removeFromUpdate( this );
  16241. }
  16242. this.isPaused = !this.isPaused;
  16243. };
  16244. THREE.Animation.prototype.stop = function() {
  16245. this.isPlaying = false;
  16246. this.isPaused = false;
  16247. THREE.AnimationHandler.removeFromUpdate( this );
  16248. };
  16249. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  16250. // early out
  16251. if ( this.isPlaying === false ) return;
  16252. // vars
  16253. var types = [ "pos", "rot", "scl" ];
  16254. var type;
  16255. var scale;
  16256. var vector;
  16257. var prevXYZ, nextXYZ;
  16258. var prevKey, nextKey;
  16259. var object;
  16260. var animationCache;
  16261. var frame;
  16262. var JIThierarchy = this.data.JIT.hierarchy;
  16263. var currentTime, unloopedCurrentTime;
  16264. var currentPoint, forwardPoint, angle;
  16265. this.currentTime += deltaTimeMS * this.timeScale;
  16266. unloopedCurrentTime = this.currentTime;
  16267. currentTime = this.currentTime = this.currentTime % this.data.length;
  16268. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  16269. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  16270. object = this.hierarchy[ h ];
  16271. animationCache = object.animationCache;
  16272. // loop through pos/rot/scl
  16273. for ( var t = 0; t < 3; t ++ ) {
  16274. // get keys
  16275. type = types[ t ];
  16276. prevKey = animationCache.prevKey[ type ];
  16277. nextKey = animationCache.nextKey[ type ];
  16278. // switch keys?
  16279. if ( nextKey.time <= unloopedCurrentTime ) {
  16280. // did we loop?
  16281. if ( currentTime < unloopedCurrentTime ) {
  16282. if ( this.loop ) {
  16283. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  16284. nextKey = this.getNextKeyWith( type, h, 1 );
  16285. while( nextKey.time < currentTime ) {
  16286. prevKey = nextKey;
  16287. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  16288. }
  16289. } else {
  16290. this.stop();
  16291. return;
  16292. }
  16293. } else {
  16294. do {
  16295. prevKey = nextKey;
  16296. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  16297. } while( nextKey.time < currentTime )
  16298. }
  16299. animationCache.prevKey[ type ] = prevKey;
  16300. animationCache.nextKey[ type ] = nextKey;
  16301. }
  16302. object.matrixAutoUpdate = true;
  16303. object.matrixWorldNeedsUpdate = true;
  16304. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  16305. prevXYZ = prevKey[ type ];
  16306. nextXYZ = nextKey[ type ];
  16307. // check scale error
  16308. if ( scale < 0 || scale > 1 ) {
  16309. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  16310. scale = scale < 0 ? 0 : 1;
  16311. }
  16312. // interpolate
  16313. if ( type === "pos" ) {
  16314. vector = object.position;
  16315. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  16316. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  16317. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  16318. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  16319. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  16320. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16321. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  16322. this.points[ 1 ] = prevXYZ;
  16323. this.points[ 2 ] = nextXYZ;
  16324. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  16325. scale = scale * 0.33 + 0.33;
  16326. currentPoint = this.interpolateCatmullRom( this.points, scale );
  16327. vector.x = currentPoint[ 0 ];
  16328. vector.y = currentPoint[ 1 ];
  16329. vector.z = currentPoint[ 2 ];
  16330. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16331. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  16332. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  16333. this.target.subSelf( vector );
  16334. this.target.y = 0;
  16335. this.target.normalize();
  16336. angle = Math.atan2( this.target.x, this.target.z );
  16337. object.rotation.set( 0, angle, 0 );
  16338. }
  16339. }
  16340. } else if ( type === "rot" ) {
  16341. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  16342. } else if ( type === "scl" ) {
  16343. vector = object.scale;
  16344. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  16345. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  16346. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  16347. }
  16348. }
  16349. }
  16350. };
  16351. // Catmull-Rom spline
  16352. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  16353. var c = [], v3 = [],
  16354. point, intPoint, weight, w2, w3,
  16355. pa, pb, pc, pd;
  16356. point = ( points.length - 1 ) * scale;
  16357. intPoint = Math.floor( point );
  16358. weight = point - intPoint;
  16359. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  16360. c[ 1 ] = intPoint;
  16361. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  16362. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  16363. pa = points[ c[ 0 ] ];
  16364. pb = points[ c[ 1 ] ];
  16365. pc = points[ c[ 2 ] ];
  16366. pd = points[ c[ 3 ] ];
  16367. w2 = weight * weight;
  16368. w3 = weight * w2;
  16369. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  16370. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  16371. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  16372. return v3;
  16373. };
  16374. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  16375. var v0 = ( p2 - p0 ) * 0.5,
  16376. v1 = ( p3 - p1 ) * 0.5;
  16377. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16378. };
  16379. // Get next key with
  16380. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  16381. var keys = this.data.hierarchy[ h ].keys;
  16382. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  16383. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16384. key = key < keys.length - 1 ? key : keys.length - 1;
  16385. } else {
  16386. key = key % keys.length;
  16387. }
  16388. for ( ; key < keys.length; key++ ) {
  16389. if ( keys[ key ][ type ] !== undefined ) {
  16390. return keys[ key ];
  16391. }
  16392. }
  16393. return this.data.hierarchy[ h ].keys[ 0 ];
  16394. };
  16395. // Get previous key with
  16396. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  16397. var keys = this.data.hierarchy[ h ].keys;
  16398. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  16399. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16400. key = key > 0 ? key : 0;
  16401. } else {
  16402. key = key >= 0 ? key : key + keys.length;
  16403. }
  16404. for ( ; key >= 0; key -- ) {
  16405. if ( keys[ key ][ type ] !== undefined ) {
  16406. return keys[ key ];
  16407. }
  16408. }
  16409. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  16410. };
  16411. /**
  16412. * @author mikael emtinger / http://gomo.se/
  16413. * @author mrdoob / http://mrdoob.com/
  16414. * @author alteredq / http://alteredqualia.com/
  16415. * @author khang duong
  16416. * @author erik kitson
  16417. */
  16418. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  16419. this.root = root;
  16420. this.data = THREE.AnimationHandler.get( data );
  16421. this.hierarchy = THREE.AnimationHandler.parse( root );
  16422. this.currentTime = 0;
  16423. this.timeScale = 0.001;
  16424. this.isPlaying = false;
  16425. this.isPaused = true;
  16426. this.loop = true;
  16427. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  16428. // initialize to first keyframes
  16429. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  16430. var keys = this.data.hierarchy[h].keys,
  16431. sids = this.data.hierarchy[h].sids,
  16432. obj = this.hierarchy[h];
  16433. if ( keys.length && sids ) {
  16434. for ( var s = 0; s < sids.length; s++ ) {
  16435. var sid = sids[ s ],
  16436. next = this.getNextKeyWith( sid, h, 0 );
  16437. if ( next ) {
  16438. next.apply( sid );
  16439. }
  16440. }
  16441. obj.matrixAutoUpdate = false;
  16442. this.data.hierarchy[h].node.updateMatrix();
  16443. obj.matrixWorldNeedsUpdate = true;
  16444. }
  16445. }
  16446. };
  16447. // Play
  16448. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  16449. if( !this.isPlaying ) {
  16450. this.isPlaying = true;
  16451. this.loop = loop !== undefined ? loop : true;
  16452. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  16453. this.startTimeMs = startTimeMS;
  16454. this.startTime = 10000000;
  16455. this.endTime = -this.startTime;
  16456. // reset key cache
  16457. var h, hl = this.hierarchy.length,
  16458. object,
  16459. node;
  16460. for ( h = 0; h < hl; h++ ) {
  16461. object = this.hierarchy[ h ];
  16462. node = this.data.hierarchy[ h ];
  16463. object.useQuaternion = true;
  16464. if ( node.animationCache === undefined ) {
  16465. node.animationCache = {};
  16466. node.animationCache.prevKey = null;
  16467. node.animationCache.nextKey = null;
  16468. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  16469. }
  16470. var keys = this.data.hierarchy[h].keys;
  16471. if (keys.length) {
  16472. node.animationCache.prevKey = keys[ 0 ];
  16473. node.animationCache.nextKey = keys[ 1 ];
  16474. this.startTime = Math.min( keys[0].time, this.startTime );
  16475. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  16476. }
  16477. }
  16478. this.update( 0 );
  16479. }
  16480. this.isPaused = false;
  16481. THREE.AnimationHandler.addToUpdate( this );
  16482. };
  16483. // Pause
  16484. THREE.KeyFrameAnimation.prototype.pause = function() {
  16485. if( this.isPaused ) {
  16486. THREE.AnimationHandler.addToUpdate( this );
  16487. } else {
  16488. THREE.AnimationHandler.removeFromUpdate( this );
  16489. }
  16490. this.isPaused = !this.isPaused;
  16491. };
  16492. // Stop
  16493. THREE.KeyFrameAnimation.prototype.stop = function() {
  16494. this.isPlaying = false;
  16495. this.isPaused = false;
  16496. THREE.AnimationHandler.removeFromUpdate( this );
  16497. // reset JIT matrix and remove cache
  16498. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  16499. var obj = this.hierarchy[ h ];
  16500. var node = this.data.hierarchy[ h ];
  16501. if ( node.animationCache !== undefined ) {
  16502. var original = node.animationCache.originalMatrix;
  16503. if( obj instanceof THREE.Bone ) {
  16504. original.copy( obj.skinMatrix );
  16505. obj.skinMatrix = original;
  16506. } else {
  16507. original.copy( obj.matrix );
  16508. obj.matrix = original;
  16509. }
  16510. delete node.animationCache;
  16511. }
  16512. }
  16513. };
  16514. // Update
  16515. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  16516. // early out
  16517. if( !this.isPlaying ) return;
  16518. // vars
  16519. var prevKey, nextKey;
  16520. var object;
  16521. var node;
  16522. var frame;
  16523. var JIThierarchy = this.data.JIT.hierarchy;
  16524. var currentTime, unloopedCurrentTime;
  16525. var looped;
  16526. // update
  16527. this.currentTime += deltaTimeMS * this.timeScale;
  16528. unloopedCurrentTime = this.currentTime;
  16529. currentTime = this.currentTime = this.currentTime % this.data.length;
  16530. // if looped around, the current time should be based on the startTime
  16531. if ( currentTime < this.startTimeMs ) {
  16532. currentTime = this.currentTime = this.startTimeMs + currentTime;
  16533. }
  16534. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  16535. looped = currentTime < unloopedCurrentTime;
  16536. if ( looped && !this.loop ) {
  16537. // Set the animation to the last keyframes and stop
  16538. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  16539. var keys = this.data.hierarchy[h].keys,
  16540. sids = this.data.hierarchy[h].sids,
  16541. end = keys.length-1,
  16542. obj = this.hierarchy[h];
  16543. if ( keys.length ) {
  16544. for ( var s = 0; s < sids.length; s++ ) {
  16545. var sid = sids[ s ],
  16546. prev = this.getPrevKeyWith( sid, h, end );
  16547. if ( prev ) {
  16548. prev.apply( sid );
  16549. }
  16550. }
  16551. this.data.hierarchy[h].node.updateMatrix();
  16552. obj.matrixWorldNeedsUpdate = true;
  16553. }
  16554. }
  16555. this.stop();
  16556. return;
  16557. }
  16558. // check pre-infinity
  16559. if ( currentTime < this.startTime ) {
  16560. return;
  16561. }
  16562. // update
  16563. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  16564. object = this.hierarchy[ h ];
  16565. node = this.data.hierarchy[ h ];
  16566. var keys = node.keys,
  16567. animationCache = node.animationCache;
  16568. // use JIT?
  16569. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  16570. if( object instanceof THREE.Bone ) {
  16571. object.skinMatrix = JIThierarchy[ h ][ frame ];
  16572. object.matrixWorldNeedsUpdate = false;
  16573. } else {
  16574. object.matrix = JIThierarchy[ h ][ frame ];
  16575. object.matrixWorldNeedsUpdate = true;
  16576. }
  16577. // use interpolation
  16578. } else if ( keys.length ) {
  16579. // make sure so original matrix and not JIT matrix is set
  16580. if ( this.JITCompile && animationCache ) {
  16581. if( object instanceof THREE.Bone ) {
  16582. object.skinMatrix = animationCache.originalMatrix;
  16583. } else {
  16584. object.matrix = animationCache.originalMatrix;
  16585. }
  16586. }
  16587. prevKey = animationCache.prevKey;
  16588. nextKey = animationCache.nextKey;
  16589. if ( prevKey && nextKey ) {
  16590. // switch keys?
  16591. if ( nextKey.time <= unloopedCurrentTime ) {
  16592. // did we loop?
  16593. if ( looped && this.loop ) {
  16594. prevKey = keys[ 0 ];
  16595. nextKey = keys[ 1 ];
  16596. while ( nextKey.time < currentTime ) {
  16597. prevKey = nextKey;
  16598. nextKey = keys[ prevKey.index + 1 ];
  16599. }
  16600. } else if ( !looped ) {
  16601. var lastIndex = keys.length - 1;
  16602. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  16603. prevKey = nextKey;
  16604. nextKey = keys[ prevKey.index + 1 ];
  16605. }
  16606. }
  16607. animationCache.prevKey = prevKey;
  16608. animationCache.nextKey = nextKey;
  16609. }
  16610. if(nextKey.time >= currentTime)
  16611. prevKey.interpolate( nextKey, currentTime );
  16612. else
  16613. prevKey.interpolate( nextKey, nextKey.time);
  16614. }
  16615. this.data.hierarchy[h].node.updateMatrix();
  16616. object.matrixWorldNeedsUpdate = true;
  16617. }
  16618. }
  16619. // update JIT?
  16620. if ( this.JITCompile ) {
  16621. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  16622. this.hierarchy[ 0 ].updateMatrixWorld( true );
  16623. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  16624. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  16625. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  16626. } else {
  16627. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  16628. }
  16629. }
  16630. }
  16631. }
  16632. };
  16633. // Get next key with
  16634. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  16635. var keys = this.data.hierarchy[ h ].keys;
  16636. key = key % keys.length;
  16637. for ( ; key < keys.length; key++ ) {
  16638. if ( keys[ key ].hasTarget( sid ) ) {
  16639. return keys[ key ];
  16640. }
  16641. }
  16642. return keys[ 0 ];
  16643. };
  16644. // Get previous key with
  16645. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  16646. var keys = this.data.hierarchy[ h ].keys;
  16647. key = key >= 0 ? key : key + keys.length;
  16648. for ( ; key >= 0; key-- ) {
  16649. if ( keys[ key ].hasTarget( sid ) ) {
  16650. return keys[ key ];
  16651. }
  16652. }
  16653. return keys[ keys.length - 1 ];
  16654. };
  16655. /**
  16656. * Camera for rendering cube maps
  16657. * - renders scene into axis-aligned cube
  16658. *
  16659. * @author alteredq / http://alteredqualia.com/
  16660. */
  16661. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  16662. THREE.Object3D.call( this );
  16663. var fov = 90, aspect = 1;
  16664. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16665. cameraPX.up.set( 0, -1, 0 );
  16666. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  16667. this.add( cameraPX );
  16668. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16669. cameraNX.up.set( 0, -1, 0 );
  16670. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  16671. this.add( cameraNX );
  16672. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16673. cameraPY.up.set( 0, 0, 1 );
  16674. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  16675. this.add( cameraPY );
  16676. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16677. cameraNY.up.set( 0, 0, -1 );
  16678. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  16679. this.add( cameraNY );
  16680. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16681. cameraPZ.up.set( 0, -1, 0 );
  16682. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  16683. this.add( cameraPZ );
  16684. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  16685. cameraNZ.up.set( 0, -1, 0 );
  16686. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  16687. this.add( cameraNZ );
  16688. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  16689. this.updateCubeMap = function ( renderer, scene ) {
  16690. var renderTarget = this.renderTarget;
  16691. var generateMipmaps = renderTarget.generateMipmaps;
  16692. renderTarget.generateMipmaps = false;
  16693. renderTarget.activeCubeFace = 0;
  16694. renderer.render( scene, cameraPX, renderTarget );
  16695. renderTarget.activeCubeFace = 1;
  16696. renderer.render( scene, cameraNX, renderTarget );
  16697. renderTarget.activeCubeFace = 2;
  16698. renderer.render( scene, cameraPY, renderTarget );
  16699. renderTarget.activeCubeFace = 3;
  16700. renderer.render( scene, cameraNY, renderTarget );
  16701. renderTarget.activeCubeFace = 4;
  16702. renderer.render( scene, cameraPZ, renderTarget );
  16703. renderTarget.generateMipmaps = generateMipmaps;
  16704. renderTarget.activeCubeFace = 5;
  16705. renderer.render( scene, cameraNZ, renderTarget );
  16706. };
  16707. };
  16708. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  16709. /*
  16710. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  16711. *
  16712. * A general perpose camera, for setting FOV, Lens Focal Length,
  16713. * and switching between perspective and orthographic views easily.
  16714. * Use this only if you do not wish to manage
  16715. * both a Orthographic and Perspective Camera
  16716. *
  16717. */
  16718. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  16719. THREE.Camera.call( this );
  16720. this.fov = fov;
  16721. this.left = -width / 2;
  16722. this.right = width / 2
  16723. this.top = height / 2;
  16724. this.bottom = -height / 2;
  16725. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  16726. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  16727. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  16728. this.zoom = 1;
  16729. this.toPerspective();
  16730. var aspect = width/height;
  16731. };
  16732. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  16733. THREE.CombinedCamera.prototype.toPerspective = function () {
  16734. // Switches to the Perspective Camera
  16735. this.near = this.cameraP.near;
  16736. this.far = this.cameraP.far;
  16737. this.cameraP.fov = this.fov / this.zoom ;
  16738. this.cameraP.updateProjectionMatrix();
  16739. this.projectionMatrix = this.cameraP.projectionMatrix;
  16740. this.inPerspectiveMode = true;
  16741. this.inOrthographicMode = false;
  16742. };
  16743. THREE.CombinedCamera.prototype.toOrthographic = function () {
  16744. // Switches to the Orthographic camera estimating viewport from Perspective
  16745. var fov = this.fov;
  16746. var aspect = this.cameraP.aspect;
  16747. var near = this.cameraP.near;
  16748. var far = this.cameraP.far;
  16749. // The size that we set is the mid plane of the viewing frustum
  16750. var hyperfocus = ( near + far ) / 2;
  16751. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  16752. var planeHeight = 2 * halfHeight;
  16753. var planeWidth = planeHeight * aspect;
  16754. var halfWidth = planeWidth / 2;
  16755. halfHeight /= this.zoom;
  16756. halfWidth /= this.zoom;
  16757. this.cameraO.left = -halfWidth;
  16758. this.cameraO.right = halfWidth;
  16759. this.cameraO.top = halfHeight;
  16760. this.cameraO.bottom = -halfHeight;
  16761. // this.cameraO.left = -farHalfWidth;
  16762. // this.cameraO.right = farHalfWidth;
  16763. // this.cameraO.top = farHalfHeight;
  16764. // this.cameraO.bottom = -farHalfHeight;
  16765. // this.cameraO.left = this.left / this.zoom;
  16766. // this.cameraO.right = this.right / this.zoom;
  16767. // this.cameraO.top = this.top / this.zoom;
  16768. // this.cameraO.bottom = this.bottom / this.zoom;
  16769. this.cameraO.updateProjectionMatrix();
  16770. this.near = this.cameraO.near;
  16771. this.far = this.cameraO.far;
  16772. this.projectionMatrix = this.cameraO.projectionMatrix;
  16773. this.inPerspectiveMode = false;
  16774. this.inOrthographicMode = true;
  16775. };
  16776. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  16777. this.cameraP.aspect = width / height;
  16778. this.left = -width / 2;
  16779. this.right = width / 2
  16780. this.top = height / 2;
  16781. this.bottom = -height / 2;
  16782. };
  16783. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  16784. this.fov = fov;
  16785. if ( this.inPerspectiveMode ) {
  16786. this.toPerspective();
  16787. } else {
  16788. this.toOrthographic();
  16789. }
  16790. };
  16791. // For mantaining similar API with PerspectiveCamera
  16792. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  16793. if ( this.inPerspectiveMode ) {
  16794. this.toPerspective();
  16795. } else {
  16796. this.toPerspective();
  16797. this.toOrthographic();
  16798. }
  16799. };
  16800. /*
  16801. * Uses Focal Length (in mm) to estimate and set FOV
  16802. * 35mm (fullframe) camera is used if frame size is not specified;
  16803. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  16804. */
  16805. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  16806. if ( frameHeight === undefined ) frameHeight = 24;
  16807. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  16808. this.setFov( fov );
  16809. return fov;
  16810. };
  16811. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  16812. this.zoom = zoom;
  16813. if ( this.inPerspectiveMode ) {
  16814. this.toPerspective();
  16815. } else {
  16816. this.toOrthographic();
  16817. }
  16818. };
  16819. THREE.CombinedCamera.prototype.toFrontView = function() {
  16820. this.rotation.x = 0;
  16821. this.rotation.y = 0;
  16822. this.rotation.z = 0;
  16823. // should we be modifing the matrix instead?
  16824. this.rotationAutoUpdate = false;
  16825. };
  16826. THREE.CombinedCamera.prototype.toBackView = function() {
  16827. this.rotation.x = 0;
  16828. this.rotation.y = Math.PI;
  16829. this.rotation.z = 0;
  16830. this.rotationAutoUpdate = false;
  16831. };
  16832. THREE.CombinedCamera.prototype.toLeftView = function() {
  16833. this.rotation.x = 0;
  16834. this.rotation.y = - Math.PI / 2;
  16835. this.rotation.z = 0;
  16836. this.rotationAutoUpdate = false;
  16837. };
  16838. THREE.CombinedCamera.prototype.toRightView = function() {
  16839. this.rotation.x = 0;
  16840. this.rotation.y = Math.PI / 2;
  16841. this.rotation.z = 0;
  16842. this.rotationAutoUpdate = false;
  16843. };
  16844. THREE.CombinedCamera.prototype.toTopView = function() {
  16845. this.rotation.x = - Math.PI / 2;
  16846. this.rotation.y = 0;
  16847. this.rotation.z = 0;
  16848. this.rotationAutoUpdate = false;
  16849. };
  16850. THREE.CombinedCamera.prototype.toBottomView = function() {
  16851. this.rotation.x = Math.PI / 2;
  16852. this.rotation.y = 0;
  16853. this.rotation.z = 0;
  16854. this.rotationAutoUpdate = false;
  16855. };
  16856. /**
  16857. * @author mrdoob / http://mrdoob.com/
  16858. * @author alteredq / http://alteredqualia.com/
  16859. * @author paulirish / http://paulirish.com/
  16860. */
  16861. THREE.FirstPersonControls = function ( object, domElement ) {
  16862. this.object = object;
  16863. this.target = new THREE.Vector3( 0, 0, 0 );
  16864. this.domElement = ( domElement !== undefined ) ? domElement : document;
  16865. this.movementSpeed = 1.0;
  16866. this.lookSpeed = 0.005;
  16867. this.lookVertical = true;
  16868. this.autoForward = false;
  16869. // this.invertVertical = false;
  16870. this.activeLook = true;
  16871. this.heightSpeed = false;
  16872. this.heightCoef = 1.0;
  16873. this.heightMin = 0.0;
  16874. this.heightMax = 1.0;
  16875. this.constrainVertical = false;
  16876. this.verticalMin = 0;
  16877. this.verticalMax = Math.PI;
  16878. this.autoSpeedFactor = 0.0;
  16879. this.mouseX = 0;
  16880. this.mouseY = 0;
  16881. this.lat = 0;
  16882. this.lon = 0;
  16883. this.phi = 0;
  16884. this.theta = 0;
  16885. this.moveForward = false;
  16886. this.moveBackward = false;
  16887. this.moveLeft = false;
  16888. this.moveRight = false;
  16889. this.freeze = false;
  16890. this.mouseDragOn = false;
  16891. this.viewHalfX = 0;
  16892. this.viewHalfY = 0;
  16893. if ( this.domElement !== document ) {
  16894. this.domElement.setAttribute( 'tabindex', -1 );
  16895. }
  16896. //
  16897. this.handleResize = function () {
  16898. if ( this.domElement === document ) {
  16899. this.viewHalfX = window.innerWidth / 2;
  16900. this.viewHalfY = window.innerHeight / 2;
  16901. } else {
  16902. this.viewHalfX = this.domElement.offsetWidth / 2;
  16903. this.viewHalfY = this.domElement.offsetHeight / 2;
  16904. }
  16905. };
  16906. this.onMouseDown = function ( event ) {
  16907. if ( this.domElement !== document ) {
  16908. this.domElement.focus();
  16909. }
  16910. event.preventDefault();
  16911. event.stopPropagation();
  16912. if ( this.activeLook ) {
  16913. switch ( event.button ) {
  16914. case 0: this.moveForward = true; break;
  16915. case 2: this.moveBackward = true; break;
  16916. }
  16917. }
  16918. this.mouseDragOn = true;
  16919. };
  16920. this.onMouseUp = function ( event ) {
  16921. event.preventDefault();
  16922. event.stopPropagation();
  16923. if ( this.activeLook ) {
  16924. switch ( event.button ) {
  16925. case 0: this.moveForward = false; break;
  16926. case 2: this.moveBackward = false; break;
  16927. }
  16928. }
  16929. this.mouseDragOn = false;
  16930. };
  16931. this.onMouseMove = function ( event ) {
  16932. if ( this.domElement === document ) {
  16933. this.mouseX = event.pageX - this.viewHalfX;
  16934. this.mouseY = event.pageY - this.viewHalfY;
  16935. } else {
  16936. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  16937. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  16938. }
  16939. };
  16940. this.onKeyDown = function ( event ) {
  16941. //event.preventDefault();
  16942. switch ( event.keyCode ) {
  16943. case 38: /*up*/
  16944. case 87: /*W*/ this.moveForward = true; break;
  16945. case 37: /*left*/
  16946. case 65: /*A*/ this.moveLeft = true; break;
  16947. case 40: /*down*/
  16948. case 83: /*S*/ this.moveBackward = true; break;
  16949. case 39: /*right*/
  16950. case 68: /*D*/ this.moveRight = true; break;
  16951. case 82: /*R*/ this.moveUp = true; break;
  16952. case 70: /*F*/ this.moveDown = true; break;
  16953. case 81: /*Q*/ this.freeze = !this.freeze; break;
  16954. }
  16955. };
  16956. this.onKeyUp = function ( event ) {
  16957. switch( event.keyCode ) {
  16958. case 38: /*up*/
  16959. case 87: /*W*/ this.moveForward = false; break;
  16960. case 37: /*left*/
  16961. case 65: /*A*/ this.moveLeft = false; break;
  16962. case 40: /*down*/
  16963. case 83: /*S*/ this.moveBackward = false; break;
  16964. case 39: /*right*/
  16965. case 68: /*D*/ this.moveRight = false; break;
  16966. case 82: /*R*/ this.moveUp = false; break;
  16967. case 70: /*F*/ this.moveDown = false; break;
  16968. }
  16969. };
  16970. this.update = function( delta ) {
  16971. var actualMoveSpeed = 0;
  16972. if ( this.freeze ) {
  16973. return;
  16974. } else {
  16975. if ( this.heightSpeed ) {
  16976. var y = THREE.Math.clamp( this.object.position.y, this.heightMin, this.heightMax );
  16977. var heightDelta = y - this.heightMin;
  16978. this.autoSpeedFactor = delta * ( heightDelta * this.heightCoef );
  16979. } else {
  16980. this.autoSpeedFactor = 0.0;
  16981. }
  16982. actualMoveSpeed = delta * this.movementSpeed;
  16983. if ( this.moveForward || ( this.autoForward && !this.moveBackward ) ) this.object.translateZ( - ( actualMoveSpeed + this.autoSpeedFactor ) );
  16984. if ( this.moveBackward ) this.object.translateZ( actualMoveSpeed );
  16985. if ( this.moveLeft ) this.object.translateX( - actualMoveSpeed );
  16986. if ( this.moveRight ) this.object.translateX( actualMoveSpeed );
  16987. if ( this.moveUp ) this.object.translateY( actualMoveSpeed );
  16988. if ( this.moveDown ) this.object.translateY( - actualMoveSpeed );
  16989. var actualLookSpeed = delta * this.lookSpeed;
  16990. if ( !this.activeLook ) {
  16991. actualLookSpeed = 0;
  16992. }
  16993. this.lon += this.mouseX * actualLookSpeed;
  16994. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed; // * this.invertVertical?-1:1;
  16995. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  16996. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  16997. this.theta = this.lon * Math.PI / 180;
  16998. var targetPosition = this.target,
  16999. position = this.object.position;
  17000. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  17001. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  17002. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  17003. }
  17004. var verticalLookRatio = 1;
  17005. if ( this.constrainVertical ) {
  17006. verticalLookRatio = Math.PI / ( this.verticalMax - this.verticalMin );
  17007. }
  17008. this.lon += this.mouseX * actualLookSpeed;
  17009. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed * verticalLookRatio;
  17010. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  17011. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  17012. this.theta = this.lon * Math.PI / 180;
  17013. if ( this.constrainVertical ) {
  17014. this.phi = THREE.Math.mapLinear( this.phi, 0, Math.PI, this.verticalMin, this.verticalMax );
  17015. }
  17016. var targetPosition = this.target,
  17017. position = this.object.position;
  17018. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  17019. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  17020. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  17021. this.object.lookAt( targetPosition );
  17022. };
  17023. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  17024. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  17025. this.domElement.addEventListener( 'mousedown', bind( this, this.onMouseDown ), false );
  17026. this.domElement.addEventListener( 'mouseup', bind( this, this.onMouseUp ), false );
  17027. this.domElement.addEventListener( 'keydown', bind( this, this.onKeyDown ), false );
  17028. this.domElement.addEventListener( 'keyup', bind( this, this.onKeyUp ), false );
  17029. function bind( scope, fn ) {
  17030. return function () {
  17031. fn.apply( scope, arguments );
  17032. };
  17033. };
  17034. this.handleResize();
  17035. };
  17036. /**
  17037. * @author alteredq / http://alteredqualia.com/
  17038. */
  17039. THREE.PathControls = function ( object, domElement ) {
  17040. this.object = object;
  17041. this.domElement = ( domElement !== undefined ) ? domElement : document;
  17042. this.id = "PathControls" + THREE.PathControlsIdCounter ++;
  17043. // API
  17044. this.duration = 10 * 1000; // milliseconds
  17045. this.waypoints = [];
  17046. this.useConstantSpeed = true;
  17047. this.resamplingCoef = 50;
  17048. this.debugPath = new THREE.Object3D();
  17049. this.debugDummy = new THREE.Object3D();
  17050. this.animationParent = new THREE.Object3D();
  17051. this.lookSpeed = 0.005;
  17052. this.lookVertical = true;
  17053. this.lookHorizontal = true;
  17054. this.verticalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  17055. this.horizontalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  17056. // internals
  17057. this.target = new THREE.Object3D();
  17058. this.mouseX = 0;
  17059. this.mouseY = 0;
  17060. this.lat = 0;
  17061. this.lon = 0;
  17062. this.phi = 0;
  17063. this.theta = 0;
  17064. var PI2 = Math.PI * 2,
  17065. PI180 = Math.PI / 180;
  17066. this.viewHalfX = 0;
  17067. this.viewHalfY = 0;
  17068. if ( this.domElement !== document ) {
  17069. this.domElement.setAttribute( 'tabindex', -1 );
  17070. }
  17071. // methods
  17072. this.handleResize = function () {
  17073. if ( this.domElement === document ) {
  17074. this.viewHalfX = window.innerWidth / 2;
  17075. this.viewHalfY = window.innerHeight / 2;
  17076. } else {
  17077. this.viewHalfX = this.domElement.offsetWidth / 2;
  17078. this.viewHalfY = this.domElement.offsetHeight / 2;
  17079. }
  17080. };
  17081. this.update = function ( delta ) {
  17082. var srcRange, dstRange;
  17083. if( this.lookHorizontal ) this.lon += this.mouseX * this.lookSpeed * delta;
  17084. if( this.lookVertical ) this.lat -= this.mouseY * this.lookSpeed * delta;
  17085. this.lon = Math.max( 0, Math.min( 360, this.lon ) );
  17086. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  17087. this.phi = ( 90 - this.lat ) * PI180;
  17088. this.theta = this.lon * PI180;
  17089. this.phi = normalize_angle_rad( this.phi );
  17090. // constrain vertical look angle
  17091. srcRange = this.verticalAngleMap.srcRange;
  17092. dstRange = this.verticalAngleMap.dstRange;
  17093. var tmpPhi = THREE.Math.mapLinear( this.phi, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  17094. var tmpPhiFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  17095. var tmpPhiNormalized = ( tmpPhi - dstRange[ 0 ] ) / tmpPhiFullRange;
  17096. this.phi = QuadraticEaseInOut( tmpPhiNormalized ) * tmpPhiFullRange + dstRange[ 0 ];
  17097. // constrain horizontal look angle
  17098. srcRange = this.horizontalAngleMap.srcRange;
  17099. dstRange = this.horizontalAngleMap.dstRange;
  17100. var tmpTheta = THREE.Math.mapLinear( this.theta, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  17101. var tmpThetaFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  17102. var tmpThetaNormalized = ( tmpTheta - dstRange[ 0 ] ) / tmpThetaFullRange;
  17103. this.theta = QuadraticEaseInOut( tmpThetaNormalized ) * tmpThetaFullRange + dstRange[ 0 ];
  17104. var targetPosition = this.target.position,
  17105. position = this.object.position;
  17106. targetPosition.x = 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  17107. targetPosition.y = 100 * Math.cos( this.phi );
  17108. targetPosition.z = 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  17109. this.object.lookAt( this.target.position );
  17110. };
  17111. this.onMouseMove = function ( event ) {
  17112. if ( this.domElement === document ) {
  17113. this.mouseX = event.pageX - this.viewHalfX;
  17114. this.mouseY = event.pageY - this.viewHalfY;
  17115. } else {
  17116. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  17117. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  17118. }
  17119. };
  17120. // utils
  17121. function normalize_angle_rad( a ) {
  17122. var b = a % PI2;
  17123. return b >= 0 ? b : b + PI2;
  17124. };
  17125. function distance( a, b ) {
  17126. var dx = a[ 0 ] - b[ 0 ],
  17127. dy = a[ 1 ] - b[ 1 ],
  17128. dz = a[ 2 ] - b[ 2 ];
  17129. return Math.sqrt( dx * dx + dy * dy + dz * dz );
  17130. };
  17131. function QuadraticEaseInOut ( k ) {
  17132. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k;
  17133. return - 0.5 * ( --k * ( k - 2 ) - 1 );
  17134. };
  17135. function bind( scope, fn ) {
  17136. return function () {
  17137. fn.apply( scope, arguments );
  17138. };
  17139. };
  17140. function initAnimationPath( parent, spline, name, duration ) {
  17141. var animationData = {
  17142. name: name,
  17143. fps: 0.6,
  17144. length: duration,
  17145. hierarchy: []
  17146. };
  17147. var i,
  17148. parentAnimation, childAnimation,
  17149. path = spline.getControlPointsArray(),
  17150. sl = spline.getLength(),
  17151. pl = path.length,
  17152. t = 0,
  17153. first = 0,
  17154. last = pl - 1;
  17155. parentAnimation = { parent: -1, keys: [] };
  17156. parentAnimation.keys[ first ] = { time: 0, pos: path[ first ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  17157. parentAnimation.keys[ last ] = { time: duration, pos: path[ last ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  17158. for ( i = 1; i < pl - 1; i++ ) {
  17159. // real distance (approximation via linear segments)
  17160. t = duration * sl.chunks[ i ] / sl.total;
  17161. // equal distance
  17162. //t = duration * ( i / pl );
  17163. // linear distance
  17164. //t += duration * distance( path[ i ], path[ i - 1 ] ) / sl.total;
  17165. parentAnimation.keys[ i ] = { time: t, pos: path[ i ] };
  17166. }
  17167. animationData.hierarchy[ 0 ] = parentAnimation;
  17168. THREE.AnimationHandler.add( animationData );
  17169. return new THREE.Animation( parent, name, THREE.AnimationHandler.CATMULLROM_FORWARD, false );
  17170. };
  17171. function createSplineGeometry( spline, n_sub ) {
  17172. var i, index, position,
  17173. geometry = new THREE.Geometry();
  17174. for ( i = 0; i < spline.points.length * n_sub; i ++ ) {
  17175. index = i / ( spline.points.length * n_sub );
  17176. position = spline.getPoint( index );
  17177. geometry.vertices[ i ] = new THREE.Vector3( position.x, position.y, position.z );
  17178. }
  17179. return geometry;
  17180. };
  17181. function createPath( parent, spline ) {
  17182. var lineGeo = createSplineGeometry( spline, 10 ),
  17183. particleGeo = createSplineGeometry( spline, 10 ),
  17184. lineMat = new THREE.LineBasicMaterial( { color: 0xff0000, linewidth: 3 } ),
  17185. lineObj = new THREE.Line( lineGeo, lineMat ),
  17186. particleObj = new THREE.ParticleSystem( particleGeo, new THREE.ParticleBasicMaterial( { color: 0xffaa00, size: 3 } ) );
  17187. lineObj.scale.set( 1, 1, 1 );
  17188. parent.add( lineObj );
  17189. particleObj.scale.set( 1, 1, 1 );
  17190. parent.add( particleObj );
  17191. var waypoint,
  17192. geo = new THREE.SphereGeometry( 1, 16, 8 ),
  17193. mat = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  17194. for ( var i = 0; i < spline.points.length; i ++ ) {
  17195. waypoint = new THREE.Mesh( geo, mat );
  17196. waypoint.position.copy( spline.points[ i ] );
  17197. parent.add( waypoint );
  17198. }
  17199. };
  17200. this.init = function ( ) {
  17201. // constructor
  17202. this.spline = new THREE.Spline();
  17203. this.spline.initFromArray( this.waypoints );
  17204. if ( this.useConstantSpeed ) {
  17205. this.spline.reparametrizeByArcLength( this.resamplingCoef );
  17206. }
  17207. if ( this.createDebugDummy ) {
  17208. var dummyParentMaterial = new THREE.MeshLambertMaterial( { color: 0x0077ff } ),
  17209. dummyChildMaterial = new THREE.MeshLambertMaterial( { color: 0x00ff00 } ),
  17210. dummyParentGeo = new THREE.CubeGeometry( 10, 10, 20 ),
  17211. dummyChildGeo = new THREE.CubeGeometry( 2, 2, 10 );
  17212. this.animationParent = new THREE.Mesh( dummyParentGeo, dummyParentMaterial );
  17213. var dummyChild = new THREE.Mesh( dummyChildGeo, dummyChildMaterial );
  17214. dummyChild.position.set( 0, 10, 0 );
  17215. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  17216. this.animationParent.add( this.object );
  17217. this.animationParent.add( this.target );
  17218. this.animationParent.add( dummyChild );
  17219. } else {
  17220. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  17221. this.animationParent.add( this.target );
  17222. this.animationParent.add( this.object );
  17223. }
  17224. if ( this.createDebugPath ) {
  17225. createPath( this.debugPath, this.spline );
  17226. }
  17227. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  17228. };
  17229. this.handleResize();
  17230. };
  17231. THREE.PathControlsIdCounter = 0;
  17232. /**
  17233. * @author James Baicoianu / http://www.baicoianu.com/
  17234. */
  17235. THREE.FlyControls = function ( object, domElement ) {
  17236. this.object = object;
  17237. this.domElement = ( domElement !== undefined ) ? domElement : document;
  17238. if ( domElement ) this.domElement.setAttribute( 'tabindex', -1 );
  17239. // API
  17240. this.movementSpeed = 1.0;
  17241. this.rollSpeed = 0.005;
  17242. this.dragToLook = false;
  17243. this.autoForward = false;
  17244. // disable default target object behavior
  17245. this.object.useQuaternion = true;
  17246. // internals
  17247. this.tmpQuaternion = new THREE.Quaternion();
  17248. this.mouseStatus = 0;
  17249. this.moveState = { up: 0, down: 0, left: 0, right: 0, forward: 0, back: 0, pitchUp: 0, pitchDown: 0, yawLeft: 0, yawRight: 0, rollLeft: 0, rollRight: 0 };
  17250. this.moveVector = new THREE.Vector3( 0, 0, 0 );
  17251. this.rotationVector = new THREE.Vector3( 0, 0, 0 );
  17252. this.handleEvent = function ( event ) {
  17253. if ( typeof this[ event.type ] == 'function' ) {
  17254. this[ event.type ]( event );
  17255. }
  17256. };
  17257. this.keydown = function( event ) {
  17258. if ( event.altKey ) {
  17259. return;
  17260. }
  17261. //event.preventDefault();
  17262. switch ( event.keyCode ) {
  17263. case 16: /* shift */ this.movementSpeedMultiplier = .1; break;
  17264. case 87: /*W*/ this.moveState.forward = 1; break;
  17265. case 83: /*S*/ this.moveState.back = 1; break;
  17266. case 65: /*A*/ this.moveState.left = 1; break;
  17267. case 68: /*D*/ this.moveState.right = 1; break;
  17268. case 82: /*R*/ this.moveState.up = 1; break;
  17269. case 70: /*F*/ this.moveState.down = 1; break;
  17270. case 38: /*up*/ this.moveState.pitchUp = 1; break;
  17271. case 40: /*down*/ this.moveState.pitchDown = 1; break;
  17272. case 37: /*left*/ this.moveState.yawLeft = 1; break;
  17273. case 39: /*right*/ this.moveState.yawRight = 1; break;
  17274. case 81: /*Q*/ this.moveState.rollLeft = 1; break;
  17275. case 69: /*E*/ this.moveState.rollRight = 1; break;
  17276. }
  17277. this.updateMovementVector();
  17278. this.updateRotationVector();
  17279. };
  17280. this.keyup = function( event ) {
  17281. switch( event.keyCode ) {
  17282. case 16: /* shift */ this.movementSpeedMultiplier = 1; break;
  17283. case 87: /*W*/ this.moveState.forward = 0; break;
  17284. case 83: /*S*/ this.moveState.back = 0; break;
  17285. case 65: /*A*/ this.moveState.left = 0; break;
  17286. case 68: /*D*/ this.moveState.right = 0; break;
  17287. case 82: /*R*/ this.moveState.up = 0; break;
  17288. case 70: /*F*/ this.moveState.down = 0; break;
  17289. case 38: /*up*/ this.moveState.pitchUp = 0; break;
  17290. case 40: /*down*/ this.moveState.pitchDown = 0; break;
  17291. case 37: /*left*/ this.moveState.yawLeft = 0; break;
  17292. case 39: /*right*/ this.moveState.yawRight = 0; break;
  17293. case 81: /*Q*/ this.moveState.rollLeft = 0; break;
  17294. case 69: /*E*/ this.moveState.rollRight = 0; break;
  17295. }
  17296. this.updateMovementVector();
  17297. this.updateRotationVector();
  17298. };
  17299. this.mousedown = function( event ) {
  17300. if ( this.domElement !== document ) {
  17301. this.domElement.focus();
  17302. }
  17303. event.preventDefault();
  17304. event.stopPropagation();
  17305. if ( this.dragToLook ) {
  17306. this.mouseStatus ++;
  17307. } else {
  17308. switch ( event.button ) {
  17309. case 0: this.object.moveForward = true; break;
  17310. case 2: this.object.moveBackward = true; break;
  17311. }
  17312. }
  17313. };
  17314. this.mousemove = function( event ) {
  17315. if ( !this.dragToLook || this.mouseStatus > 0 ) {
  17316. var container = this.getContainerDimensions();
  17317. var halfWidth = container.size[ 0 ] / 2;
  17318. var halfHeight = container.size[ 1 ] / 2;
  17319. this.moveState.yawLeft = - ( ( event.pageX - container.offset[ 0 ] ) - halfWidth ) / halfWidth;
  17320. this.moveState.pitchDown = ( ( event.pageY - container.offset[ 1 ] ) - halfHeight ) / halfHeight;
  17321. this.updateRotationVector();
  17322. }
  17323. };
  17324. this.mouseup = function( event ) {
  17325. event.preventDefault();
  17326. event.stopPropagation();
  17327. if ( this.dragToLook ) {
  17328. this.mouseStatus --;
  17329. this.moveState.yawLeft = this.moveState.pitchDown = 0;
  17330. } else {
  17331. switch ( event.button ) {
  17332. case 0: this.moveForward = false; break;
  17333. case 2: this.moveBackward = false; break;
  17334. }
  17335. }
  17336. this.updateRotationVector();
  17337. };
  17338. this.update = function( delta ) {
  17339. var moveMult = delta * this.movementSpeed;
  17340. var rotMult = delta * this.rollSpeed;
  17341. this.object.translateX( this.moveVector.x * moveMult );
  17342. this.object.translateY( this.moveVector.y * moveMult );
  17343. this.object.translateZ( this.moveVector.z * moveMult );
  17344. this.tmpQuaternion.set( this.rotationVector.x * rotMult, this.rotationVector.y * rotMult, this.rotationVector.z * rotMult, 1 ).normalize();
  17345. this.object.quaternion.multiplySelf( this.tmpQuaternion );
  17346. this.object.matrix.setPosition( this.object.position );
  17347. this.object.matrix.setRotationFromQuaternion( this.object.quaternion );
  17348. this.object.matrixWorldNeedsUpdate = true;
  17349. };
  17350. this.updateMovementVector = function() {
  17351. var forward = ( this.moveState.forward || ( this.autoForward && !this.moveState.back ) ) ? 1 : 0;
  17352. this.moveVector.x = ( -this.moveState.left + this.moveState.right );
  17353. this.moveVector.y = ( -this.moveState.down + this.moveState.up );
  17354. this.moveVector.z = ( -forward + this.moveState.back );
  17355. //console.log( 'move:', [ this.moveVector.x, this.moveVector.y, this.moveVector.z ] );
  17356. };
  17357. this.updateRotationVector = function() {
  17358. this.rotationVector.x = ( -this.moveState.pitchDown + this.moveState.pitchUp );
  17359. this.rotationVector.y = ( -this.moveState.yawRight + this.moveState.yawLeft );
  17360. this.rotationVector.z = ( -this.moveState.rollRight + this.moveState.rollLeft );
  17361. //console.log( 'rotate:', [ this.rotationVector.x, this.rotationVector.y, this.rotationVector.z ] );
  17362. };
  17363. this.getContainerDimensions = function() {
  17364. if ( this.domElement != document ) {
  17365. return {
  17366. size : [ this.domElement.offsetWidth, this.domElement.offsetHeight ],
  17367. offset : [ this.domElement.offsetLeft, this.domElement.offsetTop ]
  17368. };
  17369. } else {
  17370. return {
  17371. size : [ window.innerWidth, window.innerHeight ],
  17372. offset : [ 0, 0 ]
  17373. };
  17374. }
  17375. };
  17376. function bind( scope, fn ) {
  17377. return function () {
  17378. fn.apply( scope, arguments );
  17379. };
  17380. };
  17381. this.domElement.addEventListener( 'mousemove', bind( this, this.mousemove ), false );
  17382. this.domElement.addEventListener( 'mousedown', bind( this, this.mousedown ), false );
  17383. this.domElement.addEventListener( 'mouseup', bind( this, this.mouseup ), false );
  17384. this.domElement.addEventListener( 'keydown', bind( this, this.keydown ), false );
  17385. this.domElement.addEventListener( 'keyup', bind( this, this.keyup ), false );
  17386. this.updateMovementVector();
  17387. this.updateRotationVector();
  17388. };
  17389. /**
  17390. * @author mikael emtinger / http://gomo.se/
  17391. * @author alteredq / http://alteredqualia.com/
  17392. */
  17393. THREE.RollControls = function ( object, domElement ) {
  17394. this.object = object;
  17395. this.domElement = ( domElement !== undefined ) ? domElement : document;
  17396. // API
  17397. this.mouseLook = true;
  17398. this.autoForward = false;
  17399. this.lookSpeed = 1;
  17400. this.movementSpeed = 1;
  17401. this.rollSpeed = 1;
  17402. this.constrainVertical = [ -0.9, 0.9 ];
  17403. // disable default target object behavior
  17404. this.object.matrixAutoUpdate = false;
  17405. // internals
  17406. this.forward = new THREE.Vector3( 0, 0, 1 );
  17407. this.roll = 0;
  17408. var xTemp = new THREE.Vector3();
  17409. var yTemp = new THREE.Vector3();
  17410. var zTemp = new THREE.Vector3();
  17411. var rollMatrix = new THREE.Matrix4();
  17412. var doRoll = false, rollDirection = 1, forwardSpeed = 0, sideSpeed = 0, upSpeed = 0;
  17413. var mouseX = 0, mouseY = 0;
  17414. var windowHalfX = 0;
  17415. var windowHalfY = 0;
  17416. //
  17417. this.handleResize = function () {
  17418. windowHalfX = window.innerWidth / 2;
  17419. windowHalfY = window.innerHeight / 2;
  17420. };
  17421. // custom update
  17422. this.update = function ( delta ) {
  17423. if ( this.mouseLook ) {
  17424. var actualLookSpeed = delta * this.lookSpeed;
  17425. this.rotateHorizontally( actualLookSpeed * mouseX );
  17426. this.rotateVertically( actualLookSpeed * mouseY );
  17427. }
  17428. var actualSpeed = delta * this.movementSpeed;
  17429. var forwardOrAuto = ( forwardSpeed > 0 || ( this.autoForward && ! ( forwardSpeed < 0 ) ) ) ? 1 : forwardSpeed;
  17430. this.object.translateZ( -actualSpeed * forwardOrAuto );
  17431. this.object.translateX( actualSpeed * sideSpeed );
  17432. this.object.translateY( actualSpeed * upSpeed );
  17433. if( doRoll ) {
  17434. this.roll += this.rollSpeed * delta * rollDirection;
  17435. }
  17436. // cap forward up / down
  17437. if( this.forward.y > this.constrainVertical[ 1 ] ) {
  17438. this.forward.y = this.constrainVertical[ 1 ];
  17439. this.forward.normalize();
  17440. } else if( this.forward.y < this.constrainVertical[ 0 ] ) {
  17441. this.forward.y = this.constrainVertical[ 0 ];
  17442. this.forward.normalize();
  17443. }
  17444. // construct unrolled camera matrix
  17445. zTemp.copy( this.forward );
  17446. yTemp.set( 0, 1, 0 );
  17447. xTemp.cross( yTemp, zTemp ).normalize();
  17448. yTemp.cross( zTemp, xTemp ).normalize();
  17449. this.object.matrix.elements[0] = xTemp.x; this.object.matrix.elements[4] = yTemp.x; this.object.matrix.elements[8] = zTemp.x;
  17450. this.object.matrix.elements[1] = xTemp.y; this.object.matrix.elements[5] = yTemp.y; this.object.matrix.elements[9] = zTemp.y;
  17451. this.object.matrix.elements[2] = xTemp.z; this.object.matrix.elements[6] = yTemp.z; this.object.matrix.elements[10] = zTemp.z;
  17452. // calculate roll matrix
  17453. rollMatrix.identity();
  17454. rollMatrix.elements[0] = Math.cos( this.roll ); rollMatrix.elements[4] = -Math.sin( this.roll );
  17455. rollMatrix.elements[1] = Math.sin( this.roll ); rollMatrix.elements[5] = Math.cos( this.roll );
  17456. // multiply camera with roll
  17457. this.object.matrix.multiplySelf( rollMatrix );
  17458. this.object.matrixWorldNeedsUpdate = true;
  17459. // set position
  17460. this.object.matrix.elements[12] = this.object.position.x;
  17461. this.object.matrix.elements[13] = this.object.position.y;
  17462. this.object.matrix.elements[14] = this.object.position.z;
  17463. };
  17464. this.translateX = function ( distance ) {
  17465. this.object.position.x += this.object.matrix.elements[0] * distance;
  17466. this.object.position.y += this.object.matrix.elements[1] * distance;
  17467. this.object.position.z += this.object.matrix.elements[2] * distance;
  17468. };
  17469. this.translateY = function ( distance ) {
  17470. this.object.position.x += this.object.matrix.elements[4] * distance;
  17471. this.object.position.y += this.object.matrix.elements[5] * distance;
  17472. this.object.position.z += this.object.matrix.elements[6] * distance;
  17473. };
  17474. this.translateZ = function ( distance ) {
  17475. this.object.position.x -= this.object.matrix.elements[8] * distance;
  17476. this.object.position.y -= this.object.matrix.elements[9] * distance;
  17477. this.object.position.z -= this.object.matrix.elements[10] * distance;
  17478. };
  17479. this.rotateHorizontally = function ( amount ) {
  17480. // please note that the amount is NOT degrees, but a scale value
  17481. xTemp.set( this.object.matrix.elements[0], this.object.matrix.elements[1], this.object.matrix.elements[2] );
  17482. xTemp.multiplyScalar( amount );
  17483. this.forward.subSelf( xTemp );
  17484. this.forward.normalize();
  17485. };
  17486. this.rotateVertically = function ( amount ) {
  17487. // please note that the amount is NOT degrees, but a scale value
  17488. yTemp.set( this.object.matrix.elements[4], this.object.matrix.elements[5], this.object.matrix.elements[6] );
  17489. yTemp.multiplyScalar( amount );
  17490. this.forward.addSelf( yTemp );
  17491. this.forward.normalize();
  17492. };
  17493. function onKeyDown( event ) {
  17494. //event.preventDefault();
  17495. switch ( event.keyCode ) {
  17496. case 38: /*up*/
  17497. case 87: /*W*/ forwardSpeed = 1; break;
  17498. case 37: /*left*/
  17499. case 65: /*A*/ sideSpeed = -1; break;
  17500. case 40: /*down*/
  17501. case 83: /*S*/ forwardSpeed = -1; break;
  17502. case 39: /*right*/
  17503. case 68: /*D*/ sideSpeed = 1; break;
  17504. case 81: /*Q*/ doRoll = true; rollDirection = 1; break;
  17505. case 69: /*E*/ doRoll = true; rollDirection = -1; break;
  17506. case 82: /*R*/ upSpeed = 1; break;
  17507. case 70: /*F*/ upSpeed = -1; break;
  17508. }
  17509. };
  17510. function onKeyUp( event ) {
  17511. switch( event.keyCode ) {
  17512. case 38: /*up*/
  17513. case 87: /*W*/ forwardSpeed = 0; break;
  17514. case 37: /*left*/
  17515. case 65: /*A*/ sideSpeed = 0; break;
  17516. case 40: /*down*/
  17517. case 83: /*S*/ forwardSpeed = 0; break;
  17518. case 39: /*right*/
  17519. case 68: /*D*/ sideSpeed = 0; break;
  17520. case 81: /*Q*/ doRoll = false; break;
  17521. case 69: /*E*/ doRoll = false; break;
  17522. case 82: /*R*/ upSpeed = 0; break;
  17523. case 70: /*F*/ upSpeed = 0; break;
  17524. }
  17525. };
  17526. function onMouseMove( event ) {
  17527. mouseX = ( event.clientX - windowHalfX ) / window.innerWidth;
  17528. mouseY = ( event.clientY - windowHalfY ) / window.innerHeight;
  17529. };
  17530. function onMouseDown ( event ) {
  17531. event.preventDefault();
  17532. event.stopPropagation();
  17533. switch ( event.button ) {
  17534. case 0: forwardSpeed = 1; break;
  17535. case 2: forwardSpeed = -1; break;
  17536. }
  17537. };
  17538. function onMouseUp ( event ) {
  17539. event.preventDefault();
  17540. event.stopPropagation();
  17541. switch ( event.button ) {
  17542. case 0: forwardSpeed = 0; break;
  17543. case 2: forwardSpeed = 0; break;
  17544. }
  17545. };
  17546. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  17547. this.domElement.addEventListener( 'mousemove', onMouseMove, false );
  17548. this.domElement.addEventListener( 'mousedown', onMouseDown, false );
  17549. this.domElement.addEventListener( 'mouseup', onMouseUp, false );
  17550. this.domElement.addEventListener( 'keydown', onKeyDown, false );
  17551. this.domElement.addEventListener( 'keyup', onKeyUp, false );
  17552. this.handleResize();
  17553. };
  17554. /**
  17555. * @author Eberhard Graether / http://egraether.com/
  17556. */
  17557. THREE.TrackballControls = function ( object, domElement ) {
  17558. THREE.EventTarget.call( this );
  17559. var _this = this,
  17560. STATE = { NONE : -1, ROTATE : 0, ZOOM : 1, PAN : 2 };
  17561. this.object = object;
  17562. this.domElement = ( domElement !== undefined ) ? domElement : document;
  17563. // API
  17564. this.enabled = true;
  17565. this.screen = { width: 0, height: 0, offsetLeft: 0, offsetTop: 0 };
  17566. this.radius = ( this.screen.width + this.screen.height ) / 4;
  17567. this.rotateSpeed = 1.0;
  17568. this.zoomSpeed = 1.2;
  17569. this.panSpeed = 0.3;
  17570. this.noRotate = false;
  17571. this.noZoom = false;
  17572. this.noPan = false;
  17573. this.staticMoving = false;
  17574. this.dynamicDampingFactor = 0.2;
  17575. this.minDistance = 0;
  17576. this.maxDistance = Infinity;
  17577. this.keys = [ 65 /*A*/, 83 /*S*/, 68 /*D*/ ];
  17578. // internals
  17579. this.target = new THREE.Vector3();
  17580. var lastPosition = new THREE.Vector3();
  17581. var _keyPressed = false,
  17582. _state = STATE.NONE,
  17583. _eye = new THREE.Vector3(),
  17584. _rotateStart = new THREE.Vector3(),
  17585. _rotateEnd = new THREE.Vector3(),
  17586. _zoomStart = new THREE.Vector2(),
  17587. _zoomEnd = new THREE.Vector2(),
  17588. _panStart = new THREE.Vector2(),
  17589. _panEnd = new THREE.Vector2();
  17590. // events
  17591. var changeEvent = { type: 'change' };
  17592. // methods
  17593. this.handleResize = function () {
  17594. this.screen.width = window.innerWidth;
  17595. this.screen.height = window.innerHeight;
  17596. this.screen.offsetLeft = 0;
  17597. this.screen.offsetTop = 0;
  17598. this.radius = ( this.screen.width + this.screen.height ) / 4;
  17599. };
  17600. this.handleEvent = function ( event ) {
  17601. if ( typeof this[ event.type ] == 'function' ) {
  17602. this[ event.type ]( event );
  17603. }
  17604. };
  17605. this.getMouseOnScreen = function ( clientX, clientY ) {
  17606. return new THREE.Vector2(
  17607. ( clientX - _this.screen.offsetLeft ) / _this.radius * 0.5,
  17608. ( clientY - _this.screen.offsetTop ) / _this.radius * 0.5
  17609. );
  17610. };
  17611. this.getMouseProjectionOnBall = function ( clientX, clientY ) {
  17612. var mouseOnBall = new THREE.Vector3(
  17613. ( clientX - _this.screen.width * 0.5 - _this.screen.offsetLeft ) / _this.radius,
  17614. ( _this.screen.height * 0.5 + _this.screen.offsetTop - clientY ) / _this.radius,
  17615. 0.0
  17616. );
  17617. var length = mouseOnBall.length();
  17618. if ( length > 1.0 ) {
  17619. mouseOnBall.normalize();
  17620. } else {
  17621. mouseOnBall.z = Math.sqrt( 1.0 - length * length );
  17622. }
  17623. _eye.copy( _this.object.position ).subSelf( _this.target );
  17624. var projection = _this.object.up.clone().setLength( mouseOnBall.y );
  17625. projection.addSelf( _this.object.up.clone().crossSelf( _eye ).setLength( mouseOnBall.x ) );
  17626. projection.addSelf( _eye.setLength( mouseOnBall.z ) );
  17627. return projection;
  17628. };
  17629. this.rotateCamera = function () {
  17630. var angle = Math.acos( _rotateStart.dot( _rotateEnd ) / _rotateStart.length() / _rotateEnd.length() );
  17631. if ( angle ) {
  17632. var axis = ( new THREE.Vector3() ).cross( _rotateStart, _rotateEnd ).normalize(),
  17633. quaternion = new THREE.Quaternion();
  17634. angle *= _this.rotateSpeed;
  17635. quaternion.setFromAxisAngle( axis, -angle );
  17636. quaternion.multiplyVector3( _eye );
  17637. quaternion.multiplyVector3( _this.object.up );
  17638. quaternion.multiplyVector3( _rotateEnd );
  17639. if ( _this.staticMoving ) {
  17640. _rotateStart = _rotateEnd;
  17641. } else {
  17642. quaternion.setFromAxisAngle( axis, angle * ( _this.dynamicDampingFactor - 1.0 ) );
  17643. quaternion.multiplyVector3( _rotateStart );
  17644. }
  17645. }
  17646. };
  17647. this.zoomCamera = function () {
  17648. var factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * _this.zoomSpeed;
  17649. if ( factor !== 1.0 && factor > 0.0 ) {
  17650. _eye.multiplyScalar( factor );
  17651. if ( _this.staticMoving ) {
  17652. _zoomStart = _zoomEnd;
  17653. } else {
  17654. _zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor;
  17655. }
  17656. }
  17657. };
  17658. this.panCamera = function () {
  17659. var mouseChange = _panEnd.clone().subSelf( _panStart );
  17660. if ( mouseChange.lengthSq() ) {
  17661. mouseChange.multiplyScalar( _eye.length() * _this.panSpeed );
  17662. var pan = _eye.clone().crossSelf( _this.object.up ).setLength( mouseChange.x );
  17663. pan.addSelf( _this.object.up.clone().setLength( mouseChange.y ) );
  17664. _this.object.position.addSelf( pan );
  17665. _this.target.addSelf( pan );
  17666. if ( _this.staticMoving ) {
  17667. _panStart = _panEnd;
  17668. } else {
  17669. _panStart.addSelf( mouseChange.sub( _panEnd, _panStart ).multiplyScalar( _this.dynamicDampingFactor ) );
  17670. }
  17671. }
  17672. };
  17673. this.checkDistances = function () {
  17674. if ( !_this.noZoom || !_this.noPan ) {
  17675. if ( _this.object.position.lengthSq() > _this.maxDistance * _this.maxDistance ) {
  17676. _this.object.position.setLength( _this.maxDistance );
  17677. }
  17678. if ( _eye.lengthSq() < _this.minDistance * _this.minDistance ) {
  17679. _this.object.position.add( _this.target, _eye.setLength( _this.minDistance ) );
  17680. }
  17681. }
  17682. };
  17683. this.update = function () {
  17684. _eye.copy( _this.object.position ).subSelf( _this.target );
  17685. if ( !_this.noRotate ) {
  17686. _this.rotateCamera();
  17687. }
  17688. if ( !_this.noZoom ) {
  17689. _this.zoomCamera();
  17690. }
  17691. if ( !_this.noPan ) {
  17692. _this.panCamera();
  17693. }
  17694. _this.object.position.add( _this.target, _eye );
  17695. _this.checkDistances();
  17696. _this.object.lookAt( _this.target );
  17697. if ( lastPosition.distanceToSquared( _this.object.position ) > 0 ) {
  17698. _this.dispatchEvent( changeEvent );
  17699. lastPosition.copy( _this.object.position );
  17700. }
  17701. };
  17702. // listeners
  17703. function keydown( event ) {
  17704. if ( ! _this.enabled ) return;
  17705. //event.preventDefault();
  17706. if ( _state !== STATE.NONE ) {
  17707. return;
  17708. } else if ( event.keyCode === _this.keys[ STATE.ROTATE ] && !_this.noRotate ) {
  17709. _state = STATE.ROTATE;
  17710. } else if ( event.keyCode === _this.keys[ STATE.ZOOM ] && !_this.noZoom ) {
  17711. _state = STATE.ZOOM;
  17712. } else if ( event.keyCode === _this.keys[ STATE.PAN ] && !_this.noPan ) {
  17713. _state = STATE.PAN;
  17714. }
  17715. if ( _state !== STATE.NONE ) {
  17716. _keyPressed = true;
  17717. }
  17718. }
  17719. function keyup( event ) {
  17720. if ( ! _this.enabled ) return;
  17721. if ( _state !== STATE.NONE ) {
  17722. _state = STATE.NONE;
  17723. }
  17724. }
  17725. function mousedown( event ) {
  17726. if ( ! _this.enabled ) return;
  17727. event.preventDefault();
  17728. event.stopPropagation();
  17729. if ( _state === STATE.NONE ) {
  17730. _state = event.button;
  17731. if ( _state === STATE.ROTATE && !_this.noRotate ) {
  17732. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  17733. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  17734. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17735. } else if ( !this.noPan ) {
  17736. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17737. }
  17738. }
  17739. }
  17740. function mousemove( event ) {
  17741. if ( ! _this.enabled ) return;
  17742. if ( _keyPressed ) {
  17743. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  17744. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17745. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17746. _keyPressed = false;
  17747. }
  17748. if ( _state === STATE.NONE ) {
  17749. return;
  17750. } else if ( _state === STATE.ROTATE && !_this.noRotate ) {
  17751. _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  17752. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  17753. _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17754. } else if ( _state === STATE.PAN && !_this.noPan ) {
  17755. _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  17756. }
  17757. }
  17758. function mouseup( event ) {
  17759. if ( ! _this.enabled ) return;
  17760. event.preventDefault();
  17761. event.stopPropagation();
  17762. _state = STATE.NONE;
  17763. }
  17764. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  17765. this.domElement.addEventListener( 'mousemove', mousemove, false );
  17766. this.domElement.addEventListener( 'mousedown', mousedown, false );
  17767. this.domElement.addEventListener( 'mouseup', mouseup, false );
  17768. // this.domElement.addEventListener( 'DOMMouseScroll', mousewheel, false );
  17769. // this.domElement.addEventListener( 'mousewheel', mousewheel, false );
  17770. window.addEventListener( 'keydown', keydown, false );
  17771. window.addEventListener( 'keyup', keyup, false );
  17772. this.handleResize();
  17773. };
  17774. /**
  17775. * @author qiao / https://github.com/qiao
  17776. * @author mrdoob / http://mrdoob.com
  17777. * @author alteredq / http://alteredqualia.com/
  17778. */
  17779. THREE.OrbitControls = function ( object, domElement ) {
  17780. THREE.EventTarget.call( this );
  17781. this.object = object;
  17782. this.domElement = ( domElement !== undefined ) ? domElement : document;
  17783. // API
  17784. this.center = new THREE.Vector3();
  17785. this.userZoom = true;
  17786. this.userZoomSpeed = 1.0;
  17787. this.userRotate = true;
  17788. this.userRotateSpeed = 1.0;
  17789. this.autoRotate = false;
  17790. this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
  17791. // internals
  17792. var scope = this;
  17793. var EPS = 0.000001;
  17794. var PIXELS_PER_ROUND = 1800;
  17795. var rotateStart = new THREE.Vector2();
  17796. var rotateEnd = new THREE.Vector2();
  17797. var rotateDelta = new THREE.Vector2();
  17798. var zoomStart = new THREE.Vector2();
  17799. var zoomEnd = new THREE.Vector2();
  17800. var zoomDelta = new THREE.Vector2();
  17801. var phiDelta = 0;
  17802. var thetaDelta = 0;
  17803. var scale = 1;
  17804. var lastPosition = new THREE.Vector3();
  17805. var STATE = { NONE : -1, ROTATE : 0, ZOOM : 1 };
  17806. var state = STATE.NONE;
  17807. // events
  17808. var changeEvent = { type: 'change' };
  17809. this.rotateLeft = function ( angle ) {
  17810. if ( angle === undefined ) {
  17811. angle = getAutoRotationAngle();
  17812. }
  17813. thetaDelta -= angle;
  17814. };
  17815. this.rotateRight = function ( angle ) {
  17816. if ( angle === undefined ) {
  17817. angle = getAutoRotationAngle();
  17818. }
  17819. thetaDelta += angle;
  17820. };
  17821. this.rotateUp = function ( angle ) {
  17822. if ( angle === undefined ) {
  17823. angle = getAutoRotationAngle();
  17824. }
  17825. phiDelta -= angle;
  17826. };
  17827. this.rotateDown = function ( angle ) {
  17828. if ( angle === undefined ) {
  17829. angle = getAutoRotationAngle();
  17830. }
  17831. phiDelta += angle;
  17832. };
  17833. this.zoomIn = function ( zoomScale ) {
  17834. if ( zoomScale === undefined ) {
  17835. zoomScale = getZoomScale();
  17836. }
  17837. scale /= zoomScale;
  17838. };
  17839. this.zoomOut = function ( zoomScale ) {
  17840. if ( zoomScale === undefined ) {
  17841. zoomScale = getZoomScale();
  17842. }
  17843. scale *= zoomScale;
  17844. };
  17845. this.update = function () {
  17846. var position = this.object.position;
  17847. var offset = position.clone().subSelf( this.center )
  17848. // angle from z-axis around y-axis
  17849. var theta = Math.atan2( offset.x, offset.z );
  17850. // angle from y-axis
  17851. var phi = Math.atan2( Math.sqrt( offset.x * offset.x + offset.z * offset.z ), offset.y );
  17852. if ( this.autoRotate ) {
  17853. this.rotateLeft( getAutoRotationAngle() );
  17854. }
  17855. theta += thetaDelta;
  17856. phi += phiDelta;
  17857. // restrict phi to be betwee EPS and PI-EPS
  17858. phi = Math.max( EPS, Math.min( Math.PI - EPS, phi ) );
  17859. var radius = offset.length();
  17860. offset.x = radius * Math.sin( phi ) * Math.sin( theta );
  17861. offset.y = radius * Math.cos( phi );
  17862. offset.z = radius * Math.sin( phi ) * Math.cos( theta );
  17863. offset.multiplyScalar( scale );
  17864. position.copy( this.center ).addSelf( offset );
  17865. this.object.lookAt( this.center );
  17866. thetaDelta = 0;
  17867. phiDelta = 0;
  17868. scale = 1;
  17869. if ( lastPosition.distanceTo( this.object.position ) > 0 ) {
  17870. this.dispatchEvent( changeEvent );
  17871. lastPosition.copy( this.object.position );
  17872. }
  17873. };
  17874. function getAutoRotationAngle() {
  17875. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  17876. }
  17877. function getZoomScale() {
  17878. return Math.pow( 0.95, scope.userZoomSpeed );
  17879. }
  17880. function onMouseDown( event ) {
  17881. if ( !scope.userRotate ) return;
  17882. event.preventDefault();
  17883. if ( event.button === 0 || event.button === 2 ) {
  17884. state = STATE.ROTATE;
  17885. rotateStart.set( event.clientX, event.clientY );
  17886. } else if ( event.button === 1 ) {
  17887. state = STATE.ZOOM;
  17888. zoomStart.set( event.clientX, event.clientY );
  17889. }
  17890. document.addEventListener( 'mousemove', onMouseMove, false );
  17891. document.addEventListener( 'mouseup', onMouseUp, false );
  17892. }
  17893. function onMouseMove( event ) {
  17894. event.preventDefault();
  17895. if ( state === STATE.ROTATE ) {
  17896. rotateEnd.set( event.clientX, event.clientY );
  17897. rotateDelta.sub( rotateEnd, rotateStart );
  17898. scope.rotateLeft( 2 * Math.PI * rotateDelta.x / PIXELS_PER_ROUND * scope.userRotateSpeed );
  17899. scope.rotateUp( 2 * Math.PI * rotateDelta.y / PIXELS_PER_ROUND * scope.userRotateSpeed );
  17900. rotateStart.copy( rotateEnd );
  17901. } else if ( state === STATE.ZOOM ) {
  17902. zoomEnd.set( event.clientX, event.clientY );
  17903. zoomDelta.sub( zoomEnd, zoomStart );
  17904. if ( zoomDelta.y > 0 ) {
  17905. scope.zoomIn();
  17906. } else {
  17907. scope.zoomOut();
  17908. }
  17909. zoomStart.copy( zoomEnd );
  17910. }
  17911. }
  17912. function onMouseUp( event ) {
  17913. if ( ! scope.userRotate ) return;
  17914. document.removeEventListener( 'mousemove', onMouseMove, false );
  17915. document.removeEventListener( 'mouseup', onMouseUp, false );
  17916. state = STATE.NONE;
  17917. }
  17918. function onMouseWheel( event ) {
  17919. if ( ! scope.userZoom ) return;
  17920. if ( event.wheelDelta > 0 ) {
  17921. scope.zoomOut();
  17922. } else {
  17923. scope.zoomIn();
  17924. }
  17925. }
  17926. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  17927. this.domElement.addEventListener( 'mousedown', onMouseDown, false );
  17928. this.domElement.addEventListener( 'mousewheel', onMouseWheel, false );
  17929. };
  17930. /**
  17931. * @author hughes
  17932. */
  17933. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  17934. THREE.Geometry.call( this );
  17935. radius = radius || 50;
  17936. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  17937. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  17938. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  17939. var i, uvs = [],
  17940. center = new THREE.Vector3(), centerUV = new THREE.UV( 0.5, 0.5 );
  17941. this.vertices.push(center);
  17942. uvs.push( centerUV );
  17943. for ( i = 0; i <= segments; i ++ ) {
  17944. var vertex = new THREE.Vector3();
  17945. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  17946. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  17947. this.vertices.push( vertex );
  17948. uvs.push( new THREE.UV( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  17949. }
  17950. var n = new THREE.Vector3( 0, 0, -1 );
  17951. for ( i = 1; i <= segments; i ++ ) {
  17952. var v1 = i;
  17953. var v2 = i + 1 ;
  17954. var v3 = 0;
  17955. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  17956. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  17957. }
  17958. this.computeCentroids();
  17959. this.computeFaceNormals();
  17960. this.boundingSphere = { radius: radius };
  17961. };
  17962. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17963. /**
  17964. * @author mrdoob / http://mrdoob.com/
  17965. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  17966. */
  17967. THREE.CubeGeometry = function ( width, height, depth, segmentsWidth, segmentsHeight, segmentsDepth, materials, sides ) {
  17968. THREE.Geometry.call( this );
  17969. var scope = this,
  17970. width_half = width / 2,
  17971. height_half = height / 2,
  17972. depth_half = depth / 2;
  17973. var mpx, mpy, mpz, mnx, mny, mnz;
  17974. if ( materials !== undefined ) {
  17975. if ( materials instanceof Array ) {
  17976. this.materials = materials;
  17977. } else {
  17978. this.materials = [];
  17979. for ( var i = 0; i < 6; i ++ ) {
  17980. this.materials.push( materials );
  17981. }
  17982. }
  17983. mpx = 0; mnx = 1; mpy = 2; mny = 3; mpz = 4; mnz = 5;
  17984. } else {
  17985. this.materials = [];
  17986. }
  17987. this.sides = { px: true, nx: true, py: true, ny: true, pz: true, nz: true };
  17988. if ( sides != undefined ) {
  17989. for ( var s in sides ) {
  17990. if ( this.sides[ s ] !== undefined ) {
  17991. this.sides[ s ] = sides[ s ];
  17992. }
  17993. }
  17994. }
  17995. this.sides.px && buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, mpx ); // px
  17996. this.sides.nx && buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, mnx ); // nx
  17997. this.sides.py && buildPlane( 'x', 'z', 1, 1, width, depth, height_half, mpy ); // py
  17998. this.sides.ny && buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, mny ); // ny
  17999. this.sides.pz && buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, mpz ); // pz
  18000. this.sides.nz && buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, mnz ); // nz
  18001. function buildPlane( u, v, udir, vdir, width, height, depth, material ) {
  18002. var w, ix, iy,
  18003. gridX = segmentsWidth || 1,
  18004. gridY = segmentsHeight || 1,
  18005. width_half = width / 2,
  18006. height_half = height / 2,
  18007. offset = scope.vertices.length;
  18008. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18009. w = 'z';
  18010. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18011. w = 'y';
  18012. gridY = segmentsDepth || 1;
  18013. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18014. w = 'x';
  18015. gridX = segmentsDepth || 1;
  18016. }
  18017. var gridX1 = gridX + 1,
  18018. gridY1 = gridY + 1,
  18019. segment_width = width / gridX,
  18020. segment_height = height / gridY,
  18021. normal = new THREE.Vector3();
  18022. normal[ w ] = depth > 0 ? 1 : - 1;
  18023. for ( iy = 0; iy < gridY1; iy ++ ) {
  18024. for ( ix = 0; ix < gridX1; ix ++ ) {
  18025. var vector = new THREE.Vector3();
  18026. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18027. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18028. vector[ w ] = depth;
  18029. scope.vertices.push( vector );
  18030. }
  18031. }
  18032. for ( iy = 0; iy < gridY; iy++ ) {
  18033. for ( ix = 0; ix < gridX; ix++ ) {
  18034. var a = ix + gridX1 * iy;
  18035. var b = ix + gridX1 * ( iy + 1 );
  18036. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18037. var d = ( ix + 1 ) + gridX1 * iy;
  18038. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  18039. face.normal.copy( normal );
  18040. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18041. face.materialIndex = material;
  18042. scope.faces.push( face );
  18043. scope.faceVertexUvs[ 0 ].push( [
  18044. new THREE.UV( ix / gridX, 1 - iy / gridY ),
  18045. new THREE.UV( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  18046. new THREE.UV( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  18047. new THREE.UV( ( ix + 1 ) / gridX, 1 - iy / gridY )
  18048. ] );
  18049. }
  18050. }
  18051. }
  18052. this.computeCentroids();
  18053. this.mergeVertices();
  18054. };
  18055. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18056. /**
  18057. * @author mrdoob / http://mrdoob.com/
  18058. */
  18059. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, segmentsRadius, segmentsHeight, openEnded ) {
  18060. THREE.Geometry.call( this );
  18061. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18062. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18063. height = height !== undefined ? height : 100;
  18064. var heightHalf = height / 2;
  18065. var segmentsX = segmentsRadius || 8;
  18066. var segmentsY = segmentsHeight || 1;
  18067. var x, y, vertices = [], uvs = [];
  18068. for ( y = 0; y <= segmentsY; y ++ ) {
  18069. var verticesRow = [];
  18070. var uvsRow = [];
  18071. var v = y / segmentsY;
  18072. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18073. for ( x = 0; x <= segmentsX; x ++ ) {
  18074. var u = x / segmentsX;
  18075. var vertex = new THREE.Vector3();
  18076. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18077. vertex.y = - v * height + heightHalf;
  18078. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18079. this.vertices.push( vertex );
  18080. verticesRow.push( this.vertices.length - 1 );
  18081. uvsRow.push( new THREE.UV( u, 1 - v ) );
  18082. }
  18083. vertices.push( verticesRow );
  18084. uvs.push( uvsRow );
  18085. }
  18086. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18087. var na, nb;
  18088. for ( x = 0; x < segmentsX; x ++ ) {
  18089. if ( radiusTop !== 0 ) {
  18090. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18091. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18092. } else {
  18093. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18094. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18095. }
  18096. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18097. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18098. for ( y = 0; y < segmentsY; y ++ ) {
  18099. var v1 = vertices[ y ][ x ];
  18100. var v2 = vertices[ y + 1 ][ x ];
  18101. var v3 = vertices[ y + 1 ][ x + 1 ];
  18102. var v4 = vertices[ y ][ x + 1 ];
  18103. var n1 = na.clone();
  18104. var n2 = na.clone();
  18105. var n3 = nb.clone();
  18106. var n4 = nb.clone();
  18107. var uv1 = uvs[ y ][ x ].clone();
  18108. var uv2 = uvs[ y + 1 ][ x ].clone();
  18109. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18110. var uv4 = uvs[ y ][ x + 1 ].clone();
  18111. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18112. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18113. }
  18114. }
  18115. // top cap
  18116. if ( !openEnded && radiusTop > 0 ) {
  18117. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18118. for ( x = 0; x < segmentsX; x ++ ) {
  18119. var v1 = vertices[ 0 ][ x ];
  18120. var v2 = vertices[ 0 ][ x + 1 ];
  18121. var v3 = this.vertices.length - 1;
  18122. var n1 = new THREE.Vector3( 0, 1, 0 );
  18123. var n2 = new THREE.Vector3( 0, 1, 0 );
  18124. var n3 = new THREE.Vector3( 0, 1, 0 );
  18125. var uv1 = uvs[ 0 ][ x ].clone();
  18126. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18127. var uv3 = new THREE.UV( uv2.u, 0 );
  18128. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18129. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18130. }
  18131. }
  18132. // bottom cap
  18133. if ( !openEnded && radiusBottom > 0 ) {
  18134. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18135. for ( x = 0; x < segmentsX; x ++ ) {
  18136. var v1 = vertices[ y ][ x + 1 ];
  18137. var v2 = vertices[ y ][ x ];
  18138. var v3 = this.vertices.length - 1;
  18139. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18140. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18141. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18142. var uv1 = uvs[ y ][ x + 1 ].clone();
  18143. var uv2 = uvs[ y ][ x ].clone();
  18144. var uv3 = new THREE.UV( uv2.u, 1 );
  18145. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18146. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18147. }
  18148. }
  18149. this.computeCentroids();
  18150. this.computeFaceNormals();
  18151. }
  18152. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18153. /**
  18154. * @author zz85 / http://www.lab4games.net/zz85/blog
  18155. *
  18156. * Creates extruded geometry from a path shape.
  18157. *
  18158. * parameters = {
  18159. *
  18160. * size: <float>, // size of the text
  18161. * height: <float>, // thickness to extrude text
  18162. * curveSegments: <int>, // number of points on the curves
  18163. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18164. * amount: <int>, // Amount
  18165. *
  18166. * bevelEnabled: <bool>, // turn on bevel
  18167. * bevelThickness: <float>, // how deep into text bevel goes
  18168. * bevelSize: <float>, // how far from text outline is bevel
  18169. * bevelSegments: <int>, // number of bevel layers
  18170. *
  18171. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18172. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18173. *
  18174. * material: <int> // material index for front and back faces
  18175. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18176. * uvGenerator: <Object> // object that provides UV generator functions
  18177. *
  18178. * }
  18179. **/
  18180. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18181. if ( typeof( shapes ) === "undefined" ) {
  18182. shapes = [];
  18183. return;
  18184. }
  18185. THREE.Geometry.call( this );
  18186. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18187. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18188. this.addShapeList( shapes, options );
  18189. this.computeCentroids();
  18190. this.computeFaceNormals();
  18191. // can't really use automatic vertex normals
  18192. // as then front and back sides get smoothed too
  18193. // should do separate smoothing just for sides
  18194. //this.computeVertexNormals();
  18195. //console.log( "took", ( Date.now() - startTime ) );
  18196. };
  18197. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18198. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18199. var sl = shapes.length;
  18200. for ( var s = 0; s < sl; s ++ ) {
  18201. var shape = shapes[ s ];
  18202. this.addShape( shape, options );
  18203. }
  18204. };
  18205. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18206. var amount = options.amount !== undefined ? options.amount : 100;
  18207. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18208. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18209. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18210. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18211. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18212. var steps = options.steps !== undefined ? options.steps : 1;
  18213. var extrudePath = options.extrudePath;
  18214. var extrudePts, extrudeByPath = false;
  18215. var material = options.material;
  18216. var extrudeMaterial = options.extrudeMaterial;
  18217. // Use default WorldUVGenerator if no UV generators are specified.
  18218. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18219. var shapebb = this.shapebb;
  18220. //shapebb = shape.getBoundingBox();
  18221. var splineTube, binormal, normal, position2;
  18222. if ( extrudePath ) {
  18223. extrudePts = extrudePath.getSpacedPoints( steps );
  18224. extrudeByPath = true;
  18225. bevelEnabled = false; // bevels not supported for path extrusion
  18226. // SETUP TNB variables
  18227. // Reuse TNB from TubeGeomtry for now.
  18228. // TODO1 - have a .isClosed in spline?
  18229. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18230. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18231. binormal = new THREE.Vector3();
  18232. normal = new THREE.Vector3();
  18233. position2 = new THREE.Vector3();
  18234. }
  18235. // Safeguards if bevels are not enabled
  18236. if ( ! bevelEnabled ) {
  18237. bevelSegments = 0;
  18238. bevelThickness = 0;
  18239. bevelSize = 0;
  18240. }
  18241. // Variables initalization
  18242. var ahole, h, hl; // looping of holes
  18243. var scope = this;
  18244. var bevelPoints = [];
  18245. var shapesOffset = this.vertices.length;
  18246. var shapePoints = shape.extractPoints();
  18247. var vertices = shapePoints.shape;
  18248. var holes = shapePoints.holes;
  18249. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18250. if ( reverse ) {
  18251. vertices = vertices.reverse();
  18252. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18253. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18254. ahole = holes[ h ];
  18255. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18256. holes[ h ] = ahole.reverse();
  18257. }
  18258. }
  18259. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18260. }
  18261. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18262. /* Vertices */
  18263. var contour = vertices; // vertices has all points but contour has only points of circumference
  18264. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18265. ahole = holes[ h ];
  18266. vertices = vertices.concat( ahole );
  18267. }
  18268. function scalePt2 ( pt, vec, size ) {
  18269. if ( !vec ) console.log( "die" );
  18270. return vec.clone().multiplyScalar( size ).addSelf( pt );
  18271. }
  18272. var b, bs, t, z,
  18273. vert, vlen = vertices.length,
  18274. face, flen = faces.length,
  18275. cont, clen = contour.length;
  18276. // Find directions for point movement
  18277. var RAD_TO_DEGREES = 180 / Math.PI;
  18278. function getBevelVec( pt_i, pt_j, pt_k ) {
  18279. // Algorithm 2
  18280. return getBevelVec2( pt_i, pt_j, pt_k );
  18281. }
  18282. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18283. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18284. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18285. if ( anglea > angleb ) {
  18286. angleb += Math.PI * 2;
  18287. }
  18288. var anglec = ( anglea + angleb ) / 2;
  18289. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18290. var x = - Math.cos( anglec );
  18291. var y = - Math.sin( anglec );
  18292. var vec = new THREE.Vector2( x, y ); //.normalize();
  18293. return vec;
  18294. }
  18295. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18296. var a = THREE.ExtrudeGeometry.__v1,
  18297. b = THREE.ExtrudeGeometry.__v2,
  18298. v_hat = THREE.ExtrudeGeometry.__v3,
  18299. w_hat = THREE.ExtrudeGeometry.__v4,
  18300. p = THREE.ExtrudeGeometry.__v5,
  18301. q = THREE.ExtrudeGeometry.__v6,
  18302. v, w,
  18303. v_dot_w_hat, q_sub_p_dot_w_hat,
  18304. s, intersection;
  18305. // good reading for line-line intersection
  18306. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18307. // define a as vector j->i
  18308. // define b as vectot k->i
  18309. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18310. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18311. // get unit vectors
  18312. v = a.normalize();
  18313. w = b.normalize();
  18314. // normals from pt i
  18315. v_hat.set( -v.y, v.x );
  18316. w_hat.set( w.y, -w.x );
  18317. // pts from i
  18318. p.copy( pt_i ).addSelf( v_hat );
  18319. q.copy( pt_i ).addSelf( w_hat );
  18320. if ( p.equals( q ) ) {
  18321. //console.log("Warning: lines are straight");
  18322. return w_hat.clone();
  18323. }
  18324. // Points from j, k. helps prevents points cross overover most of the time
  18325. p.copy( pt_j ).addSelf( v_hat );
  18326. q.copy( pt_k ).addSelf( w_hat );
  18327. v_dot_w_hat = v.dot( w_hat );
  18328. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  18329. // We should not reach these conditions
  18330. if ( v_dot_w_hat === 0 ) {
  18331. console.log( "Either infinite or no solutions!" );
  18332. if ( q_sub_p_dot_w_hat === 0 ) {
  18333. console.log( "Its finite solutions." );
  18334. } else {
  18335. console.log( "Too bad, no solutions." );
  18336. }
  18337. }
  18338. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18339. if ( s < 0 ) {
  18340. // in case of emergecy, revert to algorithm 1.
  18341. return getBevelVec1( pt_i, pt_j, pt_k );
  18342. }
  18343. intersection = v.multiplyScalar( s ).addSelf( p );
  18344. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18345. }
  18346. var contourMovements = [];
  18347. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18348. if ( j === il ) j = 0;
  18349. if ( k === il ) k = 0;
  18350. // (j)---(i)---(k)
  18351. // console.log('i,j,k', i, j , k)
  18352. var pt_i = contour[ i ];
  18353. var pt_j = contour[ j ];
  18354. var pt_k = contour[ k ];
  18355. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18356. }
  18357. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18358. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18359. ahole = holes[ h ];
  18360. oneHoleMovements = [];
  18361. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18362. if ( j === il ) j = 0;
  18363. if ( k === il ) k = 0;
  18364. // (j)---(i)---(k)
  18365. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18366. }
  18367. holesMovements.push( oneHoleMovements );
  18368. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18369. }
  18370. // Loop bevelSegments, 1 for the front, 1 for the back
  18371. for ( b = 0; b < bevelSegments; b ++ ) {
  18372. //for ( b = bevelSegments; b > 0; b -- ) {
  18373. t = b / bevelSegments;
  18374. z = bevelThickness * ( 1 - t );
  18375. //z = bevelThickness * t;
  18376. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18377. //bs = bevelSize * t ; // linear
  18378. // contract shape
  18379. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18380. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18381. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18382. v( vert.x, vert.y, - z );
  18383. }
  18384. // expand holes
  18385. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18386. ahole = holes[ h ];
  18387. oneHoleMovements = holesMovements[ h ];
  18388. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18389. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18390. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18391. v( vert.x, vert.y, -z );
  18392. }
  18393. }
  18394. }
  18395. bs = bevelSize;
  18396. // Back facing vertices
  18397. for ( i = 0; i < vlen; i ++ ) {
  18398. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18399. if ( !extrudeByPath ) {
  18400. v( vert.x, vert.y, 0 );
  18401. } else {
  18402. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18403. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18404. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18405. position2.copy( extrudePts[0] ).addSelf(normal).addSelf(binormal);
  18406. v( position2.x, position2.y, position2.z );
  18407. }
  18408. }
  18409. // Add stepped vertices...
  18410. // Including front facing vertices
  18411. var s;
  18412. for ( s = 1; s <= steps; s ++ ) {
  18413. for ( i = 0; i < vlen; i ++ ) {
  18414. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18415. if ( !extrudeByPath ) {
  18416. v( vert.x, vert.y, amount / steps * s );
  18417. } else {
  18418. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18419. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18420. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18421. position2.copy( extrudePts[s] ).addSelf( normal ).addSelf( binormal );
  18422. v( position2.x, position2.y, position2.z );
  18423. }
  18424. }
  18425. }
  18426. // Add bevel segments planes
  18427. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18428. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18429. t = b / bevelSegments;
  18430. z = bevelThickness * ( 1 - t );
  18431. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18432. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18433. // contract shape
  18434. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18435. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18436. v( vert.x, vert.y, amount + z );
  18437. }
  18438. // expand holes
  18439. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18440. ahole = holes[ h ];
  18441. oneHoleMovements = holesMovements[ h ];
  18442. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18443. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18444. if ( !extrudeByPath ) {
  18445. v( vert.x, vert.y, amount + z );
  18446. } else {
  18447. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18448. }
  18449. }
  18450. }
  18451. }
  18452. /* Faces */
  18453. // Top and bottom faces
  18454. buildLidFaces();
  18455. // Sides faces
  18456. buildSideFaces();
  18457. ///// Internal functions
  18458. function buildLidFaces() {
  18459. if ( bevelEnabled ) {
  18460. var layer = 0 ; // steps + 1
  18461. var offset = vlen * layer;
  18462. // Bottom faces
  18463. for ( i = 0; i < flen; i ++ ) {
  18464. face = faces[ i ];
  18465. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  18466. }
  18467. layer = steps + bevelSegments * 2;
  18468. offset = vlen * layer;
  18469. // Top faces
  18470. for ( i = 0; i < flen; i ++ ) {
  18471. face = faces[ i ];
  18472. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  18473. }
  18474. } else {
  18475. // Bottom faces
  18476. for ( i = 0; i < flen; i++ ) {
  18477. face = faces[ i ];
  18478. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  18479. }
  18480. // Top faces
  18481. for ( i = 0; i < flen; i ++ ) {
  18482. face = faces[ i ];
  18483. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  18484. }
  18485. }
  18486. }
  18487. // Create faces for the z-sides of the shape
  18488. function buildSideFaces() {
  18489. var layeroffset = 0;
  18490. sidewalls( contour, layeroffset );
  18491. layeroffset += contour.length;
  18492. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18493. ahole = holes[ h ];
  18494. sidewalls( ahole, layeroffset );
  18495. //, true
  18496. layeroffset += ahole.length;
  18497. }
  18498. }
  18499. function sidewalls( contour, layeroffset ) {
  18500. var j, k;
  18501. i = contour.length;
  18502. while ( --i >= 0 ) {
  18503. j = i;
  18504. k = i - 1;
  18505. if ( k < 0 ) k = contour.length - 1;
  18506. //console.log('b', i,j, i-1, k,vertices.length);
  18507. var s = 0, sl = steps + bevelSegments * 2;
  18508. for ( s = 0; s < sl; s ++ ) {
  18509. var slen1 = vlen * s;
  18510. var slen2 = vlen * ( s + 1 );
  18511. var a = layeroffset + j + slen1,
  18512. b = layeroffset + k + slen1,
  18513. c = layeroffset + k + slen2,
  18514. d = layeroffset + j + slen2;
  18515. f4( a, b, c, d, contour, s, sl, j, k );
  18516. }
  18517. }
  18518. }
  18519. function v( x, y, z ) {
  18520. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18521. }
  18522. function f3( a, b, c, isBottom ) {
  18523. a += shapesOffset;
  18524. b += shapesOffset;
  18525. c += shapesOffset;
  18526. // normal, color, material
  18527. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18528. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  18529. scope.faceVertexUvs[ 0 ].push( uvs );
  18530. }
  18531. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18532. a += shapesOffset;
  18533. b += shapesOffset;
  18534. c += shapesOffset;
  18535. d += shapesOffset;
  18536. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  18537. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  18538. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  18539. scope.faceVertexUvs[ 0 ].push( uvs );
  18540. }
  18541. };
  18542. THREE.ExtrudeGeometry.WorldUVGenerator = {
  18543. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18544. var ax = geometry.vertices[ indexA ].x,
  18545. ay = geometry.vertices[ indexA ].y,
  18546. bx = geometry.vertices[ indexB ].x,
  18547. by = geometry.vertices[ indexB ].y,
  18548. cx = geometry.vertices[ indexC ].x,
  18549. cy = geometry.vertices[ indexC ].y;
  18550. return [
  18551. new THREE.UV( ax, ay ),
  18552. new THREE.UV( bx, by ),
  18553. new THREE.UV( cx, cy )
  18554. ];
  18555. },
  18556. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18557. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  18558. },
  18559. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  18560. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  18561. contourIndex1, contourIndex2 ) {
  18562. var ax = geometry.vertices[ indexA ].x,
  18563. ay = geometry.vertices[ indexA ].y,
  18564. az = geometry.vertices[ indexA ].z,
  18565. bx = geometry.vertices[ indexB ].x,
  18566. by = geometry.vertices[ indexB ].y,
  18567. bz = geometry.vertices[ indexB ].z,
  18568. cx = geometry.vertices[ indexC ].x,
  18569. cy = geometry.vertices[ indexC ].y,
  18570. cz = geometry.vertices[ indexC ].z,
  18571. dx = geometry.vertices[ indexD ].x,
  18572. dy = geometry.vertices[ indexD ].y,
  18573. dz = geometry.vertices[ indexD ].z;
  18574. if ( Math.abs( ay - by ) < 0.01 ) {
  18575. return [
  18576. new THREE.UV( ax, 1 - az ),
  18577. new THREE.UV( bx, 1 - bz ),
  18578. new THREE.UV( cx, 1 - cz ),
  18579. new THREE.UV( dx, 1 - dz )
  18580. ];
  18581. } else {
  18582. return [
  18583. new THREE.UV( ay, 1 - az ),
  18584. new THREE.UV( by, 1 - bz ),
  18585. new THREE.UV( cy, 1 - cz ),
  18586. new THREE.UV( dy, 1 - dz )
  18587. ];
  18588. }
  18589. }
  18590. };
  18591. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  18592. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  18593. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  18594. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  18595. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  18596. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  18597. /**
  18598. * @author astrodud / http://astrodud.isgreat.org/
  18599. * @author zz85 / https://github.com/zz85
  18600. */
  18601. THREE.LatheGeometry = function ( points, steps, angle ) {
  18602. THREE.Geometry.call( this );
  18603. var _steps = steps || 12;
  18604. var _angle = angle || 2 * Math.PI;
  18605. var _newV = [];
  18606. var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
  18607. for ( var j = 0; j < points.length; j ++ ) {
  18608. _newV[ j ] = points[ j ].clone();
  18609. this.vertices.push( _newV[ j ] );
  18610. }
  18611. var i, il = _steps + 1;
  18612. for ( i = 0; i < il; i ++ ) {
  18613. for ( var j = 0; j < _newV.length; j ++ ) {
  18614. _newV[ j ] = _matrix.multiplyVector3( _newV[ j ].clone() );
  18615. this.vertices.push( _newV[ j ] );
  18616. }
  18617. }
  18618. for ( i = 0; i < _steps; i ++ ) {
  18619. for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
  18620. var a = i * kl + k;
  18621. var b = ( ( i + 1 ) % il ) * kl + k;
  18622. var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
  18623. var d = i * kl + ( k + 1 ) % kl;
  18624. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18625. this.faceVertexUvs[ 0 ].push( [
  18626. new THREE.UV( 1 - i / _steps, k / kl ),
  18627. new THREE.UV( 1 - ( i + 1 ) / _steps, k / kl ),
  18628. new THREE.UV( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
  18629. new THREE.UV( 1 - i / _steps, ( k + 1 ) / kl )
  18630. ] );
  18631. }
  18632. }
  18633. this.computeCentroids();
  18634. this.computeFaceNormals();
  18635. this.computeVertexNormals();
  18636. };
  18637. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18638. /**
  18639. * @author mrdoob / http://mrdoob.com/
  18640. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  18641. */
  18642. THREE.PlaneGeometry = function ( width, height, segmentsWidth, segmentsheight ) {
  18643. THREE.Geometry.call( this );
  18644. var ix, iz,
  18645. width_half = width / 2,
  18646. height_half = height / 2,
  18647. gridX = segmentsWidth || 1,
  18648. gridZ = segmentsheight || 1,
  18649. gridX1 = gridX + 1,
  18650. gridZ1 = gridZ + 1,
  18651. segment_width = width / gridX,
  18652. segment_height = height / gridZ,
  18653. normal = new THREE.Vector3( 0, 0, 1 );
  18654. for ( iz = 0; iz < gridZ1; iz ++ ) {
  18655. for ( ix = 0; ix < gridX1; ix ++ ) {
  18656. var x = ix * segment_width - width_half;
  18657. var y = iz * segment_height - height_half;
  18658. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  18659. }
  18660. }
  18661. for ( iz = 0; iz < gridZ; iz ++ ) {
  18662. for ( ix = 0; ix < gridX; ix ++ ) {
  18663. var a = ix + gridX1 * iz;
  18664. var b = ix + gridX1 * ( iz + 1 );
  18665. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  18666. var d = ( ix + 1 ) + gridX1 * iz;
  18667. var face = new THREE.Face4( a, b, c, d );
  18668. face.normal.copy( normal );
  18669. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18670. this.faces.push( face );
  18671. this.faceVertexUvs[ 0 ].push( [
  18672. new THREE.UV( ix / gridX, 1 - iz / gridZ ),
  18673. new THREE.UV( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  18674. new THREE.UV( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  18675. new THREE.UV( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  18676. ] );
  18677. }
  18678. }
  18679. this.computeCentroids();
  18680. };
  18681. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18682. /**
  18683. * @author mrdoob / http://mrdoob.com/
  18684. */
  18685. THREE.SphereGeometry = function ( radius, segmentsWidth, segmentsHeight, phiStart, phiLength, thetaStart, thetaLength ) {
  18686. THREE.Geometry.call( this );
  18687. radius = radius || 50;
  18688. phiStart = phiStart !== undefined ? phiStart : 0;
  18689. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  18690. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18691. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  18692. var segmentsX = Math.max( 3, Math.floor( segmentsWidth ) || 8 );
  18693. var segmentsY = Math.max( 2, Math.floor( segmentsHeight ) || 6 );
  18694. var x, y, vertices = [], uvs = [];
  18695. for ( y = 0; y <= segmentsY; y ++ ) {
  18696. var verticesRow = [];
  18697. var uvsRow = [];
  18698. for ( x = 0; x <= segmentsX; x ++ ) {
  18699. var u = x / segmentsX;
  18700. var v = y / segmentsY;
  18701. var vertex = new THREE.Vector3();
  18702. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18703. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  18704. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18705. this.vertices.push( vertex );
  18706. verticesRow.push( this.vertices.length - 1 );
  18707. uvsRow.push( new THREE.UV( u, 1 - v ) );
  18708. }
  18709. vertices.push( verticesRow );
  18710. uvs.push( uvsRow );
  18711. }
  18712. for ( y = 0; y < segmentsY; y ++ ) {
  18713. for ( x = 0; x < segmentsX; x ++ ) {
  18714. var v1 = vertices[ y ][ x + 1 ];
  18715. var v2 = vertices[ y ][ x ];
  18716. var v3 = vertices[ y + 1 ][ x ];
  18717. var v4 = vertices[ y + 1 ][ x + 1 ];
  18718. var n1 = this.vertices[ v1 ].clone().normalize();
  18719. var n2 = this.vertices[ v2 ].clone().normalize();
  18720. var n3 = this.vertices[ v3 ].clone().normalize();
  18721. var n4 = this.vertices[ v4 ].clone().normalize();
  18722. var uv1 = uvs[ y ][ x + 1 ].clone();
  18723. var uv2 = uvs[ y ][ x ].clone();
  18724. var uv3 = uvs[ y + 1 ][ x ].clone();
  18725. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  18726. if ( Math.abs( this.vertices[ v1 ].y ) == radius ) {
  18727. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  18728. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  18729. } else if ( Math.abs( this.vertices[ v3 ].y ) == radius ) {
  18730. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18731. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18732. } else {
  18733. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18734. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18735. }
  18736. }
  18737. }
  18738. this.computeCentroids();
  18739. this.computeFaceNormals();
  18740. this.boundingSphere = { radius: radius };
  18741. };
  18742. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18743. /**
  18744. * @author zz85 / http://www.lab4games.net/zz85/blog
  18745. * @author alteredq / http://alteredqualia.com/
  18746. *
  18747. * For creating 3D text geometry in three.js
  18748. *
  18749. * Text = 3D Text
  18750. *
  18751. * parameters = {
  18752. * size: <float>, // size of the text
  18753. * height: <float>, // thickness to extrude text
  18754. * curveSegments: <int>, // number of points on the curves
  18755. *
  18756. * font: <string>, // font name
  18757. * weight: <string>, // font weight (normal, bold)
  18758. * style: <string>, // font style (normal, italics)
  18759. *
  18760. * bevelEnabled: <bool>, // turn on bevel
  18761. * bevelThickness: <float>, // how deep into text bevel goes
  18762. * bevelSize: <float>, // how far from text outline is bevel
  18763. * }
  18764. *
  18765. */
  18766. /* Usage Examples
  18767. // TextGeometry wrapper
  18768. var text3d = new TextGeometry( text, options );
  18769. // Complete manner
  18770. var textShapes = THREE.FontUtils.generateShapes( text, options );
  18771. var text3d = new ExtrudeGeometry( textShapes, options );
  18772. */
  18773. THREE.TextGeometry = function ( text, parameters ) {
  18774. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  18775. // translate parameters to ExtrudeGeometry API
  18776. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  18777. // defaults
  18778. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  18779. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  18780. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  18781. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  18782. };
  18783. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  18784. /**
  18785. * @author oosmoxiecode
  18786. * @author mrdoob / http://mrdoob.com/
  18787. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  18788. */
  18789. THREE.TorusGeometry = function ( radius, tube, segmentsR, segmentsT, arc ) {
  18790. THREE.Geometry.call( this );
  18791. var scope = this;
  18792. this.radius = radius || 100;
  18793. this.tube = tube || 40;
  18794. this.segmentsR = segmentsR || 8;
  18795. this.segmentsT = segmentsT || 6;
  18796. this.arc = arc || Math.PI * 2;
  18797. var center = new THREE.Vector3(), uvs = [], normals = [];
  18798. for ( var j = 0; j <= this.segmentsR; j ++ ) {
  18799. for ( var i = 0; i <= this.segmentsT; i ++ ) {
  18800. var u = i / this.segmentsT * this.arc;
  18801. var v = j / this.segmentsR * Math.PI * 2;
  18802. center.x = this.radius * Math.cos( u );
  18803. center.y = this.radius * Math.sin( u );
  18804. var vertex = new THREE.Vector3();
  18805. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  18806. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  18807. vertex.z = this.tube * Math.sin( v );
  18808. this.vertices.push( vertex );
  18809. uvs.push( new THREE.UV( i / this.segmentsT, j / this.segmentsR ) );
  18810. normals.push( vertex.clone().subSelf( center ).normalize() );
  18811. }
  18812. }
  18813. for ( var j = 1; j <= this.segmentsR; j ++ ) {
  18814. for ( var i = 1; i <= this.segmentsT; i ++ ) {
  18815. var a = ( this.segmentsT + 1 ) * j + i - 1;
  18816. var b = ( this.segmentsT + 1 ) * ( j - 1 ) + i - 1;
  18817. var c = ( this.segmentsT + 1 ) * ( j - 1 ) + i;
  18818. var d = ( this.segmentsT + 1 ) * j + i;
  18819. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  18820. face.normal.addSelf( normals[ a ] );
  18821. face.normal.addSelf( normals[ b ] );
  18822. face.normal.addSelf( normals[ c ] );
  18823. face.normal.addSelf( normals[ d ] );
  18824. face.normal.normalize();
  18825. this.faces.push( face );
  18826. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  18827. }
  18828. }
  18829. this.computeCentroids();
  18830. };
  18831. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18832. /**
  18833. * @author oosmoxiecode
  18834. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  18835. */
  18836. THREE.TorusKnotGeometry = function ( radius, tube, segmentsR, segmentsT, p, q, heightScale ) {
  18837. THREE.Geometry.call( this );
  18838. var scope = this;
  18839. this.radius = radius || 200;
  18840. this.tube = tube || 40;
  18841. this.segmentsR = segmentsR || 64;
  18842. this.segmentsT = segmentsT || 8;
  18843. this.p = p || 2;
  18844. this.q = q || 3;
  18845. this.heightScale = heightScale || 1;
  18846. this.grid = new Array(this.segmentsR);
  18847. var tang = new THREE.Vector3();
  18848. var n = new THREE.Vector3();
  18849. var bitan = new THREE.Vector3();
  18850. for ( var i = 0; i < this.segmentsR; ++ i ) {
  18851. this.grid[ i ] = new Array( this.segmentsT );
  18852. for ( var j = 0; j < this.segmentsT; ++ j ) {
  18853. var u = i / this.segmentsR * 2 * this.p * Math.PI;
  18854. var v = j / this.segmentsT * 2 * Math.PI;
  18855. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  18856. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  18857. var cx, cy;
  18858. tang.sub( p2, p1 );
  18859. n.add( p2, p1 );
  18860. bitan.cross( tang, n );
  18861. n.cross( bitan, tang );
  18862. bitan.normalize();
  18863. n.normalize();
  18864. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18865. cy = this.tube * Math.sin( v );
  18866. p1.x += cx * n.x + cy * bitan.x;
  18867. p1.y += cx * n.y + cy * bitan.y;
  18868. p1.z += cx * n.z + cy * bitan.z;
  18869. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  18870. }
  18871. }
  18872. for ( var i = 0; i < this.segmentsR; ++ i ) {
  18873. for ( var j = 0; j < this.segmentsT; ++ j ) {
  18874. var ip = ( i + 1 ) % this.segmentsR;
  18875. var jp = ( j + 1 ) % this.segmentsT;
  18876. var a = this.grid[ i ][ j ];
  18877. var b = this.grid[ ip ][ j ];
  18878. var c = this.grid[ ip ][ jp ];
  18879. var d = this.grid[ i ][ jp ];
  18880. var uva = new THREE.UV( i / this.segmentsR, j / this.segmentsT );
  18881. var uvb = new THREE.UV( ( i + 1 ) / this.segmentsR, j / this.segmentsT );
  18882. var uvc = new THREE.UV( ( i + 1 ) / this.segmentsR, ( j + 1 ) / this.segmentsT );
  18883. var uvd = new THREE.UV( i / this.segmentsR, ( j + 1 ) / this.segmentsT );
  18884. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18885. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  18886. }
  18887. }
  18888. this.computeCentroids();
  18889. this.computeFaceNormals();
  18890. this.computeVertexNormals();
  18891. function vert( x, y, z ) {
  18892. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  18893. }
  18894. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  18895. var cu = Math.cos( u );
  18896. var cv = Math.cos( v );
  18897. var su = Math.sin( u );
  18898. var quOverP = in_q / in_p * u;
  18899. var cs = Math.cos( quOverP );
  18900. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  18901. var ty = radius * ( 2 + cs ) * su * 0.5;
  18902. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  18903. return new THREE.Vector3( tx, ty, tz );
  18904. }
  18905. };
  18906. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18907. /**
  18908. * @author WestLangley / https://github.com/WestLangley
  18909. * @author zz85 / https://github.com/zz85
  18910. * @author miningold / https://github.com/miningold
  18911. *
  18912. * Modified from the TorusKnotGeometry by @oosmoxiecode
  18913. *
  18914. * Creates a tube which extrudes along a 3d spline
  18915. *
  18916. * Uses parallel transport frames as described in
  18917. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18918. */
  18919. THREE.TubeGeometry = function( path, segments, radius, segmentsRadius, closed, debug ) {
  18920. THREE.Geometry.call( this );
  18921. this.path = path;
  18922. this.segments = segments || 64;
  18923. this.radius = radius || 1;
  18924. this.segmentsRadius = segmentsRadius || 8;
  18925. this.closed = closed || false;
  18926. if ( debug ) this.debug = new THREE.Object3D();
  18927. this.grid = [];
  18928. var scope = this,
  18929. tangent,
  18930. normal,
  18931. binormal,
  18932. numpoints = this.segments + 1,
  18933. x, y, z,
  18934. tx, ty, tz,
  18935. u, v,
  18936. cx, cy,
  18937. pos, pos2 = new THREE.Vector3(),
  18938. i, j,
  18939. ip, jp,
  18940. a, b, c, d,
  18941. uva, uvb, uvc, uvd;
  18942. var frames = new THREE.TubeGeometry.FrenetFrames(path, segments, closed),
  18943. tangents = frames.tangents,
  18944. normals = frames.normals,
  18945. binormals = frames.binormals;
  18946. // proxy internals
  18947. this.tangents = tangents;
  18948. this.normals = normals;
  18949. this.binormals = binormals;
  18950. function vert( x, y, z ) {
  18951. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  18952. }
  18953. // consruct the grid
  18954. for ( i = 0; i < numpoints; i++ ) {
  18955. this.grid[ i ] = [];
  18956. u = i / ( numpoints - 1 );
  18957. pos = path.getPointAt( u );
  18958. tangent = tangents[ i ];
  18959. normal = normals[ i ];
  18960. binormal = binormals[ i ];
  18961. if ( this.debug ) {
  18962. this.debug.add(new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff));
  18963. this.debug.add(new THREE.ArrowHelper(normal, pos, radius, 0xff0000));
  18964. this.debug.add(new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00));
  18965. }
  18966. for ( j = 0; j < this.segmentsRadius; j++ ) {
  18967. v = j / this.segmentsRadius * 2 * Math.PI;
  18968. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18969. cy = this.radius * Math.sin( v );
  18970. pos2.copy( pos );
  18971. pos2.x += cx * normal.x + cy * binormal.x;
  18972. pos2.y += cx * normal.y + cy * binormal.y;
  18973. pos2.z += cx * normal.z + cy * binormal.z;
  18974. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  18975. }
  18976. }
  18977. // construct the mesh
  18978. for ( i = 0; i < this.segments; i++ ) {
  18979. for ( j = 0; j < this.segmentsRadius; j++ ) {
  18980. ip = ( closed ) ? (i + 1) % this.segments : i + 1;
  18981. jp = (j + 1) % this.segmentsRadius;
  18982. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  18983. b = this.grid[ ip ][ j ];
  18984. c = this.grid[ ip ][ jp ];
  18985. d = this.grid[ i ][ jp ];
  18986. uva = new THREE.UV( i / this.segments, j / this.segmentsRadius );
  18987. uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.segmentsRadius );
  18988. uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.segmentsRadius );
  18989. uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.segmentsRadius );
  18990. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18991. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  18992. }
  18993. }
  18994. this.computeCentroids();
  18995. this.computeFaceNormals();
  18996. this.computeVertexNormals();
  18997. };
  18998. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18999. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19000. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19001. var
  19002. tangent = new THREE.Vector3(),
  19003. normal = new THREE.Vector3(),
  19004. binormal = new THREE.Vector3(),
  19005. tangents = [],
  19006. normals = [],
  19007. binormals = [],
  19008. vec = new THREE.Vector3(),
  19009. mat = new THREE.Matrix4(),
  19010. numpoints = segments + 1,
  19011. theta,
  19012. epsilon = 0.0001,
  19013. smallest,
  19014. tx, ty, tz,
  19015. i, u, v;
  19016. // expose internals
  19017. this.tangents = tangents;
  19018. this.normals = normals;
  19019. this.binormals = binormals;
  19020. // compute the tangent vectors for each segment on the path
  19021. for ( i = 0; i < numpoints; i++ ) {
  19022. u = i / ( numpoints - 1 );
  19023. tangents[ i ] = path.getTangentAt( u );
  19024. tangents[ i ].normalize();
  19025. }
  19026. initialNormal3();
  19027. function initialNormal1(lastBinormal) {
  19028. // fixed start binormal. Has dangers of 0 vectors
  19029. normals[ 0 ] = new THREE.Vector3();
  19030. binormals[ 0 ] = new THREE.Vector3();
  19031. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19032. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  19033. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  19034. }
  19035. function initialNormal2() {
  19036. // This uses the Frenet-Serret formula for deriving binormal
  19037. var t2 = path.getTangentAt( epsilon );
  19038. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
  19039. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  19040. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19041. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  19042. }
  19043. function initialNormal3() {
  19044. // select an initial normal vector perpenicular to the first tangent vector,
  19045. // and in the direction of the smallest tangent xyz component
  19046. normals[ 0 ] = new THREE.Vector3();
  19047. binormals[ 0 ] = new THREE.Vector3();
  19048. smallest = Number.MAX_VALUE;
  19049. tx = Math.abs( tangents[ 0 ].x );
  19050. ty = Math.abs( tangents[ 0 ].y );
  19051. tz = Math.abs( tangents[ 0 ].z );
  19052. if ( tx <= smallest ) {
  19053. smallest = tx;
  19054. normal.set( 1, 0, 0 );
  19055. }
  19056. if ( ty <= smallest ) {
  19057. smallest = ty;
  19058. normal.set( 0, 1, 0 );
  19059. }
  19060. if ( tz <= smallest ) {
  19061. normal.set( 0, 0, 1 );
  19062. }
  19063. vec.cross( tangents[ 0 ], normal ).normalize();
  19064. normals[ 0 ].cross( tangents[ 0 ], vec );
  19065. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  19066. }
  19067. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19068. for ( i = 1; i < numpoints; i++ ) {
  19069. normals[ i ] = normals[ i-1 ].clone();
  19070. binormals[ i ] = binormals[ i-1 ].clone();
  19071. vec.cross( tangents[ i-1 ], tangents[ i ] );
  19072. if ( vec.length() > epsilon ) {
  19073. vec.normalize();
  19074. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  19075. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  19076. }
  19077. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  19078. }
  19079. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19080. if ( closed ) {
  19081. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  19082. theta /= ( numpoints - 1 );
  19083. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19084. theta = -theta;
  19085. }
  19086. for ( i = 1; i < numpoints; i++ ) {
  19087. // twist a little...
  19088. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  19089. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  19090. }
  19091. }
  19092. };
  19093. /**
  19094. * @author clockworkgeek / https://github.com/clockworkgeek
  19095. * @author timothypratley / https://github.com/timothypratley
  19096. */
  19097. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19098. THREE.Geometry.call( this );
  19099. radius = radius || 1;
  19100. detail = detail || 0;
  19101. var that = this;
  19102. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19103. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19104. }
  19105. var midpoints = [], p = this.vertices;
  19106. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19107. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  19108. }
  19109. this.mergeVertices();
  19110. // Apply radius
  19111. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19112. this.vertices[ i ].multiplyScalar( radius );
  19113. }
  19114. // Project vector onto sphere's surface
  19115. function prepare( vector ) {
  19116. var vertex = vector.normalize().clone();
  19117. vertex.index = that.vertices.push( vertex ) - 1;
  19118. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19119. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19120. var v = inclination( vector ) / Math.PI + 0.5;
  19121. vertex.uv = new THREE.UV( u, 1 - v );
  19122. return vertex;
  19123. }
  19124. // Approximate a curved face with recursively sub-divided triangles.
  19125. function make( v1, v2, v3, detail ) {
  19126. if ( detail < 1 ) {
  19127. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19128. face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
  19129. face.normal = face.centroid.clone().normalize();
  19130. that.faces.push( face );
  19131. var azi = azimuth( face.centroid );
  19132. that.faceVertexUvs[ 0 ].push( [
  19133. correctUV( v1.uv, v1, azi ),
  19134. correctUV( v2.uv, v2, azi ),
  19135. correctUV( v3.uv, v3, azi )
  19136. ] );
  19137. } else {
  19138. detail -= 1;
  19139. // split triangle into 4 smaller triangles
  19140. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  19141. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  19142. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  19143. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  19144. }
  19145. }
  19146. function midpoint( v1, v2 ) {
  19147. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  19148. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  19149. var mid = midpoints[ v1.index ][ v2.index ];
  19150. if ( mid === undefined ) {
  19151. // generate mean point and project to surface with prepare()
  19152. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  19153. new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
  19154. );
  19155. }
  19156. return mid;
  19157. }
  19158. // Angle around the Y axis, counter-clockwise when looking from above.
  19159. function azimuth( vector ) {
  19160. return Math.atan2( vector.z, -vector.x );
  19161. }
  19162. // Angle above the XZ plane.
  19163. function inclination( vector ) {
  19164. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19165. }
  19166. // Texture fixing helper. Spheres have some odd behaviours.
  19167. function correctUV( uv, vector, azimuth ) {
  19168. if ( ( azimuth < 0 ) && ( uv.u === 1 ) ) uv = new THREE.UV( uv.u - 1, uv.v );
  19169. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
  19170. return uv;
  19171. }
  19172. this.computeCentroids();
  19173. this.boundingSphere = { radius: radius };
  19174. };
  19175. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19176. /**
  19177. * @author timothypratley / https://github.com/timothypratley
  19178. */
  19179. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19180. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19181. var vertices = [
  19182. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19183. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19184. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19185. ];
  19186. var faces = [
  19187. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19188. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19189. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19190. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19191. ];
  19192. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19193. };
  19194. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19195. /**
  19196. * @author timothypratley / https://github.com/timothypratley
  19197. */
  19198. THREE.OctahedronGeometry = function ( radius, detail ) {
  19199. var vertices = [
  19200. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19201. ];
  19202. var faces = [
  19203. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19204. ];
  19205. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19206. };
  19207. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19208. /**
  19209. * @author timothypratley / https://github.com/timothypratley
  19210. */
  19211. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19212. var vertices = [
  19213. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19214. ];
  19215. var faces = [
  19216. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19217. ];
  19218. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19219. };
  19220. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19221. /**
  19222. * @author zz85 / https://github.com/zz85
  19223. * Parametric Surfaces Geometry
  19224. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19225. *
  19226. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  19227. *
  19228. */
  19229. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  19230. THREE.Geometry.call( this );
  19231. var verts = this.vertices;
  19232. var faces = this.faces;
  19233. var uvs = this.faceVertexUvs[ 0 ];
  19234. useTris = (useTris === undefined) ? false : useTris;
  19235. var i, il, j, p;
  19236. var u, v;
  19237. var stackCount = stacks + 1;
  19238. var sliceCount = slices + 1;
  19239. for ( i = 0; i <= stacks; i ++ ) {
  19240. v = i / stacks;
  19241. for ( j = 0; j <= slices; j ++ ) {
  19242. u = j / slices;
  19243. p = func( u, v );
  19244. verts.push( p );
  19245. }
  19246. }
  19247. var a, b, c, d;
  19248. var uva, uvb, uvc, uvd;
  19249. for ( i = 0; i < stacks; i ++ ) {
  19250. for ( j = 0; j < slices; j ++ ) {
  19251. a = i * sliceCount + j;
  19252. b = i * sliceCount + j + 1;
  19253. c = (i + 1) * sliceCount + j;
  19254. d = (i + 1) * sliceCount + j + 1;
  19255. uva = new THREE.UV( j / slices, i / stacks );
  19256. uvb = new THREE.UV( ( j + 1 ) / slices, i / stacks );
  19257. uvc = new THREE.UV( j / slices, ( i + 1 ) / stacks );
  19258. uvd = new THREE.UV( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19259. if ( useTris ) {
  19260. faces.push( new THREE.Face3( a, b, c ) );
  19261. faces.push( new THREE.Face3( b, d, c ) );
  19262. uvs.push( [ uva, uvb, uvc ] );
  19263. uvs.push( [ uvb, uvd, uvc ] );
  19264. } else {
  19265. faces.push( new THREE.Face4( a, b, d, c ) );
  19266. uvs.push( [ uva, uvb, uvd, uvc ] );
  19267. }
  19268. }
  19269. }
  19270. // console.log(this);
  19271. // magic bullet
  19272. // var diff = this.mergeVertices();
  19273. // console.log('removed ', diff, ' vertices by merging');
  19274. this.computeCentroids();
  19275. this.computeFaceNormals();
  19276. this.computeVertexNormals();
  19277. };
  19278. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19279. /**
  19280. * @author qiao / https://github.com/qiao
  19281. * @fileoverview This is a convex hull generator using the incremental method.
  19282. * The complexity is O(n^2) where n is the number of vertices.
  19283. * O(nlogn) algorithms do exist, but they are much more complicated.
  19284. *
  19285. * Benchmark:
  19286. *
  19287. * Platform: CPU: P7350 @2.00GHz Engine: V8
  19288. *
  19289. * Num Vertices Time(ms)
  19290. *
  19291. * 10 1
  19292. * 20 3
  19293. * 30 19
  19294. * 40 48
  19295. * 50 107
  19296. */
  19297. THREE.ConvexGeometry = function( vertices ) {
  19298. THREE.Geometry.call( this );
  19299. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  19300. for ( var i = 3; i < vertices.length; i++ ) {
  19301. addPoint( i );
  19302. }
  19303. function addPoint( vertexId ) {
  19304. var vertex = vertices[ vertexId ].clone();
  19305. var mag = vertex.length();
  19306. vertex.x += mag * randomOffset();
  19307. vertex.y += mag * randomOffset();
  19308. vertex.z += mag * randomOffset();
  19309. var hole = [];
  19310. for ( var f = 0; f < faces.length; ) {
  19311. var face = faces[ f ];
  19312. // for each face, if the vertex can see it,
  19313. // then we try to add the face's edges into the hole.
  19314. if ( visible( face, vertex ) ) {
  19315. for ( var e = 0; e < 3; e++ ) {
  19316. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  19317. var boundary = true;
  19318. // remove duplicated edges.
  19319. for ( var h = 0; h < hole.length; h++ ) {
  19320. if ( equalEdge( hole[ h ], edge ) ) {
  19321. hole[ h ] = hole[ hole.length - 1 ];
  19322. hole.pop();
  19323. boundary = false;
  19324. break;
  19325. }
  19326. }
  19327. if ( boundary ) {
  19328. hole.push( edge );
  19329. }
  19330. }
  19331. // remove faces[ f ]
  19332. faces[ f ] = faces[ faces.length - 1 ];
  19333. faces.pop();
  19334. } else { // not visible
  19335. f++;
  19336. }
  19337. }
  19338. // construct the new faces formed by the edges of the hole and the vertex
  19339. for ( var h = 0; h < hole.length; h++ ) {
  19340. faces.push( [
  19341. hole[ h ][ 0 ],
  19342. hole[ h ][ 1 ],
  19343. vertexId
  19344. ] );
  19345. }
  19346. }
  19347. /**
  19348. * Whether the face is visible from the vertex
  19349. */
  19350. function visible( face, vertex ) {
  19351. var va = vertices[ face[ 0 ] ];
  19352. var vb = vertices[ face[ 1 ] ];
  19353. var vc = vertices[ face[ 2 ] ];
  19354. var n = normal( va, vb, vc );
  19355. // distance from face to origin
  19356. var dist = n.dot( va );
  19357. return n.dot( vertex ) >= dist;
  19358. }
  19359. /**
  19360. * Face normal
  19361. */
  19362. function normal( va, vb, vc ) {
  19363. var cb = new THREE.Vector3();
  19364. var ab = new THREE.Vector3();
  19365. cb.sub( vc, vb );
  19366. ab.sub( va, vb );
  19367. cb.crossSelf( ab );
  19368. if ( !cb.isZero() ) {
  19369. cb.normalize();
  19370. }
  19371. return cb;
  19372. }
  19373. /**
  19374. * Detect whether two edges are equal.
  19375. * Note that when constructing the convex hull, two same edges can only
  19376. * be of the negative direction.
  19377. */
  19378. function equalEdge( ea, eb ) {
  19379. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  19380. }
  19381. /**
  19382. * Create a random offset between -1e-6 and 1e-6.
  19383. */
  19384. function randomOffset() {
  19385. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  19386. }
  19387. /**
  19388. * XXX: Not sure if this is the correct approach. Need someone to review.
  19389. */
  19390. function vertexUv( vertex ) {
  19391. var mag = vertex.length();
  19392. return new THREE.UV( vertex.x / mag, vertex.y / mag );
  19393. }
  19394. // Push vertices into `this.vertices`, skipping those inside the hull
  19395. var id = 0;
  19396. var newId = new Array( vertices.length ); // map from old vertex id to new id
  19397. for ( var i = 0; i < faces.length; i++ ) {
  19398. var face = faces[ i ];
  19399. for ( var j = 0; j < 3; j++ ) {
  19400. if ( newId[ face[ j ] ] === undefined ) {
  19401. newId[ face[ j ] ] = id++;
  19402. this.vertices.push( vertices[ face[ j ] ] );
  19403. }
  19404. face[ j ] = newId[ face[ j ] ];
  19405. }
  19406. }
  19407. // Convert faces into instances of THREE.Face3
  19408. for ( var i = 0; i < faces.length; i++ ) {
  19409. this.faces.push( new THREE.Face3(
  19410. faces[ i ][ 0 ],
  19411. faces[ i ][ 1 ],
  19412. faces[ i ][ 2 ]
  19413. ) );
  19414. }
  19415. // Compute UVs
  19416. for ( var i = 0; i < this.faces.length; i++ ) {
  19417. var face = this.faces[ i ];
  19418. this.faceVertexUvs[ 0 ].push( [
  19419. vertexUv( this.vertices[ face.a ] ),
  19420. vertexUv( this.vertices[ face.b ] ),
  19421. vertexUv( this.vertices[ face.c ])
  19422. ] );
  19423. }
  19424. this.computeCentroids();
  19425. this.computeFaceNormals();
  19426. this.computeVertexNormals();
  19427. };
  19428. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19429. /**
  19430. * @author sroucheray / http://sroucheray.org/
  19431. * @author mrdoob / http://mrdoob.com/
  19432. */
  19433. THREE.AxisHelper = function () {
  19434. THREE.Object3D.call( this );
  19435. var lineGeometry = new THREE.Geometry();
  19436. lineGeometry.vertices.push( new THREE.Vector3() );
  19437. lineGeometry.vertices.push( new THREE.Vector3( 0, 100, 0 ) );
  19438. var coneGeometry = new THREE.CylinderGeometry( 0, 5, 25, 5, 1 );
  19439. var line, cone;
  19440. // x
  19441. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0xff0000 } ) );
  19442. line.rotation.z = - Math.PI / 2;
  19443. this.add( line );
  19444. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0xff0000 } ) );
  19445. cone.position.x = 100;
  19446. cone.rotation.z = - Math.PI / 2;
  19447. this.add( cone );
  19448. // y
  19449. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x00ff00 } ) );
  19450. this.add( line );
  19451. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x00ff00 } ) );
  19452. cone.position.y = 100;
  19453. this.add( cone );
  19454. // z
  19455. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x0000ff } ) );
  19456. line.rotation.x = Math.PI / 2;
  19457. this.add( line );
  19458. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x0000ff } ) );
  19459. cone.position.z = 100;
  19460. cone.rotation.x = Math.PI / 2;
  19461. this.add( cone );
  19462. };
  19463. THREE.AxisHelper.prototype = Object.create( THREE.Object3D.prototype );
  19464. /**
  19465. * @author WestLangley / http://github.com/WestLangley
  19466. * @author zz85 / https://github.com/zz85
  19467. *
  19468. * Creates an arrow for visualizing directions
  19469. *
  19470. * Parameters:
  19471. * dir - Vector3
  19472. * origin - Vector3
  19473. * length - Number
  19474. * hex - color in hex value
  19475. */
  19476. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  19477. THREE.Object3D.call( this );
  19478. if ( hex === undefined ) hex = 0xffff00;
  19479. if ( length === undefined ) length = 20;
  19480. var lineGeometry = new THREE.Geometry();
  19481. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  19482. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  19483. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  19484. this.add( this.line );
  19485. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  19486. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  19487. this.cone.position.set( 0, 1, 0 );
  19488. this.add( this.cone );
  19489. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  19490. this.setDirection( dir );
  19491. this.setLength( length );
  19492. };
  19493. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  19494. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  19495. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  19496. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  19497. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  19498. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  19499. };
  19500. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  19501. this.scale.set( length, length, length );
  19502. };
  19503. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  19504. this.line.material.color.setHex( hex );
  19505. this.cone.material.color.setHex( hex );
  19506. };
  19507. /**
  19508. * @author alteredq / http://alteredqualia.com/
  19509. *
  19510. * - shows frustum, line of sight and up of the camera
  19511. * - suitable for fast updates
  19512. * - based on frustum visualization in lightgl.js shadowmap example
  19513. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  19514. */
  19515. THREE.CameraHelper = function ( camera ) {
  19516. THREE.Line.call( this );
  19517. var scope = this;
  19518. this.geometry = new THREE.Geometry();
  19519. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  19520. this.type = THREE.LinePieces;
  19521. this.matrixWorld = camera.matrixWorld;
  19522. this.matrixAutoUpdate = false;
  19523. this.pointMap = {};
  19524. // colors
  19525. var hexFrustum = 0xffaa00;
  19526. var hexCone = 0xff0000;
  19527. var hexUp = 0x00aaff;
  19528. var hexTarget = 0xffffff;
  19529. var hexCross = 0x333333;
  19530. // near
  19531. addLine( "n1", "n2", hexFrustum );
  19532. addLine( "n2", "n4", hexFrustum );
  19533. addLine( "n4", "n3", hexFrustum );
  19534. addLine( "n3", "n1", hexFrustum );
  19535. // far
  19536. addLine( "f1", "f2", hexFrustum );
  19537. addLine( "f2", "f4", hexFrustum );
  19538. addLine( "f4", "f3", hexFrustum );
  19539. addLine( "f3", "f1", hexFrustum );
  19540. // sides
  19541. addLine( "n1", "f1", hexFrustum );
  19542. addLine( "n2", "f2", hexFrustum );
  19543. addLine( "n3", "f3", hexFrustum );
  19544. addLine( "n4", "f4", hexFrustum );
  19545. // cone
  19546. addLine( "p", "n1", hexCone );
  19547. addLine( "p", "n2", hexCone );
  19548. addLine( "p", "n3", hexCone );
  19549. addLine( "p", "n4", hexCone );
  19550. // up
  19551. addLine( "u1", "u2", hexUp );
  19552. addLine( "u2", "u3", hexUp );
  19553. addLine( "u3", "u1", hexUp );
  19554. // target
  19555. addLine( "c", "t", hexTarget );
  19556. addLine( "p", "c", hexCross );
  19557. // cross
  19558. addLine( "cn1", "cn2", hexCross );
  19559. addLine( "cn3", "cn4", hexCross );
  19560. addLine( "cf1", "cf2", hexCross );
  19561. addLine( "cf3", "cf4", hexCross );
  19562. this.camera = camera;
  19563. function addLine( a, b, hex ) {
  19564. addPoint( a, hex );
  19565. addPoint( b, hex );
  19566. }
  19567. function addPoint( id, hex ) {
  19568. scope.geometry.vertices.push( new THREE.Vector3() );
  19569. scope.geometry.colors.push( new THREE.Color( hex ) );
  19570. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  19571. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  19572. }
  19573. this.update( camera );
  19574. };
  19575. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  19576. THREE.CameraHelper.prototype.update = function () {
  19577. var scope = this;
  19578. var w = 1, h = 1;
  19579. // we need just camera projection matrix
  19580. // world matrix must be identity
  19581. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  19582. // center / target
  19583. setPoint( "c", 0, 0, -1 );
  19584. setPoint( "t", 0, 0, 1 );
  19585. // near
  19586. setPoint( "n1", -w, -h, -1 );
  19587. setPoint( "n2", w, -h, -1 );
  19588. setPoint( "n3", -w, h, -1 );
  19589. setPoint( "n4", w, h, -1 );
  19590. // far
  19591. setPoint( "f1", -w, -h, 1 );
  19592. setPoint( "f2", w, -h, 1 );
  19593. setPoint( "f3", -w, h, 1 );
  19594. setPoint( "f4", w, h, 1 );
  19595. // up
  19596. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  19597. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  19598. setPoint( "u3", 0, h * 2, -1 );
  19599. // cross
  19600. setPoint( "cf1", -w, 0, 1 );
  19601. setPoint( "cf2", w, 0, 1 );
  19602. setPoint( "cf3", 0, -h, 1 );
  19603. setPoint( "cf4", 0, h, 1 );
  19604. setPoint( "cn1", -w, 0, -1 );
  19605. setPoint( "cn2", w, 0, -1 );
  19606. setPoint( "cn3", 0, -h, -1 );
  19607. setPoint( "cn4", 0, h, -1 );
  19608. function setPoint( point, x, y, z ) {
  19609. THREE.CameraHelper.__v.set( x, y, z );
  19610. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  19611. var points = scope.pointMap[ point ];
  19612. if ( points !== undefined ) {
  19613. for ( var i = 0, il = points.length; i < il; i ++ ) {
  19614. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  19615. }
  19616. }
  19617. }
  19618. this.geometry.verticesNeedUpdate = true;
  19619. };
  19620. THREE.CameraHelper.__projector = new THREE.Projector();
  19621. THREE.CameraHelper.__v = new THREE.Vector3();
  19622. THREE.CameraHelper.__c = new THREE.Camera();
  19623. /*
  19624. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  19625. *
  19626. * Subdivision Geometry Modifier
  19627. * using Catmull-Clark Subdivision Surfaces
  19628. * for creating smooth geometry meshes
  19629. *
  19630. * Note: a modifier modifies vertices and faces of geometry,
  19631. * so use THREE.GeometryUtils.clone() if orignal geoemtry needs to be retained
  19632. *
  19633. * Readings:
  19634. * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  19635. * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
  19636. * http://xrt.wikidot.com/blog:31
  19637. * "Subdivision Surfaces in Character Animation"
  19638. *
  19639. * Supports:
  19640. * Closed and Open geometries.
  19641. *
  19642. * TODO:
  19643. * crease vertex and "semi-sharp" features
  19644. * selective subdivision
  19645. */
  19646. THREE.SubdivisionModifier = function( subdivisions ) {
  19647. this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
  19648. // Settings
  19649. this.useOldVertexColors = false;
  19650. this.supportUVs = true;
  19651. this.debug = false;
  19652. };
  19653. // Applies the "modify" pattern
  19654. THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {
  19655. var repeats = this.subdivisions;
  19656. while ( repeats-- > 0 ) {
  19657. this.smooth( geometry );
  19658. }
  19659. };
  19660. // Performs an iteration of Catmull-Clark Subdivision
  19661. THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
  19662. //debug( 'running smooth' );
  19663. // New set of vertices, faces and uvs
  19664. var newVertices = [], newFaces = [], newUVs = [];
  19665. function v( x, y, z ) {
  19666. newVertices.push( new THREE.Vector3( x, y, z ) );
  19667. }
  19668. var scope = this;
  19669. function debug() {
  19670. if (scope.debug) console.log.apply(console, arguments);
  19671. }
  19672. function warn() {
  19673. if (console)
  19674. console.log.apply(console, arguments);
  19675. }
  19676. function f4( a, b, c, d, oldFace, orders, facei ) {
  19677. // TODO move vertex selection over here!
  19678. var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.materialIndex );
  19679. if (scope.useOldVertexColors) {
  19680. newFace.vertexColors = [];
  19681. var color, tmpColor, order;
  19682. for (var i=0;i<4;i++) {
  19683. order = orders[i];
  19684. color = new THREE.Color(),
  19685. color.setRGB(0,0,0);
  19686. for (var j=0, jl=0; j<order.length;j++) {
  19687. tmpColor = oldFace.vertexColors[order[j]-1];
  19688. color.r += tmpColor.r;
  19689. color.g += tmpColor.g;
  19690. color.b += tmpColor.b;
  19691. }
  19692. color.r /= order.length;
  19693. color.g /= order.length;
  19694. color.b /= order.length;
  19695. newFace.vertexColors[i] = color;
  19696. }
  19697. }
  19698. newFaces.push( newFace );
  19699. if (scope.supportUVs) {
  19700. var aUv = [
  19701. getUV(a, ''),
  19702. getUV(b, facei),
  19703. getUV(c, facei),
  19704. getUV(d, facei)
  19705. ];
  19706. if (!aUv[0]) debug('a :( ', a+':'+facei);
  19707. else if (!aUv[1]) debug('b :( ', b+':'+facei);
  19708. else if (!aUv[2]) debug('c :( ', c+':'+facei);
  19709. else if (!aUv[3]) debug('d :( ', d+':'+facei);
  19710. else
  19711. newUVs.push( aUv );
  19712. }
  19713. }
  19714. function edge_hash( a, b ) {
  19715. return Math.min( a, b ) + "_" + Math.max( a, b );
  19716. }
  19717. function computeEdgeFaces( geometry ) {
  19718. var i, il, v1, v2, j, k,
  19719. face, faceIndices, faceIndex,
  19720. edge,
  19721. hash,
  19722. edgeFaceMap = {};
  19723. function mapEdgeHash( hash, i ) {
  19724. if ( edgeFaceMap[ hash ] === undefined ) {
  19725. edgeFaceMap[ hash ] = [];
  19726. }
  19727. edgeFaceMap[ hash ].push( i );
  19728. }
  19729. // construct vertex -> face map
  19730. for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  19731. face = geometry.faces[ i ];
  19732. if ( face instanceof THREE.Face3 ) {
  19733. hash = edge_hash( face.a, face.b );
  19734. mapEdgeHash( hash, i );
  19735. hash = edge_hash( face.b, face.c );
  19736. mapEdgeHash( hash, i );
  19737. hash = edge_hash( face.c, face.a );
  19738. mapEdgeHash( hash, i );
  19739. } else if ( face instanceof THREE.Face4 ) {
  19740. hash = edge_hash( face.a, face.b );
  19741. mapEdgeHash( hash, i );
  19742. hash = edge_hash( face.b, face.c );
  19743. mapEdgeHash( hash, i );
  19744. hash = edge_hash( face.c, face.d );
  19745. mapEdgeHash( hash, i );
  19746. hash = edge_hash( face.d, face.a );
  19747. mapEdgeHash( hash, i );
  19748. }
  19749. }
  19750. // extract faces
  19751. // var edges = [];
  19752. //
  19753. // var numOfEdges = 0;
  19754. // for (i in edgeFaceMap) {
  19755. // numOfEdges++;
  19756. //
  19757. // edge = edgeFaceMap[i];
  19758. // edges.push(edge);
  19759. //
  19760. // }
  19761. //debug('edgeFaceMap', edgeFaceMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
  19762. return edgeFaceMap;
  19763. }
  19764. var originalPoints = oldGeometry.vertices;
  19765. var originalFaces = oldGeometry.faces;
  19766. var newPoints = originalPoints.concat(); // Vertices
  19767. var facePoints = [], edgePoints = {};
  19768. var sharpEdges = {}, sharpVertices = [], sharpFaces = [];
  19769. var uvForVertices = {}; // Stored in {vertex}:{old face} format
  19770. var originalVerticesLength = originalPoints.length;
  19771. function getUV(vertexNo, oldFaceNo) {
  19772. var j,jl;
  19773. var key = vertexNo+':'+oldFaceNo;
  19774. var theUV = uvForVertices[key];
  19775. if (!theUV) {
  19776. if (vertexNo>=originalVerticesLength && vertexNo < (originalVerticesLength + originalFaces.length)) {
  19777. debug('face pt');
  19778. } else {
  19779. debug('edge pt');
  19780. }
  19781. warn('warning, UV not found for', key);
  19782. return null;
  19783. }
  19784. return theUV;
  19785. // Original faces -> Vertex Nos.
  19786. // new Facepoint -> Vertex Nos.
  19787. // edge Points
  19788. }
  19789. function addUV(vertexNo, oldFaceNo, value) {
  19790. var key = vertexNo+':'+oldFaceNo;
  19791. if (!(key in uvForVertices)) {
  19792. uvForVertices[key] = value;
  19793. } else {
  19794. warn('dup vertexNo', vertexNo, 'oldFaceNo', oldFaceNo, 'value', value, 'key', key, uvForVertices[key]);
  19795. }
  19796. }
  19797. // Step 1
  19798. // For each face, add a face point
  19799. // Set each face point to be the centroid of all original points for the respective face.
  19800. // debug(oldGeometry);
  19801. var i, il, j, jl, face;
  19802. // For Uvs
  19803. var uvs = oldGeometry.faceVertexUvs[0];
  19804. var abcd = 'abcd', vertice;
  19805. debug('originalFaces, uvs, originalVerticesLength', originalFaces.length, uvs.length, originalVerticesLength);
  19806. if (scope.supportUVs)
  19807. for (i=0, il = uvs.length; i<il; i++ ) {
  19808. for (j=0,jl=uvs[i].length;j<jl;j++) {
  19809. vertice = originalFaces[i][abcd.charAt(j)];
  19810. addUV(vertice, i, uvs[i][j]);
  19811. }
  19812. }
  19813. if (uvs.length == 0) scope.supportUVs = false;
  19814. // Additional UVs check, if we index original
  19815. var uvCount = 0;
  19816. for (var u in uvForVertices) {
  19817. uvCount++;
  19818. }
  19819. if (!uvCount) {
  19820. scope.supportUVs = false;
  19821. debug('no uvs');
  19822. }
  19823. debug('-- Original Faces + Vertices UVs completed', uvForVertices, 'vs', uvs.length);
  19824. var avgUv ;
  19825. for (i=0, il = originalFaces.length; i<il ;i++) {
  19826. face = originalFaces[ i ];
  19827. facePoints.push( face.centroid );
  19828. newPoints.push( face.centroid );
  19829. if (!scope.supportUVs) continue;
  19830. // Prepare subdivided uv
  19831. avgUv = new THREE.UV();
  19832. if ( face instanceof THREE.Face3 ) {
  19833. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u;
  19834. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v;
  19835. avgUv.u /= 3;
  19836. avgUv.v /= 3;
  19837. } else if ( face instanceof THREE.Face4 ) {
  19838. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u + getUV( face.d, i ).u;
  19839. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v + getUV( face.d, i ).v;
  19840. avgUv.u /= 4;
  19841. avgUv.v /= 4;
  19842. }
  19843. addUV(originalVerticesLength + i, '', avgUv);
  19844. }
  19845. debug('-- added UVs for new Faces', uvForVertices);
  19846. // Step 2
  19847. // For each edge, add an edge point.
  19848. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
  19849. var edgeFaceMap = computeEdgeFaces ( oldGeometry ); // Edge Hash -> Faces Index
  19850. var edge, faceIndexA, faceIndexB, avg;
  19851. // debug('edgeFaceMap', edgeFaceMap);
  19852. var edgeCount = 0;
  19853. var edgeVertex, edgeVertexA, edgeVertexB;
  19854. ////
  19855. var vertexEdgeMap = {}; // Gives edges connecting from each vertex
  19856. var vertexFaceMap = {}; // Gives faces connecting from each vertex
  19857. function addVertexEdgeMap(vertex, edge) {
  19858. if (vertexEdgeMap[vertex]===undefined) {
  19859. vertexEdgeMap[vertex] = [];
  19860. }
  19861. vertexEdgeMap[vertex].push(edge);
  19862. }
  19863. function addVertexFaceMap(vertex, face, edge) {
  19864. if (vertexFaceMap[vertex]===undefined) {
  19865. vertexFaceMap[vertex] = {};
  19866. }
  19867. vertexFaceMap[vertex][face] = edge;
  19868. // vertexFaceMap[vertex][face] = null;
  19869. }
  19870. // Prepares vertexEdgeMap and vertexFaceMap
  19871. for (i in edgeFaceMap) { // This is for every edge
  19872. edge = edgeFaceMap[i];
  19873. edgeVertex = i.split('_');
  19874. edgeVertexA = edgeVertex[0];
  19875. edgeVertexB = edgeVertex[1];
  19876. // Maps an edgeVertex to connecting edges
  19877. addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
  19878. addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
  19879. for (j=0,jl=edge.length;j<jl;j++) {
  19880. face = edge[j];
  19881. addVertexFaceMap(edgeVertexA, face, i);
  19882. addVertexFaceMap(edgeVertexB, face, i);
  19883. }
  19884. if (edge.length < 2) {
  19885. // edge is "sharp";
  19886. sharpEdges[i] = true;
  19887. sharpVertices[edgeVertexA] = true;
  19888. sharpVertices[edgeVertexB] = true;
  19889. }
  19890. }
  19891. debug('vertexEdgeMap',vertexEdgeMap, 'vertexFaceMap', vertexFaceMap);
  19892. for (i in edgeFaceMap) {
  19893. edge = edgeFaceMap[i];
  19894. faceIndexA = edge[0]; // face index a
  19895. faceIndexB = edge[1]; // face index b
  19896. edgeVertex = i.split('_');
  19897. edgeVertexA = edgeVertex[0];
  19898. edgeVertexB = edgeVertex[1];
  19899. avg = new THREE.Vector3();
  19900. //debug(i, faceIndexB,facePoints[faceIndexB]);
  19901. if (sharpEdges[i]) {
  19902. //debug('warning, ', i, 'edge has only 1 connecting face', edge);
  19903. // For a sharp edge, average the edge end points.
  19904. avg.addSelf(originalPoints[edgeVertexA]);
  19905. avg.addSelf(originalPoints[edgeVertexB]);
  19906. avg.multiplyScalar(0.5);
  19907. sharpVertices[newPoints.length] = true;
  19908. } else {
  19909. avg.addSelf(facePoints[faceIndexA]);
  19910. avg.addSelf(facePoints[faceIndexB]);
  19911. avg.addSelf(originalPoints[edgeVertexA]);
  19912. avg.addSelf(originalPoints[edgeVertexB]);
  19913. avg.multiplyScalar(0.25);
  19914. }
  19915. edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
  19916. newPoints.push( avg );
  19917. edgeCount ++;
  19918. if (!scope.supportUVs) {
  19919. continue;
  19920. }
  19921. // debug('faceIndexAB', faceIndexA, faceIndexB, sharpEdges[i]);
  19922. // Prepare subdivided uv
  19923. avgUv = new THREE.UV();
  19924. avgUv.u = getUV(edgeVertexA, faceIndexA).u + getUV(edgeVertexB, faceIndexA).u;
  19925. avgUv.v = getUV(edgeVertexA, faceIndexA).v + getUV(edgeVertexB, faceIndexA).v;
  19926. avgUv.u /= 2;
  19927. avgUv.v /= 2;
  19928. addUV(edgePoints[i], faceIndexA, avgUv);
  19929. if (!sharpEdges[i]) {
  19930. avgUv = new THREE.UV();
  19931. avgUv.u = getUV(edgeVertexA, faceIndexB).u + getUV(edgeVertexB, faceIndexB).u;
  19932. avgUv.v = getUV(edgeVertexA, faceIndexB).v + getUV(edgeVertexB, faceIndexB).v;
  19933. avgUv.u /= 2;
  19934. avgUv.v /= 2;
  19935. addUV(edgePoints[i], faceIndexB, avgUv);
  19936. }
  19937. }
  19938. debug('-- Step 2 done');
  19939. // Step 3
  19940. // For each face point, add an edge for every edge of the face,
  19941. // connecting the face point to each edge point for the face.
  19942. var facePt, currentVerticeIndex;
  19943. var hashAB, hashBC, hashCD, hashDA, hashCA;
  19944. var abc123 = ['123', '12', '2', '23'];
  19945. var bca123 = ['123', '23', '3', '31'];
  19946. var cab123 = ['123', '31', '1', '12'];
  19947. var abc1234 = ['1234', '12', '2', '23'];
  19948. var bcd1234 = ['1234', '23', '3', '34'];
  19949. var cda1234 = ['1234', '34', '4', '41'];
  19950. var dab1234 = ['1234', '41', '1', '12'];
  19951. for (i=0, il = facePoints.length; i<il ;i++) { // for every face
  19952. facePt = facePoints[i];
  19953. face = originalFaces[i];
  19954. currentVerticeIndex = originalVerticesLength+ i;
  19955. if ( face instanceof THREE.Face3 ) {
  19956. // create 3 face4s
  19957. hashAB = edge_hash( face.a, face.b );
  19958. hashBC = edge_hash( face.b, face.c );
  19959. hashCA = edge_hash( face.c, face.a );
  19960. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123, i );
  19961. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123, i );
  19962. f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123, i );
  19963. } else if ( face instanceof THREE.Face4 ) {
  19964. // create 4 face4s
  19965. hashAB = edge_hash( face.a, face.b );
  19966. hashBC = edge_hash( face.b, face.c );
  19967. hashCD = edge_hash( face.c, face.d );
  19968. hashDA = edge_hash( face.d, face.a );
  19969. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234, i );
  19970. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234, i );
  19971. f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234, i );
  19972. f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234, i );
  19973. } else {
  19974. debug('face should be a face!', face);
  19975. }
  19976. }
  19977. newVertices = newPoints;
  19978. // debug('original ', oldGeometry.vertices.length, oldGeometry.faces.length );
  19979. // debug('new points', newPoints.length, 'faces', newFaces.length );
  19980. // Step 4
  19981. // For each original point P,
  19982. // take the average F of all n face points for faces touching P,
  19983. // and take the average R of all n edge midpoints for edges touching P,
  19984. // where each edge midpoint is the average of its two endpoint vertices.
  19985. // Move each original point to the point
  19986. var F = new THREE.Vector3();
  19987. var R = new THREE.Vector3();
  19988. var n;
  19989. for (i=0, il = originalPoints.length; i<il; i++) {
  19990. // (F + 2R + (n-3)P) / n
  19991. if (vertexEdgeMap[i]===undefined) continue;
  19992. F.set(0,0,0);
  19993. R.set(0,0,0);
  19994. var newPos = new THREE.Vector3(0,0,0);
  19995. var f =0;
  19996. for (j in vertexFaceMap[i]) {
  19997. F.addSelf(facePoints[j]);
  19998. f++;
  19999. }
  20000. var sharpEdgeCount = 0;
  20001. n = vertexEdgeMap[i].length;
  20002. for (j=0;j<n;j++) {
  20003. if (
  20004. sharpEdges[
  20005. edge_hash(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
  20006. ]) {
  20007. sharpEdgeCount++;
  20008. }
  20009. }
  20010. if ( sharpEdgeCount==2 ) {
  20011. continue;
  20012. // Do not move vertex if there's 2 connecting sharp edges.
  20013. }
  20014. /*
  20015. if (sharpEdgeCount>2) {
  20016. // TODO
  20017. }
  20018. */
  20019. F.divideScalar(f);
  20020. for (j=0; j<n;j++) {
  20021. edge = vertexEdgeMap[i][j];
  20022. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  20023. R.addSelf(midPt);
  20024. // R.addSelf(originalPoints[edge[0]]);
  20025. // R.addSelf(originalPoints[edge[1]]);
  20026. }
  20027. R.divideScalar(n);
  20028. newPos.addSelf(originalPoints[i]);
  20029. newPos.multiplyScalar(n - 3);
  20030. newPos.addSelf(F);
  20031. newPos.addSelf(R.multiplyScalar(2));
  20032. newPos.divideScalar(n);
  20033. newVertices[i] = newPos;
  20034. }
  20035. var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
  20036. newGeometry.vertices = newVertices;
  20037. newGeometry.faces = newFaces;
  20038. newGeometry.faceVertexUvs[ 0 ] = newUVs;
  20039. delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
  20040. newGeometry.computeCentroids();
  20041. newGeometry.computeFaceNormals();
  20042. newGeometry.computeVertexNormals();
  20043. };
  20044. /**
  20045. * @author alteredq / http://alteredqualia.com/
  20046. */
  20047. THREE.ImmediateRenderObject = function ( ) {
  20048. THREE.Object3D.call( this );
  20049. this.render = function ( renderCallback ) { };
  20050. };
  20051. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20052. /**
  20053. * @author mikael emtinger / http://gomo.se/
  20054. * @author alteredq / http://alteredqualia.com/
  20055. */
  20056. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20057. THREE.Object3D.call( this );
  20058. this.lensFlares = [];
  20059. this.positionScreen = new THREE.Vector3();
  20060. this.customUpdateCallback = undefined;
  20061. if( texture !== undefined ) {
  20062. this.add( texture, size, distance, blending, color );
  20063. }
  20064. };
  20065. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20066. /*
  20067. * Add: adds another flare
  20068. */
  20069. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20070. if( size === undefined ) size = -1;
  20071. if( distance === undefined ) distance = 0;
  20072. if( opacity === undefined ) opacity = 1;
  20073. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20074. if( blending === undefined ) blending = THREE.NormalBlending;
  20075. distance = Math.min( distance, Math.max( 0, distance ) );
  20076. this.lensFlares.push( { texture: texture, // THREE.Texture
  20077. size: size, // size in pixels (-1 = use texture.width)
  20078. distance: distance, // distance (0-1) from light source (0=at light source)
  20079. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20080. scale: 1, // scale
  20081. rotation: 1, // rotation
  20082. opacity: opacity, // opacity
  20083. color: color, // color
  20084. blending: blending } ); // blending
  20085. };
  20086. /*
  20087. * Update lens flares update positions on all flares based on the screen position
  20088. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20089. */
  20090. THREE.LensFlare.prototype.updateLensFlares = function () {
  20091. var f, fl = this.lensFlares.length;
  20092. var flare;
  20093. var vecX = -this.positionScreen.x * 2;
  20094. var vecY = -this.positionScreen.y * 2;
  20095. for( f = 0; f < fl; f ++ ) {
  20096. flare = this.lensFlares[ f ];
  20097. flare.x = this.positionScreen.x + vecX * flare.distance;
  20098. flare.y = this.positionScreen.y + vecY * flare.distance;
  20099. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20100. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20101. }
  20102. };
  20103. /**
  20104. * @author alteredq / http://alteredqualia.com/
  20105. */
  20106. THREE.MorphBlendMesh = function( geometry, material ) {
  20107. THREE.Mesh.call( this, geometry, material );
  20108. this.animationsMap = {};
  20109. this.animationsList = [];
  20110. // prepare default animation
  20111. // (all frames played together in 1 second)
  20112. var numFrames = this.geometry.morphTargets.length;
  20113. var name = "__default";
  20114. var startFrame = 0;
  20115. var endFrame = numFrames - 1;
  20116. var fps = numFrames / 1;
  20117. this.createAnimation( name, startFrame, endFrame, fps );
  20118. this.setAnimationWeight( name, 1 );
  20119. };
  20120. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20121. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20122. var animation = {
  20123. startFrame: start,
  20124. endFrame: end,
  20125. length: end - start + 1,
  20126. fps: fps,
  20127. duration: ( end - start ) / fps,
  20128. lastFrame: 0,
  20129. currentFrame: 0,
  20130. active: false,
  20131. time: 0,
  20132. direction: 1,
  20133. weight: 1,
  20134. directionBackwards: false,
  20135. mirroredLoop: false
  20136. };
  20137. this.animationsMap[ name ] = animation;
  20138. this.animationsList.push( animation );
  20139. };
  20140. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20141. var pattern = /([a-z]+)(\d+)/;
  20142. var firstAnimation, frameRanges = {};
  20143. var geometry = this.geometry;
  20144. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20145. var morph = geometry.morphTargets[ i ];
  20146. var chunks = morph.name.match( pattern );
  20147. if ( chunks && chunks.length > 1 ) {
  20148. var name = chunks[ 1 ];
  20149. var num = chunks[ 2 ];
  20150. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20151. var range = frameRanges[ name ];
  20152. if ( i < range.start ) range.start = i;
  20153. if ( i > range.end ) range.end = i;
  20154. if ( ! firstAnimation ) firstAnimation = name;
  20155. }
  20156. }
  20157. for ( var name in frameRanges ) {
  20158. var range = frameRanges[ name ];
  20159. this.createAnimation( name, range.start, range.end, fps );
  20160. }
  20161. this.firstAnimation = firstAnimation;
  20162. };
  20163. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20164. var animation = this.animationsMap[ name ];
  20165. if ( animation ) {
  20166. animation.direction = 1;
  20167. animation.directionBackwards = false;
  20168. }
  20169. };
  20170. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20171. var animation = this.animationsMap[ name ];
  20172. if ( animation ) {
  20173. animation.direction = -1;
  20174. animation.directionBackwards = true;
  20175. }
  20176. };
  20177. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20178. var animation = this.animationsMap[ name ];
  20179. if ( animation ) {
  20180. animation.fps = fps;
  20181. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20182. }
  20183. };
  20184. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20185. var animation = this.animationsMap[ name ];
  20186. if ( animation ) {
  20187. animation.duration = duration;
  20188. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20189. }
  20190. };
  20191. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20192. var animation = this.animationsMap[ name ];
  20193. if ( animation ) {
  20194. animation.weight = weight;
  20195. }
  20196. };
  20197. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20198. var animation = this.animationsMap[ name ];
  20199. if ( animation ) {
  20200. animation.time = time;
  20201. }
  20202. };
  20203. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20204. var time = 0;
  20205. var animation = this.animationsMap[ name ];
  20206. if ( animation ) {
  20207. time = animation.time;
  20208. }
  20209. return time;
  20210. };
  20211. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20212. var duration = -1;
  20213. var animation = this.animationsMap[ name ];
  20214. if ( animation ) {
  20215. duration = animation.duration;
  20216. }
  20217. return duration;
  20218. };
  20219. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20220. var animation = this.animationsMap[ name ];
  20221. if ( animation ) {
  20222. animation.time = 0;
  20223. animation.active = true;
  20224. } else {
  20225. console.warn( "animation[" + name + "] undefined" );
  20226. }
  20227. };
  20228. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20229. var animation = this.animationsMap[ name ];
  20230. if ( animation ) {
  20231. animation.active = false;
  20232. }
  20233. };
  20234. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20235. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20236. var animation = this.animationsList[ i ];
  20237. if ( ! animation.active ) continue;
  20238. var frameTime = animation.duration / animation.length;
  20239. animation.time += animation.direction * delta;
  20240. if ( animation.mirroredLoop ) {
  20241. if ( animation.time > animation.duration || animation.time < 0 ) {
  20242. animation.direction *= -1;
  20243. if ( animation.time > animation.duration ) {
  20244. animation.time = animation.duration;
  20245. animation.directionBackwards = true;
  20246. }
  20247. if ( animation.time < 0 ) {
  20248. animation.time = 0;
  20249. animation.directionBackwards = false;
  20250. }
  20251. }
  20252. } else {
  20253. animation.time = animation.time % animation.duration;
  20254. if ( animation.time < 0 ) animation.time += animation.duration;
  20255. }
  20256. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20257. var weight = animation.weight;
  20258. if ( keyframe !== animation.currentFrame ) {
  20259. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20260. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20261. this.morphTargetInfluences[ keyframe ] = 0;
  20262. animation.lastFrame = animation.currentFrame;
  20263. animation.currentFrame = keyframe;
  20264. }
  20265. var mix = ( animation.time % frameTime ) / frameTime;
  20266. if ( animation.directionBackwards ) mix = 1 - mix;
  20267. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20268. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20269. }
  20270. };
  20271. /**
  20272. * @author mikael emtinger / http://gomo.se/
  20273. * @author alteredq / http://alteredqualia.com/
  20274. */
  20275. THREE.LensFlarePlugin = function ( ) {
  20276. var _gl, _renderer, _lensFlare = {};
  20277. this.init = function ( renderer ) {
  20278. _gl = renderer.context;
  20279. _renderer = renderer;
  20280. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20281. _lensFlare.faces = new Uint16Array( 6 );
  20282. var i = 0;
  20283. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20284. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20285. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20286. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20287. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20288. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20289. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20290. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20291. i = 0;
  20292. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20293. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20294. // buffers
  20295. _lensFlare.vertexBuffer = _gl.createBuffer();
  20296. _lensFlare.elementBuffer = _gl.createBuffer();
  20297. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20298. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20299. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20300. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20301. // textures
  20302. _lensFlare.tempTexture = _gl.createTexture();
  20303. _lensFlare.occlusionTexture = _gl.createTexture();
  20304. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20305. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20306. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20307. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20308. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20309. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20310. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20311. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20312. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20313. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20314. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20315. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20316. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20317. _lensFlare.hasVertexTexture = false;
  20318. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  20319. } else {
  20320. _lensFlare.hasVertexTexture = true;
  20321. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  20322. }
  20323. _lensFlare.attributes = {};
  20324. _lensFlare.uniforms = {};
  20325. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20326. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20327. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20328. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20329. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20330. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20331. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20332. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20333. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20334. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20335. _lensFlare.attributesEnabled = false;
  20336. };
  20337. /*
  20338. * Render lens flares
  20339. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20340. * reads these back and calculates occlusion.
  20341. * Then _lensFlare.update_lensFlares() is called to re-position and
  20342. * update transparency of flares. Then they are rendered.
  20343. *
  20344. */
  20345. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20346. var flares = scene.__webglFlares,
  20347. nFlares = flares.length;
  20348. if ( ! nFlares ) return;
  20349. var tempPosition = new THREE.Vector3();
  20350. var invAspect = viewportHeight / viewportWidth,
  20351. halfViewportWidth = viewportWidth * 0.5,
  20352. halfViewportHeight = viewportHeight * 0.5;
  20353. var size = 16 / viewportHeight,
  20354. scale = new THREE.Vector2( size * invAspect, size );
  20355. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20356. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20357. var uniforms = _lensFlare.uniforms,
  20358. attributes = _lensFlare.attributes;
  20359. // set _lensFlare program and reset blending
  20360. _gl.useProgram( _lensFlare.program );
  20361. if ( ! _lensFlare.attributesEnabled ) {
  20362. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20363. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20364. _lensFlare.attributesEnabled = true;
  20365. }
  20366. // loop through all lens flares to update their occlusion and positions
  20367. // setup gl and common used attribs/unforms
  20368. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20369. _gl.uniform1i( uniforms.map, 1 );
  20370. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20371. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20372. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20373. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20374. _gl.disable( _gl.CULL_FACE );
  20375. _gl.depthMask( false );
  20376. var i, j, jl, flare, sprite;
  20377. for ( i = 0; i < nFlares; i ++ ) {
  20378. size = 16 / viewportHeight;
  20379. scale.set( size * invAspect, size );
  20380. // calc object screen position
  20381. flare = flares[ i ];
  20382. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20383. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  20384. camera.projectionMatrix.multiplyVector3( tempPosition );
  20385. // setup arrays for gl programs
  20386. screenPosition.copy( tempPosition )
  20387. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20388. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20389. // screen cull
  20390. if ( _lensFlare.hasVertexTexture || (
  20391. screenPositionPixels.x > 0 &&
  20392. screenPositionPixels.x < viewportWidth &&
  20393. screenPositionPixels.y > 0 &&
  20394. screenPositionPixels.y < viewportHeight ) ) {
  20395. // save current RGB to temp texture
  20396. _gl.activeTexture( _gl.TEXTURE1 );
  20397. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20398. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20399. // render pink quad
  20400. _gl.uniform1i( uniforms.renderType, 0 );
  20401. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20402. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20403. _gl.disable( _gl.BLEND );
  20404. _gl.enable( _gl.DEPTH_TEST );
  20405. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20406. // copy result to occlusionMap
  20407. _gl.activeTexture( _gl.TEXTURE0 );
  20408. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20409. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20410. // restore graphics
  20411. _gl.uniform1i( uniforms.renderType, 1 );
  20412. _gl.disable( _gl.DEPTH_TEST );
  20413. _gl.activeTexture( _gl.TEXTURE1 );
  20414. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20415. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20416. // update object positions
  20417. flare.positionScreen.copy( screenPosition )
  20418. if ( flare.customUpdateCallback ) {
  20419. flare.customUpdateCallback( flare );
  20420. } else {
  20421. flare.updateLensFlares();
  20422. }
  20423. // render flares
  20424. _gl.uniform1i( uniforms.renderType, 2 );
  20425. _gl.enable( _gl.BLEND );
  20426. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  20427. sprite = flare.lensFlares[ j ];
  20428. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  20429. screenPosition.x = sprite.x;
  20430. screenPosition.y = sprite.y;
  20431. screenPosition.z = sprite.z;
  20432. size = sprite.size * sprite.scale / viewportHeight;
  20433. scale.x = size * invAspect;
  20434. scale.y = size;
  20435. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20436. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20437. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20438. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20439. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20440. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20441. _renderer.setTexture( sprite.texture, 1 );
  20442. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20443. }
  20444. }
  20445. }
  20446. }
  20447. // restore gl
  20448. _gl.enable( _gl.CULL_FACE );
  20449. _gl.enable( _gl.DEPTH_TEST );
  20450. _gl.depthMask( true );
  20451. };
  20452. function createProgram ( shader ) {
  20453. var program = _gl.createProgram();
  20454. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20455. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20456. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  20457. _gl.shaderSource( vertexShader, shader.vertexShader );
  20458. _gl.compileShader( fragmentShader );
  20459. _gl.compileShader( vertexShader );
  20460. _gl.attachShader( program, fragmentShader );
  20461. _gl.attachShader( program, vertexShader );
  20462. _gl.linkProgram( program );
  20463. return program;
  20464. };
  20465. };/**
  20466. * @author alteredq / http://alteredqualia.com/
  20467. */
  20468. THREE.ShadowMapPlugin = function ( ) {
  20469. var _gl,
  20470. _renderer,
  20471. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  20472. _frustum = new THREE.Frustum(),
  20473. _projScreenMatrix = new THREE.Matrix4(),
  20474. _min = new THREE.Vector3(),
  20475. _max = new THREE.Vector3();
  20476. this.init = function ( renderer ) {
  20477. _gl = renderer.context;
  20478. _renderer = renderer;
  20479. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20480. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20481. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20482. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20483. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  20484. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  20485. _depthMaterial._shadowPass = true;
  20486. _depthMaterialMorph._shadowPass = true;
  20487. _depthMaterialSkin._shadowPass = true;
  20488. _depthMaterialMorphSkin._shadowPass = true;
  20489. };
  20490. this.render = function ( scene, camera ) {
  20491. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  20492. this.update( scene, camera );
  20493. };
  20494. this.update = function ( scene, camera ) {
  20495. var i, il, j, jl, n,
  20496. shadowMap, shadowMatrix, shadowCamera,
  20497. program, buffer, material,
  20498. webglObject, object, light,
  20499. renderList,
  20500. lights = [],
  20501. k = 0,
  20502. fog = null;
  20503. // set GL state for depth map
  20504. _gl.clearColor( 1, 1, 1, 1 );
  20505. _gl.disable( _gl.BLEND );
  20506. _gl.enable( _gl.CULL_FACE );
  20507. _gl.frontFace( _gl.CCW );
  20508. if ( _renderer.shadowMapCullFrontFaces ) {
  20509. _gl.cullFace( _gl.FRONT );
  20510. } else {
  20511. _gl.cullFace( _gl.BACK );
  20512. }
  20513. _renderer.setDepthTest( true );
  20514. // preprocess lights
  20515. // - skip lights that are not casting shadows
  20516. // - create virtual lights for cascaded shadow maps
  20517. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  20518. light = scene.__lights[ i ];
  20519. if ( ! light.castShadow ) continue;
  20520. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  20521. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  20522. var virtualLight;
  20523. if ( ! light.shadowCascadeArray[ n ] ) {
  20524. virtualLight = createVirtualLight( light, n );
  20525. virtualLight.originalCamera = camera;
  20526. var gyro = new THREE.Gyroscope();
  20527. gyro.position = light.shadowCascadeOffset;
  20528. gyro.add( virtualLight );
  20529. gyro.add( virtualLight.target );
  20530. camera.add( gyro );
  20531. light.shadowCascadeArray[ n ] = virtualLight;
  20532. console.log( "Created virtualLight", virtualLight );
  20533. } else {
  20534. virtualLight = light.shadowCascadeArray[ n ];
  20535. }
  20536. updateVirtualLight( light, n );
  20537. lights[ k ] = virtualLight;
  20538. k ++;
  20539. }
  20540. } else {
  20541. lights[ k ] = light;
  20542. k ++;
  20543. }
  20544. }
  20545. // render depth map
  20546. for ( i = 0, il = lights.length; i < il; i ++ ) {
  20547. light = lights[ i ];
  20548. if ( ! light.shadowMap ) {
  20549. var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  20550. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  20551. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  20552. light.shadowMatrix = new THREE.Matrix4();
  20553. }
  20554. if ( ! light.shadowCamera ) {
  20555. if ( light instanceof THREE.SpotLight ) {
  20556. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  20557. } else if ( light instanceof THREE.DirectionalLight ) {
  20558. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  20559. } else {
  20560. console.error( "Unsupported light type for shadow" );
  20561. continue;
  20562. }
  20563. scene.add( light.shadowCamera );
  20564. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  20565. }
  20566. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  20567. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  20568. light.shadowCamera.add( light.cameraHelper );
  20569. }
  20570. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  20571. updateShadowCamera( camera, light );
  20572. }
  20573. shadowMap = light.shadowMap;
  20574. shadowMatrix = light.shadowMatrix;
  20575. shadowCamera = light.shadowCamera;
  20576. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  20577. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  20578. shadowCamera.updateMatrixWorld();
  20579. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  20580. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  20581. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  20582. // compute shadow matrix
  20583. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  20584. 0.0, 0.5, 0.0, 0.5,
  20585. 0.0, 0.0, 0.5, 0.5,
  20586. 0.0, 0.0, 0.0, 1.0 );
  20587. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  20588. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  20589. // update camera matrices and frustum
  20590. if ( ! shadowCamera._viewMatrixArray ) shadowCamera._viewMatrixArray = new Float32Array( 16 );
  20591. if ( ! shadowCamera._projectionMatrixArray ) shadowCamera._projectionMatrixArray = new Float32Array( 16 );
  20592. shadowCamera.matrixWorldInverse.flattenToArray( shadowCamera._viewMatrixArray );
  20593. shadowCamera.projectionMatrix.flattenToArray( shadowCamera._projectionMatrixArray );
  20594. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  20595. _frustum.setFromMatrix( _projScreenMatrix );
  20596. // render shadow map
  20597. _renderer.setRenderTarget( shadowMap );
  20598. _renderer.clear();
  20599. // set object matrices & frustum culling
  20600. renderList = scene.__webglObjects;
  20601. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20602. webglObject = renderList[ j ];
  20603. object = webglObject.object;
  20604. webglObject.render = false;
  20605. if ( object.visible && object.castShadow ) {
  20606. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  20607. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20608. webglObject.render = true;
  20609. }
  20610. }
  20611. }
  20612. // render regular objects
  20613. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20614. webglObject = renderList[ j ];
  20615. if ( webglObject.render ) {
  20616. object = webglObject.object;
  20617. buffer = webglObject.buffer;
  20618. // culling is overriden globally for all objects
  20619. // while rendering depth map
  20620. if ( object.customDepthMaterial ) {
  20621. material = object.customDepthMaterial;
  20622. } else if ( object instanceof THREE.SkinnedMesh ) {
  20623. material = object.geometry.morphTargets.length ? _depthMaterialMorphSkin : _depthMaterialSkin;
  20624. } else if ( object.geometry.morphTargets.length ) {
  20625. material = _depthMaterialMorph;
  20626. } else {
  20627. material = _depthMaterial;
  20628. }
  20629. if ( buffer instanceof THREE.BufferGeometry ) {
  20630. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  20631. } else {
  20632. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  20633. }
  20634. }
  20635. }
  20636. // set matrices and render immediate objects
  20637. renderList = scene.__webglObjectsImmediate;
  20638. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20639. webglObject = renderList[ j ];
  20640. object = webglObject.object;
  20641. if ( object.visible && object.castShadow ) {
  20642. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20643. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  20644. }
  20645. }
  20646. }
  20647. // restore GL state
  20648. var clearColor = _renderer.getClearColor(),
  20649. clearAlpha = _renderer.getClearAlpha();
  20650. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  20651. _gl.enable( _gl.BLEND );
  20652. if ( _renderer.shadowMapCullFrontFaces ) {
  20653. _gl.cullFace( _gl.BACK );
  20654. }
  20655. };
  20656. function createVirtualLight( light, cascade ) {
  20657. var virtualLight = new THREE.DirectionalLight();
  20658. virtualLight.isVirtual = true;
  20659. virtualLight.onlyShadow = true;
  20660. virtualLight.castShadow = true;
  20661. virtualLight.shadowCameraNear = light.shadowCameraNear;
  20662. virtualLight.shadowCameraFar = light.shadowCameraFar;
  20663. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  20664. virtualLight.shadowCameraRight = light.shadowCameraRight;
  20665. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  20666. virtualLight.shadowCameraTop = light.shadowCameraTop;
  20667. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20668. virtualLight.shadowDarkness = light.shadowDarkness;
  20669. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20670. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  20671. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  20672. virtualLight.pointsWorld = [];
  20673. virtualLight.pointsFrustum = [];
  20674. var pointsWorld = virtualLight.pointsWorld,
  20675. pointsFrustum = virtualLight.pointsFrustum;
  20676. for ( var i = 0; i < 8; i ++ ) {
  20677. pointsWorld[ i ] = new THREE.Vector3();
  20678. pointsFrustum[ i ] = new THREE.Vector3();
  20679. }
  20680. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20681. var farZ = light.shadowCascadeFarZ[ cascade ];
  20682. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  20683. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  20684. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  20685. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  20686. pointsFrustum[ 4 ].set( -1, -1, farZ );
  20687. pointsFrustum[ 5 ].set( 1, -1, farZ );
  20688. pointsFrustum[ 6 ].set( -1, 1, farZ );
  20689. pointsFrustum[ 7 ].set( 1, 1, farZ );
  20690. return virtualLight;
  20691. }
  20692. // Synchronize virtual light with the original light
  20693. function updateVirtualLight( light, cascade ) {
  20694. var virtualLight = light.shadowCascadeArray[ cascade ];
  20695. virtualLight.position.copy( light.position );
  20696. virtualLight.target.position.copy( light.target.position );
  20697. virtualLight.lookAt( virtualLight.target );
  20698. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20699. virtualLight.shadowDarkness = light.shadowDarkness;
  20700. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20701. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20702. var farZ = light.shadowCascadeFarZ[ cascade ];
  20703. var pointsFrustum = virtualLight.pointsFrustum;
  20704. pointsFrustum[ 0 ].z = nearZ;
  20705. pointsFrustum[ 1 ].z = nearZ;
  20706. pointsFrustum[ 2 ].z = nearZ;
  20707. pointsFrustum[ 3 ].z = nearZ;
  20708. pointsFrustum[ 4 ].z = farZ;
  20709. pointsFrustum[ 5 ].z = farZ;
  20710. pointsFrustum[ 6 ].z = farZ;
  20711. pointsFrustum[ 7 ].z = farZ;
  20712. }
  20713. // Fit shadow camera's ortho frustum to camera frustum
  20714. function updateShadowCamera( camera, light ) {
  20715. var shadowCamera = light.shadowCamera,
  20716. pointsFrustum = light.pointsFrustum,
  20717. pointsWorld = light.pointsWorld;
  20718. _min.set( Infinity, Infinity, Infinity );
  20719. _max.set( -Infinity, -Infinity, -Infinity );
  20720. for ( var i = 0; i < 8; i ++ ) {
  20721. var p = pointsWorld[ i ];
  20722. p.copy( pointsFrustum[ i ] );
  20723. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  20724. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  20725. if ( p.x < _min.x ) _min.x = p.x;
  20726. if ( p.x > _max.x ) _max.x = p.x;
  20727. if ( p.y < _min.y ) _min.y = p.y;
  20728. if ( p.y > _max.y ) _max.y = p.y;
  20729. if ( p.z < _min.z ) _min.z = p.z;
  20730. if ( p.z > _max.z ) _max.z = p.z;
  20731. }
  20732. shadowCamera.left = _min.x;
  20733. shadowCamera.right = _max.x;
  20734. shadowCamera.top = _max.y;
  20735. shadowCamera.bottom = _min.y;
  20736. // can't really fit near/far
  20737. //shadowCamera.near = _min.z;
  20738. //shadowCamera.far = _max.z;
  20739. shadowCamera.updateProjectionMatrix();
  20740. }
  20741. };
  20742. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  20743. /**
  20744. * @author mikael emtinger / http://gomo.se/
  20745. * @author alteredq / http://alteredqualia.com/
  20746. */
  20747. THREE.SpritePlugin = function ( ) {
  20748. var _gl, _renderer, _sprite = {};
  20749. this.init = function ( renderer ) {
  20750. _gl = renderer.context;
  20751. _renderer = renderer;
  20752. _sprite.vertices = new Float32Array( 8 + 8 );
  20753. _sprite.faces = new Uint16Array( 6 );
  20754. var i = 0;
  20755. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  20756. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  20757. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  20758. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  20759. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  20760. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  20761. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  20762. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  20763. i = 0;
  20764. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  20765. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  20766. _sprite.vertexBuffer = _gl.createBuffer();
  20767. _sprite.elementBuffer = _gl.createBuffer();
  20768. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  20769. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  20770. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  20771. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  20772. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  20773. _sprite.attributes = {};
  20774. _sprite.uniforms = {};
  20775. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  20776. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  20777. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  20778. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  20779. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  20780. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  20781. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  20782. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  20783. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  20784. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  20785. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  20786. _sprite.uniforms.affectedByDistance = _gl.getUniformLocation( _sprite.program, "affectedByDistance" );
  20787. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  20788. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  20789. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  20790. _sprite.attributesEnabled = false;
  20791. };
  20792. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20793. var sprites = scene.__webglSprites,
  20794. nSprites = sprites.length;
  20795. if ( ! nSprites ) return;
  20796. var attributes = _sprite.attributes,
  20797. uniforms = _sprite.uniforms;
  20798. var invAspect = viewportHeight / viewportWidth;
  20799. var halfViewportWidth = viewportWidth * 0.5,
  20800. halfViewportHeight = viewportHeight * 0.5;
  20801. var mergeWith3D = true;
  20802. // setup gl
  20803. _gl.useProgram( _sprite.program );
  20804. if ( ! _sprite.attributesEnabled ) {
  20805. _gl.enableVertexAttribArray( attributes.position );
  20806. _gl.enableVertexAttribArray( attributes.uv );
  20807. _sprite.attributesEnabled = true;
  20808. }
  20809. _gl.disable( _gl.CULL_FACE );
  20810. _gl.enable( _gl.BLEND );
  20811. _gl.depthMask( true );
  20812. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  20813. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20814. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20815. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  20816. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  20817. _gl.activeTexture( _gl.TEXTURE0 );
  20818. _gl.uniform1i( uniforms.map, 0 );
  20819. // update positions and sort
  20820. var i, sprite, screenPosition, size, scale = [];
  20821. for( i = 0; i < nSprites; i ++ ) {
  20822. sprite = sprites[ i ];
  20823. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  20824. if( ! sprite.useScreenCoordinates ) {
  20825. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld );
  20826. sprite.z = - sprite._modelViewMatrix.elements[14];
  20827. } else {
  20828. sprite.z = - sprite.position.z;
  20829. }
  20830. }
  20831. sprites.sort( painterSort );
  20832. // render all sprites
  20833. for( i = 0; i < nSprites; i ++ ) {
  20834. sprite = sprites[ i ];
  20835. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  20836. if ( sprite.map && sprite.map.image && sprite.map.image.width ) {
  20837. if ( sprite.useScreenCoordinates ) {
  20838. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  20839. _gl.uniform3f( uniforms.screenPosition, ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  20840. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  20841. Math.max( 0, Math.min( 1, sprite.position.z ) ) );
  20842. } else {
  20843. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  20844. _gl.uniform1i( uniforms.affectedByDistance, sprite.affectedByDistance ? 1 : 0 );
  20845. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  20846. }
  20847. size = sprite.map.image.width / ( sprite.scaleByViewport ? viewportHeight : 1 );
  20848. scale[ 0 ] = size * invAspect * sprite.scale.x;
  20849. scale[ 1 ] = size * sprite.scale.y;
  20850. _gl.uniform2f( uniforms.uvScale, sprite.uvScale.x, sprite.uvScale.y );
  20851. _gl.uniform2f( uniforms.uvOffset, sprite.uvOffset.x, sprite.uvOffset.y );
  20852. _gl.uniform2f( uniforms.alignment, sprite.alignment.x, sprite.alignment.y );
  20853. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20854. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20855. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20856. _gl.uniform2fv( uniforms.scale, scale );
  20857. if ( sprite.mergeWith3D && !mergeWith3D ) {
  20858. _gl.enable( _gl.DEPTH_TEST );
  20859. mergeWith3D = true;
  20860. } else if ( ! sprite.mergeWith3D && mergeWith3D ) {
  20861. _gl.disable( _gl.DEPTH_TEST );
  20862. mergeWith3D = false;
  20863. }
  20864. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20865. _renderer.setTexture( sprite.map, 0 );
  20866. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20867. }
  20868. }
  20869. // restore gl
  20870. _gl.enable( _gl.CULL_FACE );
  20871. _gl.enable( _gl.DEPTH_TEST );
  20872. _gl.depthMask( true );
  20873. };
  20874. function createProgram ( shader ) {
  20875. var program = _gl.createProgram();
  20876. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20877. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20878. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  20879. _gl.shaderSource( vertexShader, shader.vertexShader );
  20880. _gl.compileShader( fragmentShader );
  20881. _gl.compileShader( vertexShader );
  20882. _gl.attachShader( program, fragmentShader );
  20883. _gl.attachShader( program, vertexShader );
  20884. _gl.linkProgram( program );
  20885. return program;
  20886. };
  20887. function painterSort ( a, b ) {
  20888. return b.z - a.z;
  20889. };
  20890. };/**
  20891. * @author alteredq / http://alteredqualia.com/
  20892. */
  20893. THREE.DepthPassPlugin = function ( ) {
  20894. this.enabled = false;
  20895. this.renderTarget = null;
  20896. var _gl,
  20897. _renderer,
  20898. _depthMaterial, _depthMaterialMorph,
  20899. _frustum = new THREE.Frustum(),
  20900. _projScreenMatrix = new THREE.Matrix4();
  20901. this.init = function ( renderer ) {
  20902. _gl = renderer.context;
  20903. _renderer = renderer;
  20904. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20905. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20906. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20907. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20908. _depthMaterial._shadowPass = true;
  20909. _depthMaterialMorph._shadowPass = true;
  20910. };
  20911. this.render = function ( scene, camera ) {
  20912. if ( ! this.enabled ) return;
  20913. this.update( scene, camera );
  20914. };
  20915. this.update = function ( scene, camera ) {
  20916. var i, il, j, jl, n,
  20917. program, buffer, material,
  20918. webglObject, object, light,
  20919. renderList,
  20920. fog = null;
  20921. // set GL state for depth map
  20922. _gl.clearColor( 1, 1, 1, 1 );
  20923. _gl.disable( _gl.BLEND );
  20924. _renderer.setDepthTest( true );
  20925. // update scene
  20926. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  20927. // update camera matrices and frustum
  20928. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  20929. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  20930. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  20931. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  20932. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  20933. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  20934. _frustum.setFromMatrix( _projScreenMatrix );
  20935. // render depth map
  20936. _renderer.setRenderTarget( this.renderTarget );
  20937. _renderer.clear();
  20938. // set object matrices & frustum culling
  20939. renderList = scene.__webglObjects;
  20940. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20941. webglObject = renderList[ j ];
  20942. object = webglObject.object;
  20943. webglObject.render = false;
  20944. if ( object.visible ) {
  20945. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  20946. //object.matrixWorld.flattenToArray( object._modelMatrixArray );
  20947. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  20948. webglObject.render = true;
  20949. }
  20950. }
  20951. }
  20952. // render regular objects
  20953. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20954. webglObject = renderList[ j ];
  20955. if ( webglObject.render ) {
  20956. object = webglObject.object;
  20957. buffer = webglObject.buffer;
  20958. if ( object.material ) _renderer.setMaterialFaces( object.material );
  20959. if ( object.customDepthMaterial ) {
  20960. material = object.customDepthMaterial;
  20961. } else if ( object.geometry.morphTargets.length ) {
  20962. material = _depthMaterialMorph;
  20963. } else {
  20964. material = _depthMaterial;
  20965. }
  20966. if ( buffer instanceof THREE.BufferGeometry ) {
  20967. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  20968. } else {
  20969. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  20970. }
  20971. }
  20972. }
  20973. // set matrices and render immediate objects
  20974. renderList = scene.__webglObjectsImmediate;
  20975. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20976. webglObject = renderList[ j ];
  20977. object = webglObject.object;
  20978. if ( object.visible && object.castShadow ) {
  20979. /*
  20980. if ( object.matrixAutoUpdate ) {
  20981. object.matrixWorld.flattenToArray( object._modelMatrixArray );
  20982. }
  20983. */
  20984. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  20985. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  20986. }
  20987. }
  20988. // restore GL state
  20989. var clearColor = _renderer.getClearColor(),
  20990. clearAlpha = _renderer.getClearAlpha();
  20991. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  20992. _gl.enable( _gl.BLEND );
  20993. };
  20994. };
  20995. /**
  20996. * @author mikael emtinger / http://gomo.se/
  20997. *
  20998. */
  20999. THREE.ShaderFlares = {
  21000. 'lensFlareVertexTexture': {
  21001. vertexShader: [
  21002. "uniform vec3 screenPosition;",
  21003. "uniform vec2 scale;",
  21004. "uniform float rotation;",
  21005. "uniform int renderType;",
  21006. "uniform sampler2D occlusionMap;",
  21007. "attribute vec2 position;",
  21008. "attribute vec2 uv;",
  21009. "varying vec2 vUV;",
  21010. "varying float vVisibility;",
  21011. "void main() {",
  21012. "vUV = uv;",
  21013. "vec2 pos = position;",
  21014. "if( renderType == 2 ) {",
  21015. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21016. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21017. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21018. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21019. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21020. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21021. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21022. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21023. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21024. "vVisibility = ( visibility.r / 9.0 ) *",
  21025. "( 1.0 - visibility.g / 9.0 ) *",
  21026. "( visibility.b / 9.0 ) *",
  21027. "( 1.0 - visibility.a / 9.0 );",
  21028. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21029. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21030. "}",
  21031. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21032. "}"
  21033. ].join( "\n" ),
  21034. fragmentShader: [
  21035. "precision mediump float;",
  21036. "uniform sampler2D map;",
  21037. "uniform float opacity;",
  21038. "uniform int renderType;",
  21039. "uniform vec3 color;",
  21040. "varying vec2 vUV;",
  21041. "varying float vVisibility;",
  21042. "void main() {",
  21043. // pink square
  21044. "if( renderType == 0 ) {",
  21045. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21046. // restore
  21047. "} else if( renderType == 1 ) {",
  21048. "gl_FragColor = texture2D( map, vUV );",
  21049. // flare
  21050. "} else {",
  21051. "vec4 texture = texture2D( map, vUV );",
  21052. "texture.a *= opacity * vVisibility;",
  21053. "gl_FragColor = texture;",
  21054. "gl_FragColor.rgb *= color;",
  21055. "}",
  21056. "}"
  21057. ].join( "\n" )
  21058. },
  21059. 'lensFlare': {
  21060. vertexShader: [
  21061. "uniform vec3 screenPosition;",
  21062. "uniform vec2 scale;",
  21063. "uniform float rotation;",
  21064. "uniform int renderType;",
  21065. "attribute vec2 position;",
  21066. "attribute vec2 uv;",
  21067. "varying vec2 vUV;",
  21068. "void main() {",
  21069. "vUV = uv;",
  21070. "vec2 pos = position;",
  21071. "if( renderType == 2 ) {",
  21072. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21073. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21074. "}",
  21075. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21076. "}"
  21077. ].join( "\n" ),
  21078. fragmentShader: [
  21079. "precision mediump float;",
  21080. "uniform sampler2D map;",
  21081. "uniform sampler2D occlusionMap;",
  21082. "uniform float opacity;",
  21083. "uniform int renderType;",
  21084. "uniform vec3 color;",
  21085. "varying vec2 vUV;",
  21086. "void main() {",
  21087. // pink square
  21088. "if( renderType == 0 ) {",
  21089. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21090. // restore
  21091. "} else if( renderType == 1 ) {",
  21092. "gl_FragColor = texture2D( map, vUV );",
  21093. // flare
  21094. "} else {",
  21095. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21096. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21097. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21098. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21099. "visibility = ( 1.0 - visibility / 4.0 );",
  21100. "vec4 texture = texture2D( map, vUV );",
  21101. "texture.a *= opacity * visibility;",
  21102. "gl_FragColor = texture;",
  21103. "gl_FragColor.rgb *= color;",
  21104. "}",
  21105. "}"
  21106. ].join( "\n" )
  21107. }
  21108. };
  21109. /**
  21110. * @author mikael emtinger / http://gomo.se/
  21111. *
  21112. */
  21113. THREE.ShaderSprite = {
  21114. 'sprite': {
  21115. vertexShader: [
  21116. "uniform int useScreenCoordinates;",
  21117. "uniform int affectedByDistance;",
  21118. "uniform vec3 screenPosition;",
  21119. "uniform mat4 modelViewMatrix;",
  21120. "uniform mat4 projectionMatrix;",
  21121. "uniform float rotation;",
  21122. "uniform vec2 scale;",
  21123. "uniform vec2 alignment;",
  21124. "uniform vec2 uvOffset;",
  21125. "uniform vec2 uvScale;",
  21126. "attribute vec2 position;",
  21127. "attribute vec2 uv;",
  21128. "varying vec2 vUV;",
  21129. "void main() {",
  21130. "vUV = uvOffset + uv * uvScale;",
  21131. "vec2 alignedPosition = position + alignment;",
  21132. "vec2 rotatedPosition;",
  21133. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21134. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21135. "vec4 finalPosition;",
  21136. "if( useScreenCoordinates != 0 ) {",
  21137. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21138. "} else {",
  21139. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21140. "finalPosition.xy += rotatedPosition * ( affectedByDistance == 1 ? 1.0 : finalPosition.z );",
  21141. "}",
  21142. "gl_Position = finalPosition;",
  21143. "}"
  21144. ].join( "\n" ),
  21145. fragmentShader: [
  21146. "precision mediump float;",
  21147. "uniform vec3 color;",
  21148. "uniform sampler2D map;",
  21149. "uniform float opacity;",
  21150. "varying vec2 vUV;",
  21151. "void main() {",
  21152. "vec4 texture = texture2D( map, vUV );",
  21153. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21154. "}"
  21155. ].join( "\n" )
  21156. }
  21157. };